Hello, I'm a beginner at Java and trying to get to know programming and one day work my way up developing android apps. Well I was trying make this program that would read in data from a txt file like this:
[img]http://i42.tinypic.com/2vvkokj.png[/img]
I wanted the firstname, lastname, id# and dob each to have their own variables and then only to have the lastname and dob be printed to an outputfile(that the user would name) like this:
[img]http://i44.tinypic.com/sfgjkl.png[/img]
so I decided the best way to do that would be in arrays. I ran into a problem during my first for loop after the trybox where it says that the first array has no source so I tried to move the for loop to include the trybox and that still wouldn't work..
I received these errors:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at HealthDriver.main(HealthDriver.java:38)
After commenting out some code I took out the forloop completely and I just in left the arrays initialized to [0] and it worked until the 2nd for loop and would instead give me the trybox exception error message(in the 2nd trybox)...Could anyone tell me what's wrong here? or maybe someone has an idea how to do this without arrays?
Any tips, nudges in the right direction, constructive criticism is welcomed. Thank you all in advanced. :D!
import java.util.*;
import java.io.*; //Include header
public class HealthDriver {
public static void main(String[] args) {
String writeword; //used to write filename to outputfile
String[] aryfirst = new String[4];
String[] arylast= new String[4];
int[] aryid = new int[4];
String[] arydob = new String[4];
//Prompt to enter in data.
System.out.printf("Please enter in the name of the file: ");
Scanner s = new Scanner(System.in);
//Reads in the string name for the file.
writeword = s.next();
//Reads in from the file Patient.txt
String filename = "Patient.txt";
Scanner sf = null;
try
{
sf = new Scanner(new FileReader(filename));
}
catch (Exception e)
{
System.out.printf("ERROR...There is no Patient.txt");
}
//Loop that reads each piece of data from txt and arranges them in each array.
int i = 0;
for (i = 0; i <=4; i++)
{
aryfirst[i] = sf.next();
arylast[i] = sf.next();
aryid[i] = sf.nextInt();
arydob[i] = sf.next();
}
//Declare a PrintStream variable
PrintStream ps=null;
try
{
//This creates a new file or wipes the old one. Based on what user types
ps = new PrintStream(writeword);
//Loop that should print out each last name and date of birth..
for (i = 0; i <=4; i++)
{
ps.printf("%-20s", arylast[i]);
ps.printf("%15d", arydob[i]);
}
/*
aryfirst[i] = sf.next();
arylast[i] = sf.next();
aryid[i] = sf.nextInt();
arydob[i] = sf.next();
ps.printf("%-20s", lastname);
*/
//ps.printf("%15d", dateofbirth);
}
catch (Exception e)
{
System.out.println("ERROR! Something went WRONG!");
}
}
}