Hey there pretty new to Java I have a CSV file that I am scanning line by line (I am assuming) and printing out the details formatted. I keep getting a java.lang.ArrayIndexOutOfBoundsException: 1 what could I be doing wrong?
Here is the CSV file contents.
1,Mazda CX-9,7,Automatic,Premium,150
2,VW Golf,5,Automatic,Standard,59
3,Toyota Corolla,5,Automatic,Premium,55
4,VW Tiguan,7,Automatic,Premium,110
5,Ford Falcon,5,Manual,Standard,60
String fileName = "CarList.CSV";
File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
carsAvailableCount++;
String line = input.nextLine();
int lenght = line.length();
String fields[] = line.split(",");
String carNo = fields[0];
String carName = fields[1];
String seats = fields[2];
String transmission = fields[3];
String carType = fields[4];
String rate = fields[5];
System.out.format("%-9s%-9s%-9s%-9s%-9s%-9s\n", carNo, carName, seats, transmission, carType, rate);
}
Figured out the problem haha, my CSV file had empty lines below my last entry. Cheers everyone.
Related
I am working on a program that takes in a text file and converts it to a team roster. The text file has unknown length, first name, last name, offence score, and defense score. the name and scores are on the same line. Rachael Adams 3.36 1.93. I can not figure out how to convert each line of the text file into an object. I've searched the internet and all of the examples just have one value per a line and converts it into one big array. I've included some extra imports in the code because i know that I will need them further on in the project(find best attackers, best defenders, make teams of 6, print teams). I've modified code from previous projects that took in numbers separated by lines.
class VolleyballFile {
String fileName;
int count;
String currentFileName;
String outputFile="";
String firstName;
String lastName;
double attackScore;
double defenceScore;
Scanner input = new Scanner(System.in);
public VolleyballFile() throws FileNotFoundException {
System.out.println("Please enter a file name to get the roster from");
this.fileName = input.nextLine();
File file = new File(fileName);
Scanner scan = new Scanner(file);
while (scan.hasNextLine()){
int result = Integer.parseInt(scan.nextLine());
this.count+=1;
}
}
}
Using the command String.split(); you can split a string up to an array of strings. So:
while (scan.hasNextLine()) {
//int result = Integer.parseInt(scan.nextLine());
string[] line = scan.nextLine().split(" ");
firstName = string[0];
lastName = string[1];
attackScore = Float.Parse(string[2]);
defenceScore = Float.Parse(string[3]);
this.count+=1;
}
I'm not sure if you can Float.Parse(), don't remember since I haven't used java recently.
I am trying to create an object for each line of text and as each object is created, place it into an array. I'm struggling to place it into an array. This is my code:
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
Shareholder shareholder = new Shareholder();
while (inputFile.hasNext()) {
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder.setID(tokens[0]);
shareholder.setName(tokens[1]);
shareholder.setAddress(tokens[2]);
shareholder.setPortfolioID(tokens[3]);
}
If you have a fixed number of shareholders, you can do this -
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
int i=0;
Shareholder[] shareholder = new Shareholder[n];
while (inputFile.hasNext()) {
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder[i++] = new Shareholder(tokens[0],tokens[1],tokens[2],tokens[3]);
}
Or if dont know the number of shareholders, then you can use list -
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
List<Shareholder> list = new ArrayList<>();
while (inputFile.hasNext()) {
Shareholder shareholder = new Shareholder();
str = inputFile.nextLine();
String tokens[] = str.split(",");
list.add(new Shareholder(tokens[0],tokens[1],tokens[2],tokens[3]));
}
I think a list of shareholder objects might make the most sense here:
File inFile = new File("shareholders.txt");
Scanner inputFile = new Scanner(inFile);
String str;
List<Shareholder> list = new ArrayList<>();
while (inputFile.hasNext()) {
Shareholder shareholder = new Shareholder();
str = inputFile.nextLine();
String tokens[] = str.split(",");
shareholder.setID(tokens[0]);
shareholder.setName(tokens[1]);
shareholder.setAddress(tokens[2]);
shareholder.setPortfolioID(tokens[3]);
list.add(shareholder);
}
The reason a list makes sense here is because you might not know how many shareholders are present in the input file. Hence, an array might not work so well in this case (and even if the number of shareholders were fixed it could change at some later date).
Before reading the file, you can not know how many lines the file has.
The information about the number of lines is important to initialize your array with that specific size or otherwise you would need to extend your array multiple times by creating a new, bigger one. Which is bad practice and bad performance.
But instead of working with an array itself, use an arraylist for easier usage and just return a simple array, which can be received from the arraylist you worked with.
My suggestion as a solution for this issue is the following. Please note that the following code is not 100% complete and will not run in it's state. It is your job to complete it and make it run.
public void readFileIntoArray(String filename, Shareholder[] targetArray)
{
File sourceFile = new File(filename);
// Read in the file to determine the number of lines (int numberOfLines)
ArrayList<Shareholder> lines = new ArrayList<>(numberOfLines);
Shareholder sh;
while(file.hasNext())
{
sh = new Shareholder();
//Parse data into Shareholderobject
lines.add(sh);
}
return lines.toArray();
}
I am working on a project that involves asking a user for their zip code. Using the zip code provided the program should loop through a .csv file to determine what city they live in. I can read the information in the .csv file but I have no idea how to loop through it to find a specific piece of information.
import java.util.Scanner;
import java.io.*;
public class DetermineCity {
public static void main(String[] args) throws IOException {
String zip = "99820,AK,ANGOON";
Scanner keyboard = new Scanner(System.in);
System.out.println("enter then name of a file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is ");
System.out.println(line);
inputFile.close();
}
}
Use Scanner.hasNext() method to loop
String Details="";
int ZipCodeIndex=0;
String ZipCode = "10230"
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext()){
String x=inputFile.nextLine();
String[] arr=x.split(",");
if(ZipCode.equals(arr[ZipCodeIndex]))
{
Details=x;
break;
}
}
This assumes the format of your file is of the form "2301,Suburb, City, Country"
the .nextLine() function returns a String of the next line, however return null if their isn't a line. So using a while loop you can go through your file and store each line in a string.
Then using .split() method you would break this string using a delimiter ",". This would be stored in an array.
Then compare the user zip code with the first value of the array. If they match then you have an array with the city and other information. Then a break statement as you have found the city.
String suburb;
String[] lineArray;
String line = null;
while((line = inputFile.nextLine()) != null){
lineArray[] = line.split(",");
if(lineArray[0] == zipCodeString){
suburb = lineArray[1];
break;
}
}
I am having trouble with a programming assignment. I need to read data from a txt file and store it in parallel arrays. The txt file contents are formatted like this:
Line1: Stringwith466numbers
Line2: String with a few words
Line3(int): 4
Line4: Stringwith4643numbers
Line5: String with another few words
Line6(int): 9
Note: The "Line1: ", "Line2: ", etc is just for display purposes and isn't actually in the txt file.
As you can see it goes in a pattern of threes. Each entry to the txt file is three lines, two strings and one int.
I would like to read the first line into an array, the second into another, and the third into an int array. Then the fourth line would be added to the first array, the 5th line to the second array and the 6th line into the third array.
I have tried to write the code for this but can't get it working:
//Create Parallel Arrays
String[] moduleCodes = new String[3];
String[] moduleNames = new String[3];
int[] numberOfStudents = new int[3];
String fileName = "myfile.txt";
readFileContent(fileName, moduleCodes, moduleNames, numberOfStudents);
private static void readFileContent(String fileName, String[] moduleCodes, String[] moduleNames, int[] numberOfStudents) throws FileNotFoundException {
// Create File Object
File file = new File(fileName);
if (file.exists())
{
Scanner scan = new Scanner(file);
int counter = 0;
while(scan.hasNext())
{
String code = scan.next();
String moduleName = scan.next();
int totalPurchase = scan.nextInt();
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
}
}
The above code doesn't work properly. When I try to print out an element of the array. it returns null for the string arrays and 0 for the int arrays suggesting that the code to read the data in isn't working.
Any suggestions or guidance much appreciated as it's getting frustrating at this point.
The fact that only null's get printed suggests that the file doesn't exist or is empty (if you print it correctly).
It's a good idea to put in some checking to make sure everything is fine:
if (!file.exists())
System.out.println("The file " + fileName + " doesn't exist!");
Or you can actually just skip the above and also take out the if (file.exists()) line in your code and let the FileNotFoundException get thrown.
Another problem is that next splits things by white-space (by default), the problem is that there is white-space on that second line.
nextLine should work:
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.parseInt(scan.nextLine());
Or, changing the delimiter should also work: (with your code as is)
scan.useDelimiter("\\r?\\n");
You are reading line so try this:
while(scan.hasNextLine()){
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.pasreInt(scan.nextLine().trim());
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = scan.nextInt();
scan.nextLine()
This will move scanner to proper position after reading int.
i am working on a program to read a binary file and update it form a txt file, it was working the all of a sudden it started throwing this error
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at StockManage.updateInv(StockManage.java:134)
at StockManage.main(StockManage.java:173)
heres the code thats causes the error
try
{
Scanner trans = new Scanner(new File(file));
RandomAccessFile inv = new RandomAccessFile (file2,"rws");
String tempName = "Temp" + (int)(Math.random()*1000000) + ".dat";
RandomAccessFile newInv = new RandomAccessFile (tempName , "rws");
File newFile = new File(tempName);
String transISBN = trans.next();
String author = inv.readUTF();
String title = inv.readUTF();
String iSBN = inv.readUTF();
int amount = inv.readInt();
while (inv.getFilePointer()<=inv.length())
{
boolean empty = true;
while (empty&&trans.hasNext())
{
if (iSBN.compareTo(transISBN)<0)
{
empty = false;
break;
}
else if (iSBN.compareTo(transISBN)==0)
{
int change = trans.nextInt();
amount += change;
transISBN = trans.next();
}
}
newInv.writeUTF(author);
newInv.writeUTF(title);
newInv.writeUTF(iSBN);
newInv.writeInt(amount);
author = inv.readUTF();
title = inv.readUTF();
iSBN = inv.readUTF();
amount = inv.readInt();
}
im really stuck in this one so any help would be great
Before calling next() on a Scanner object you should call hasNext() to check if there is actually more data to read.
This code part is error-prone:
else if (iSBN.compareTo(transISBN)==0)
{
int change = trans.nextInt();
amount += change;
transISBN = trans.next();
}
You control trans.hasNext() in the while loop, but you don't before transISBN = trans.next(); put an if(trans.hasNext()) at the top of it and problem will be solved, I guess.