Java: searching a string array from a CSV file - java

I am new at Java so please bear with me.
I need help for one of my assignments again. Now it involves FileI/O.
The task that I have to do is:
I have to read a .csv file. The values that's inside the file are:
Christopher Lee,54.0
Stanley Wright,90.5
Oliver Stewart,75.8
Jessica Chang,34.65
As the task said, I must store the contents on the file into two arrays. One for the names, and one for the test marks. I should read the file at least twice, once to check how many names are in the file and a couple more times to actually read the file (to get the names and marks). So basically, I should have an array to store the names as Strings, and an array to store the marks of the student as real numbers.
I should line up the arrays (e.g.students[0] should store the name of the first student and marks[0] should store the mark of the first student
After I stored the contents of the .csv file into an array I have to display a following menu to the user. If the user pressed 1, it should prompt the user to enter the name of a student. If the user pressed 2, the program should exit. If the name exists, it should display the test mark for the student entered. If the student does not exist then I must output a message indicating so to the user, yet the program should not end but return to the above menu.
This is my code so far:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String fileName = "file:///Documents/Java/marks_file.csv"; // Opens the file
String[] arrayString = new String[6]; // String length inside the file
int numLines, selection = 0;
double[] arrayReal = new double[6]; // Number length inside the file
numLines = getNumLines(fileName); // Gets the length of the file
readFile(arrayString, arrayReal, fileName);
// Selection menu
do
{
System.out.println("Select an option:");
System.out.println("1. Display mark");
System.out.println("2. Exit");
selection = sc.nextInt();
if (selection == 1)
{
System.out.println("Enter your full name");
{
// Do something
}
}
else if (selection == 2)
{
System.out.println("Goodbye");
}
}
while (selection == 1);
//System.out.println("Number of arrays: " + numLines);
}
// Method to get the length of the .csv file
public static int getNumLines(String fileName)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
lineNum = lineNum + 1;
line = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
return lineNum;
}
// Method to store the values to arrays
public static void readFile(String[] arrayString, double[] arrayReal, String fileName)
{
Scanner sc = new Scanner(System.in);
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
for (int i = 0; i < arrayString.length; i++)
{
line = bufRdr.readLine();
arrayString[i] = processString(line);
arrayReal[i] = processReal(line);
}
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
// Stores the String lines to array
public static String processString(String line)
{
String string;
String[] lineArray = line.split(",");
return string = lineArray[0];
}
// Stores real number lines to array
public static double processReal(String line)
{
double real;
String[] lineArray = line.split(",");
return real = Double.parseDouble(lineArray[1]);
}
So far, I finished the "reading the file" part and processing the contents from a .csv file to an array.
I am not too sure how to prompt a user to search a string array from a .csv file. I tried looking at other sources, even at this website but I have no luck at all. I tried the Scanner.next() method but that doesn't work at all. Maybe I just missed something. Also, I am not sure if I did the "reading the file twice" right.
Am I on the right track? I am need of some guidance here

First of all I want to say that I'd use a Map instead of two arrays but I'll show you a solution using two arrays.
You were close to the solution. One of you problems is that scanner.next() only reads the input until the first whitespace. That's why you need to use scanner.nextLine(). This method reads the complete line. And the code could look something like that:
Solution with two arrays
Scanner sc = new Scanner(System.in);
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
for(int i = 0; i < arrayString.length; i++){
if(name.equals(arrayString[i])) {
System.out.println(arrayReal[i]);
}
}
Solution with a HashMap
Initialize HashMap
HashMap<String, Double> hm = new HashMap<String, Double>();
Fill HashMap
hm.put("Christopher Lee", 54.0);
Print double value of student
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
System.out.println(hm.get(name));

Instead of storing into arrays, I would rather tell you to pass the data to data into generic arraylist and then query the result using get() method.

You are making simple thing difficult.
Just use a HashMap with name as the keys and test-score as the values.
You open file
You read each line and translate each line to an entry of hash map
When a text is input to the console, you just get it from hash map, if existed return the value, if not then back to number 3

Related

Scanner for input file and storing data objects from input file in array

Basically, I had to create a scanner for a given file and read through the file (the name is input through the terminal by the user) once counting the number of lines in the file. Then after, I had to create an array of objects from the file, of the correct size (where the num of lines comes in). Then I had to create another scanner for the file and read through it again, storing it in the array I created. And lastly, had to return the array in the method.
My problem is I cannot seem to get the second scanner to actually store the file objects in the array.
I've tried using .nextLine inside a for loop that also calls the array, but it doesn't seem to be working.
public static Data[] getData(String filename) {
Scanner input = new Scanner(new File(filename));
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
System.out.println(count);
Data[] data = new Data[count];
Scanner input1 = new Scanner(new File(filename));
while (input1.hasNextLine()) {
for (int i = 0; i < count; i++) {
System.out.println(data[i].nextLine);
}
}
return data;
}
I expect the output to successfully read the input file so that it can be accessed by other methods that I have created (not shown).
You should definitely use an IDE if you don't have one, try intellij... There you have autocompletion and syntax checking and much more.
It is not clear what you want to do in your for loop, because there are several mistakes, for example the readline() function works only with the scanner objekt, so you can do input.nextline() or input1.nextline()`...
so I just show you, how you can get the Data from a file with Scanner:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Readfile {
public static void getData(String filename) throws FileNotFoundException {
ArrayList<String> test = new ArrayList<>(); //arraylist to store the data
Scanner inputSc = new Scanner(new File(filename)); //scanner of the file
while (inputSc.hasNextLine()) {
String str = inputSc.nextLine();
System.out.println(str); //print the line which was read from the file
test.add(str); //adds the line to the arraylist
//for you it would be something like data[i] = str; and i is a counter
}
inputSc.close();
}
public static void main(String[] args) {
try {
getData("/home/user/documents/bla.txt"); //path to file
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You don't need to read thru the file twice - just use an ArrayList to hold the data that's coming in from the file, like this, and then return Data[] at the end:
public static Data[] getData(String filename) {
List<Data> result = new ArrayList<>();
try (Scanner input = new Scanner(new File(filename))){
while (input.hasNextLine()) {
Data data = new Data(input.nextLine());
result.add(data);
}
}
return result.toArray(new Data[0]);
}
Not clear what Data.class do you mean, if you switch it to String, the problem obviously would be in this line
System.out.println(data[i].nextLine);
if you want to assign and print simultaneously write this
for (int i = 0; i < count; i++) {
data[i] = input1.next();
System.out.println(data[i]);
}
and dont forget to close your Scanners, better use try-with-resources.
If your Data is your custom class you'd better learn about Serialization-Deserialization
Or use some ObjectMapper-s(Jackson, for example) to store your class instances and restore them.
Your way of opening the file just to count the lines and then again looping through its lines to store them in the array is not that efficient, but it could be just a school assignment.
Try this:
public static Data[] getData(String filename) {
Scanner input = null;
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
input.close();
System.out.println(count);
Data[] data = new Data[count];
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
for (int i = 0; i < count; i++) {
Data d = new Data(input.nextLine(), 0, 0);
data[i] = d;
System.out.println(data[i].name);
}
input.close();
return data;
}
After the 1st loop you must close the Scanner and reopen it so to start all over from the first line of the file.

Getting values from LinkedList according to user input

Facing some issues with my lab codes
I've done trouble shooting to find that both there's nothing wrong with my filereader/bufferedreaders, Vehicle method and LinkedList values
I'm found out that I'm having Problems getting the if statement to work
I do not know How do I compare the current linkedlist data extracted from my file.txt using tokenizer to pass into given fields with userinput using if/else ?
Main method
package test6;
// import packages
import java.util.LinkedList;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Lab6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Declare variables for reading file
FileReader fr = null;
BufferedReader br = null;
String inFile = "Vehicle_Records.txt";
final String INPUT_PROMPT = "\nPlease enter the search word " + "that you would like to obtain more information on:";
String line;
StringTokenizer tokenizer;
// Declare variables to contain the record fields
String group;
String brand;
String model;
double rate;
// Declare and instantiate a new LinkedList
LinkedList<Vehicle> list = new LinkedList<Vehicle>();
try {
// Instantiate FileReader & BufferedReader objects
fr = new FileReader(inFile);
br = new BufferedReader(fr);
//read a line from the file
line = br.readLine();
// While line is not null
while (line != null) {
// Tokenize the records
tokenizer = new StringTokenizer(line, ",");
group = tokenizer.nextToken();
brand = tokenizer.nextToken();
model = tokenizer.nextToken();
rate = Double.parseDouble(tokenizer.nextToken());
// Create a new Vehicle object of the record
Vehicle newVehicle = new Vehicle(group, brand, model, rate);
System.out.println(newVehicle);
// Add this item object into the LinkedList
list.add(newVehicle);
// Read another line from file
line = br.readLine();
}
// Close BufferedReader
br.close();
}
catch (FileNotFoundException e)
{
System.out.println("The file" + inFile + "was not found");
}
catch (IOException e)
{
System.out.println("Reading error!" + e);
}
finally
{
//Check if FileReader is opened
if (fr != null) {
try {
//close FileReader
fr.close();
} catch (IOException e) {
System.out.println("Error closing file!");
}
}
}
// Print out the input prompt
System.out.println(INPUT_PROMPT);
try
{
// Create readers to read from user input
//FileReader ufr = new FileReader(INPUT_PROMPT);
BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));
// Read one line from user input
String uline=ubr.readLine();
// Loop through all the records in the LinkedList
for(int i = 0; i< list.size(); i++)
{
// if the record is the same as the input from user
// (Hint: use contains() in String class to check whether
// search word is found in the records
String temp = new String(uline);
if(list.get(i)== uline.contains(temp))
{
//print out the information of the vehicle that match user input
System.out.println(list.get(i));
}
}
}
catch(IOException e)
{
System.out.println(e);
}
catch (Exception e)
{
System.out.println("Input error!" + e);
}
}
}//main
Vehical Class
package lab6;
public class Vehicle {
// Declare all the variables to contain the fields of a record
String group;
String brand;
String model;
double rate;
// Creates a constructor to store all the fields into the variables
public Vehicle(String group, String brand, String model, double rate)
{
this.group=group; this.brand=brand; this.model=model; this.rate=rate;
}
// Create a toString() method to return string in the same delimited
// format as the input record
public String toString()
{
return(group+","+brand+","+model+","+rate);
}
}
Your code is not inside a method , so you are facing a problem.
I assume since your looking through vehicle objects trying to find a match of one its four variables. Your approach is wrong since you're comparing an object with a String.
Instead you could use a Comparable interface inside the Vehicle class where you would simply compare multiple strings.
Edit:
public class Vehicle implements Comparable<String>{
/* This method returns 0 if the search matches
* Else it return a negative or a positive number*/
#Override
public int compareTo(String o) {
int cmp = this.getBrand().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
cmp = this.getGroup().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
cmp = this.getModel().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
/* Edited this part to work with doubles */
try{
cmp = (int)(this.getRate() - Double.parseDouble(o));
}
catch(NumberFormatException e){
return cmp;
}
return cmp;
}
}
And here is how you would loop through it:
for(int i = 0; i< list.size(); i++){
if(list.get(i).compareTo(uline) == 0)
{
System.out.println(list.get(i));
}
}
Hope it help.
PS. I'm also new to this :)
AAAAAAAND I FINALLY FIGURED IT OUT TOGETHER WITH MY OTHER FRIEND
Still, I'd love to thank all of you for extending a hand to help me :')
Shall post the solution to my problem here
//-etc-
// Create readers to read from user input
//FileReader ufr = new FileReader(INPUT_PROMPT);
BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));
// Read one line from user input
String uline=ubr.readLine();
// Loop through all the records in the LinkedList
for(int i = 0; i< list.size(); i++)
{
// if the record is the same as the input from user
// (Hint: use contains() in String class to check whether
// search word is found in the records
Vehicle vehicle = list.get(i);
if(vehicle.group.contains(uline) ||
vehicle.brand.contains(uline) ||
vehicle.model.contains(uline))
{
//print out the information of the vehicle that match user input
System.out.println(list.get(i));
}

Trying to save a clone of an array in a txt file but returns NULL

I am making an app that keeps username and scores from a game in a txt file. The concept is that when it writes a new username and score to the txt file it should open the .txt file, read it and then make a clone of it adding a new uername and score entry in the txt file.
I am thinking of making this with 2 object arrays. The first is the one that is read in and the new will be the one is writen which will have one more entry.
So if player[i] is readen player[i+1] should be writen with new entry.
I am giving u the code below!
private Player[] myplayer=null;
private Player[] mynewplayer=null;
//open Players.txt
int i;
int n;
String filename="players.txt";
try
{
FileReader fp=new FileReader(filename);
BufferedReader bf=new BufferedReader(fp);
n=Integer.parseInt(bf.readLine());
myplayer=new Player[n];
int x=n+1;
mynewplayer=new Player[x];
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
bf.close();
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
n=myplayer.length;
try
{
filename="players.txt";
FileWriter fp=new FileWriter(filename);
fp.write(""+n+"\n");
for(i=0;i<n+1;i++)
fp.write(""+mynewplayer[i]+"\n");
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s="";
for(i=0;i<mynewplayer.length;i++)
s=s+mynewplayer[i]+"\n";
JOptionPane.showMessageDialog(null,"Players are \n "+s);
Problem is that when it's written, it returns null for mynewplayer.
I suppose the mynewplayer doesnt really take the entries of the "myplayer" but neither writes the new username.
Compile doesnt show any errors. Just writes NULL to the textfile.
Ask me if u want further info on the code writen!
Thanks in advance!
Here is an edited version of your code, with some improvements and there should be a comment around code that I changed, explaining what I did.
Player[] myPlayer = null; // first word uncapitalized, every
Player[] myNewPlayer = null; // other word begins with a capital
//open Players.txt
int i, n; // combine the variables into 1 line
String filename = "players.txt";
try {
FileReader fp = new FileReader(filename);
BufferedReader bf = new BufferedReader(fp);
n = Integer.parseInt(bf.readLine());
// not needed
//myPlayer = new Player[n];
// NOT NEEDED int x = n + 1;
myNewPlayer = new Player[n + 1];
for (i = 0; i < n; i++) {
String s = bf.readLine();
String user, score; // combine variables, doesnt need to initalize them
String[] items = s.split(","); // Splits the line into array elements on every delimiter -> ,
//user = s.substring(0, s.indexOf(","));
//s = s.substring(s.indexOf(",") + 1);
//score = s;
user = items[0];
score = items[1];
// this line below isnt actually needed
//myPlayer[i] = new Player(user, Double.parseDouble(score));
// Create a new player clone, dont copy the previous one
myNewPlayer[i] = new Player(user, Double.parseDouble(score));
}
// We've read all the variables from the text file, now we create the last one
// Since myNewPlayer is (n+1) size, the range of the array is
// 0 to n
// the last index will be n New Score Variable
myNewPlayer[n] = new Player("Username variable", Double.parseDouble("22"));
bf.close();
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
// This is called a ternary operator
// it is a 1 line if statement
// the format is like so
// booleanLogic ? trueAnswer Execution : falseAnswer Execution;
// if () { true }else { false }
n = myNewPlayer != null ? myNewPlayer.length : 0;
// CHANGED HERE - was using the first array rather than second
// dont need the 1st array
try {
filename = "players.txt";
FileWriter fp = new FileWriter(filename);
// Dont need "" before the items
fp.write(n + "\n");
for (i = 0; i < n; i++) {
fp.write(myNewPlayer[i] + "\n");
}
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s = "";
for (i = 0; i < myNewPlayer.length; i++) {
// s += ""; is like doing s = s + "";
s += myNewPlayer[i] + "\n";
}
JOptionPane.showMessageDialog(null, "Players are \n " + s);
I believe that your problem is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
You have nested loops, which is fine, but they use the same counter (the variable i ).
So what is happening is the first line of the file is read, and then added to myplayer[0]. However, instead of just also adding it to mynewplayer[0], you start another loop on i. This loop:
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
is going to copy the first player into mynewplayer[0]...and then null into every other entry (since myplayer only has the firsdt element filled.
The problem is that after that loop completes, i will equal n, so when you get back to the top of the outer loop, the check $i
Perhaps what you should do is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
mynewplayer[i]= new Player(user,Double.parseDouble(score));
}
mynewplayer[x]=new Player(<the new username>,Double.parseDouble(<the new score>));

Loading elements of Array into a collection

I have a text file of names( last and first). I have successfully been able to use RandomAccessFile class to load all the names into an Array of strings. What is left for me to do, is to assign each of the first names to an Array of first names and each of the last names in the list to an array of Last Names. Here is what I did but Im not getting any desired result.
public static void main(String[] args) {
String fname = "src\\workshop7\\customers.txt";
String s;
String[] Name;
String[] lastName, firstName;
String last, first;
RandomAccessFile f;
try {
f = new RandomAccessFile(fname, "r");
while ((s = f.readLine()) != null) {
Name = s.split("\\s");
System.out.println(Arrays.toString(Name));
for (int i = 0; i < Name.length; i++) {
first = Name[0];
last = Name[1];
System.out.println("last Name: " + last + "First Name: "+ first);
}
}
f.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Please help me out I seem to be confused on what kind of collection to use and how to go about it Thanks
You could create a method to read a file and put the data in an Array, but, if you are determined to use an Array you are going to have to create it at a fixed size b/c arrays are immutable in java
public class tmp {
public static void main(String[] args) throws FileNotFoundException {
//problem you have to create an array of fixed size
String[] array = new String[4];
readLines(array);
}
public static String[] readLines(String[] lines) throws FileNotFoundException {
//this counter can be printed to check the size of your array
int count = 0; // number of array elements with data
// Create a File class object linked to the name of the file to read
java.io.File myFile = new java.io.File("path/to/file.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(myFile);
/* This while loop reads lines of text into an array. it uses a Scanner class
* boolean function hasNextLine() to see if there another line in the file.
*/
while (infile.hasNextLine()) {
// read a line and put it in an array element
lines[count] = infile.nextLine();
count++; // increment the number of array elements with data
} // end while
infile.close();
return lines;
}
}
However, the preferred method is to use an ArrayList which is an object that uses dynamically resizing arrays as data is added. In other words, you don't need to worry about having different size text files.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("path/of/file.txt"));
String str;
ArrayList<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
A little about random access.
Classes like BufferedReader and FileInputStream use a sequential process of reading or writing data. RandomAccess, on the other hand, does exactly as the name implies, which is to permit non-sequential, random access to the contents of a file. However, Random access is typically used for other applications like reading and writing to zip files. Unless you have speed concerns I would recommend using the other classes.
public static void main(String[] args) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader("src\\workshop7\\customers.txt"));
String str;
String names[];
List<String> firstName = new ArrayList();
List<String> lastName = new ArrayList();
try {
while ((str = in.readLine()) != null) {
names = str.split("\\s");
int count = 0;
do{
firstName.add(names[count]);
lastName.add(names[count+1]);
count = count + 2;
}while(count < names.length);
}
} catch (IOException e) {
e.printStackTrace();
}
// do whatever with firstName list here
System.out.println(firstName);
// do whatever with LastName list here
System.out.println(lastName);
}

Read integers from txt file and storing into an array

I'm having issues reading and storing only integers from a text file. I'm using a int array so I want to do this without list. I'm getting a input mismatch exception, and I don't know how I should go about correcting that issue. The text files being read from also include strings.
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
int i = 0;
//connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
//If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
//if connected, read file
if(inputFile != null){
System.out.print("number of integers in file \""
+ filename + "\" = \n");
//loop through file for integers and store in array
while (inputFile.hasNext()) {
array[i] = inputFile.nextInt();
i++;
}
inputFile.close();
}
return array;
}
You might use something like this (to skip over any non-int(s)), and you should close your Scanner!
// if connected, read file
if (inputFile != null) {
System.out.print("number of integers in file \""
+ filename + "\" = \n");
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
} else {
inputFile.next();
}
}
} finally {
inputFile.close();
}
// I think you wanted to print it.
System.out.println(i);
for (int v = 0; v < i; v++) {
System.out.printf("array[%d] = %d\n", v, array[v]);
}
}
Change hasNext() to hasNextInt() in your while loop.
What you need to do is before you get a new value and try to put it into the array you need to check to make sure that it is in fact an int and if it isn't then skip over it and move on to the next value. Alternately you could make a string array of all of the values and then copy only the integers into a separate array. However, the first solution is probably the better of the two.
Also... As has been mentioned in the comments it tends to be easier to read the integers in as strings and then parse the values from them...

Categories

Resources