This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I have my program which reads from a txt file, then turns txt information into a car object and adds them to an arraylist.
try {
String filePath = "car.txt";
File f = new File(filePath);
Scanner sc = new Scanner(f);
List<Car> car = new ArrayList<Car>();
while(sc.hasNextLine()){
String newLine = sc.nextLine();
String[] details = newLine.split(" ");
String brand = details[0];
String model = details[1];
double cost = Double.parseDouble(details[2]);
Car c = new Car(brand, model, cost);
Car.add(c);
}
However, If a line from the txt file does not contain the three components then it crashes. How would I check if the line contains all 3 components, if not print a message then terminate?
Stack trace -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Main.loadPerson(Main.java:31)
at Main.main(Main.java:12)
You need to check for the length of details is 3, if not exit as shown below:
String[] details = newLine.split(" ");
if(details.length != 3) {
System.out.println("Incorrect data entered !! Please try again !!! ");
return;
} else {
String brand = details[0];
String model = details[1];
double cost = Double.parseDouble(details[2]);
Car c = new Car(brand, model, cost);
Car.add(c);
}
You can check the length of return array from split by:
int count = details.length;
and then decide what to do
check length before accessing elements,
try the pattern \\s+ to avoid trimming spaces, there is a typo in your code where adding Car to car list
while (sc.hasNextLine()) {
String newLine = sc.nextLine();
String[] details = newLine.split("\\s+");
if (details.length == 3) {
String brand = details[0];
String model = details[1];
double cost = Double.parseDouble(details[2]);
Car c = new Car(brand, model, cost);
car.add(c);
} else {
System.out.println("Invalid input");
}
}
If the file doesn't contain the 3 components, then details will be empty. use this instead.
if(details.length() != 3){
System.out.println("Invalid .txt file!");
break;
}
Related
I've written a class for a program designed to help manage a volleyball team's roster. The roster is contained in a .dat file and the players are written as follows:
Rachael Adams 3.36 1.93
My issue arises when I try to separate this string into the proper data types (the name being a string, then the first and second values being doubles for the stats).
public Roster(String filename) {
players = new ArrayList<Player>();
try {
FileReader fr = new FileReader(filename);
BufferedReader inFile = new BufferedReader (fr);
String line = inFile.readLine();
Scanner scan = new Scanner(line);
while(line != null) {
String firstName = scan.next();
String lastName = scan.next();
double attackStat = scan.nextDouble();
double blockStat = scan.nextDouble();
String name = firstName + " " + lastName;
Player newPlayer = new Player(name, attackStat, blockStat);
players.add(newPlayer);
line = inFile.readLine();
}
scan.close();
inFile.close();
} catch (IOException e) {
System.out.println(e);
}
}
The program throws this exception when a Roster object is created
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Roster.<init>(Roster.java:30)
at Assignment08.openRosterFile(Assignment08.java:59)
at Assignment08.main(Assignment08.java:18)
I am newer to Java and still facing a learning curve, so if there is more information needed then please let me know.
If at all possible, I would greatly appreciate an explanation as to what I did wrong rather than just a solution. Thank you very much.
I always find it easier to split the line:
String[] columns = line.split(" (?=\\d)";
String name = columns[0];
double attackStat = Double.parseDouble(columns[1]);
double blockStat = Double.parseDouble(columns[2]);
This works by splitting on a space, but only when the next char is a digit via the look ahead (?=\d).
This automatically caters for any number of words in the name.
This question already has answers here:
Read CSV with Scanner()
(8 answers)
Closed 5 years ago.
I am attempting to read from a .csv file for my program but we have never read from a .csv file before in my class. I'm not quite sure how to go about it, but this is my attempt so far. I imagine that I am missing some kind of loop that loops through every line of the file but I am not sure how to go about doing that.
Bank bank = new Bank();
Scanner infile = new Scanner("C:/Users/Josh/Desktop/prog5input.csv");
Scanner s2 = new Scanner(infile.nextLine());
int accountType = 0;
String accountHolder = "";
double accountInitial = 0.0;
double accountRate = 0.0;
System.out.println("Program 5, Josh Correia, cssc0491");
System.out.println("Creating accounts...");
s2.useDelimiter(",");
if (s2.hasNextInt()) accountType = s2.nextInt();
if (s2.hasNext()) accountHolder = s2.next();
if (s2.hasNextDouble()) accountInitial = s2.nextDouble();
if (s2.hasNextDouble()) accountRate = s2.nextDouble();
bank.addNewAccount(new SavingsAccount(accountHolder, accountInitial, accountRate));
This is the file that I am reading from:
1,Waterford Ellingsworth, 4350.0, 0.002
2,Bethanie Treadwell, 500.0, 0.35
3,Ira Standish, 50000, 0.1, 59, 0.1
4,Debi Cardashian, 5100, 0.0
File file = new File("C:/Users/Josh/Desktop/prog5input.csv");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
String str = sc.nextLine();
String[] arr = str.split(",");
int accountType = Integer.valueOf(((String)arr[0]).trim());
......
}
You can refer to this link about other ways to read file.
you could set it to an actual String and then to a ArrayList via the spilt method :
String str = " ";
ArrayList<String> elephantList = Arrays.asList(str.split(","));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i got a code that i am implementing from another but i get the error of Java ArrayIndexOutofBoundsException can someone help me? I am not sure of what to do it might be the codes that trigger the error
the data in the file is
Username|HashedPassword|no.of chips
code is below
public static void DeletePlayer()throws IOException{
File inputFile = new File("players.dat");
File tempFile = new File ("temp.dat");
BufferedReader read = new BufferedReader(new FileReader(inputFile));
BufferedWriter write = new BufferedWriter(new FileWriter(tempFile));
ArrayList<String> player = new ArrayList<String>();
try {
String line;
Scanner reader = new Scanner(System.in);
System.out.println("Please Enter Username:");
String UserN = reader.nextLine();
System.out.println("Please Enter Chips to Add:");
String UserCadd = reader.nextLine();
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
Integer totalChips = (Integer.parseInt(UserCadd) + Integer.parseInt(Chips));
if(Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
write.write("\r\n"+line);
}
}
read.close();
write.close();
inputFile.delete();
tempFile.renameTo(inputFile);
main(null);
}catch (IOException e){
System.out.println("fail");
}
}
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
It seems that your details array has only one or two elements. The moment, you try to get something from the array, for an index that is out of (the existing) range, that Exception is thrown.
Are you sure your file doesn't end with an empty line ?
add the line:
System.out.println("length: " + details.length);
right after your split method, or print out all the element of the details array, that will tell you how many elements there are, and how many times you try to do this for which values.
In this code:
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
//...
}
You must check if the user input is at the expected format, in your case,
joe|g00d|12
The minimal check is to have 3 elements separated by |. e.g.
while((line = read.readLine()) != null){
String[] details = line.split("\\|");
if (details.length != 3) {
System.out.println("Bad input, try agains...");
continue;
}
String Username = details[0];
String Password = details[1];
String Chips = details[2];
//...
}
Note that you should String#trim() your inputs in order to strip leading and ending whitespaces (this allows an input like joe | g00d | 123), and you still can have an error when parsing the number of chips which has to be an integer. I would also certainly check that.
I am writing a method that will take in some command line arguments, validate them and if valid will edit an airport's code. The airport name and it's code are stored in a CSV file. An example is "Belfast,BHD". The command line arguments are entered as follows, java editAirport EA BEL Belfast, "EA" is the 2letter code that makes the project know that I want to Edit the code for an Airport, "BEL" is the new code, and Belfast is the name of the Airport.
When I have checked through the cla's and validated them I read through the file and store them in an ArrayList as, "Belfast,BEL". Then I want to update the text file by removing the lines from the text file and dumping in the arraylist, but I cannot figure out how to do it. Can someone show me a way using simple code (no advanced java stuff) how this is possible.
Here is my program
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class editAirport
{
public static void main(String [] args)throws IOException
{
String pattern = "[A-Z]{3}";
String line, line1, line2;
String[] parts;
String[] parts1;
boolean found1 = false, found2 = false;
File file = new File("Airports.txt"); // I created the file using the examples in the outline
Scanner in = new Scanner(file);
Scanner in1 = new Scanner(file);
Scanner in2 = new Scanner(file);
String x = args[0], y = args[1], z = args[2];
//-------------- Validation -------------------------------
if(args.length != 3) // if user enters more or less than 3 CLA's didplay message
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(file.exists())) // if "Airports.txt" doesn't exist end program
JOptionPane.showMessageDialog(null, "Airports.txt does not exist");
else // if everything is hunky dory
{
if(!(x.equals("EA"))) //if user doesn't enter EA an message will be displayed
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(y.matches(pattern))) // If the code doesn't match the pattern a message will be dislayed
JOptionPane.showMessageDialog(null, "Airport Code is invalid");
while(in.hasNext())
{
line = in.nextLine();
parts = line.split(",");
if(y.equalsIgnoreCase(parts[1]))
found1 = true; //checking if Airport code already is in use
if(z.equalsIgnoreCase(parts[0]))
found2 = true; // checking if Airport name is in the file
}
if(found1)
JOptionPane.showMessageDialog(null, "Airport Code already exists, Enter a different one.");
else if(found2 = false)
JOptionPane.showMessageDialog(null, "Airport Name not found, Enter it again.");
else
/*
Creating the ArrayList to store the name,code.
1st while adds the names and coses to arraylist,
checks if the name of the airport that is being edited is in the line,
then it adds the new code onto the name.
sorting the arraylist.
2nd for/while is printing the arraylist into the file
*/
ArrayList<String> airport = new ArrayList<String>();
while(in1.hasNext()) // 1st while
{
line1 = in1.nextLine();
if(line1.contains(z))
{
parts1 = line1.split(",");
parts1[1] = y;
airport.add(parts1[0] + "," + parts1[1]);
}
else
airport.add(line1);
}
Collections.sort(airport); // sorts arraylist
FileWriter aFileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(aFileWriter);
for(int i = 0; i < airport.size();)
{
while(in2.hasNext()) // 2nd while
{
line2 = in2.nextLine();
line2 = airport.get(i);
output.println(line2);
i++;
}
}
output.close();
aFileWriter.close();
}
}
}
}
The Airports.txt file is this
Aberdeen,ABZ
Belfast City,BHD
Dublin,DUB
New York,JFK
Shannon,SNN
Venice,VCE
I think your problem may lie in the two lines:
line2 = in2.nextLine();
line2 = airport.get(i);
this will overwrite the 'line2' in memory, but not in the file.
This question already has answers here:
Java - delete line from text file by overwriting while reading it
(3 answers)
Closed 8 years ago.
I have this file
1007 book1 5 3
1004 book2 4 1
1003 book3 3 0
1002 book4 2 1
and I am trying to delete the book number 1004 from the file, but before that I let the user enter the number of the book that he wants to delete.
First check if the book exists in the file or not, if the book is exists I delete it if not show "the book does not exists".
Scanner kb = new Scanner(System.in);
FileInputStream book = new FileInputStream("input.txt");
Scanner infile = new Scanner(book);
FileOutputStream out = new FileOutputStream("output.txt");
PrintWriter pw = new PrintWriter(out);
boolean found = false;
System.out.print("Enter the bookID : ");
int bID = kb.nextInt();
while(infile.hasNext()){
int id = infile.nextInt();
String title = infile.next();
int quantity = infile.nextInt();
int bQuantity = infile.nextInt();
if(bID == id){
found = true;
}
if(found == true){
pw.printf("%8d\t%-30s\t%8d\t%8d", infile.nextInt(), infile.next(), infile.nextInt(), infile.nextInt());
infile.nextLine();
System.out.println("The book has been deleted");
break;
}
}
if(found == false)
System.out.print("Not found");
pw.close();
infile.close();
I am trying to print all the file with out the book I have deleted.
You will need a book class, like this:
public class Book {
private int series;
private String name;
private int intA;
private int intB;
public Book(int series,String name, int intA, int intB) {
this.series = series;
this.name = name;
this.intA = intA;
this.intB = intB;
}
....
.... (add other methods as needed, you will definitely need a
toString() method, and getIntA(), getIntB(), getSeriesNum(),
getName() etc.)
}
When you use scanner to read the file, read them into an arraylist of type Book. When user enter a number, use a for loop to find the Book that matches that number, and remove that book object from your arraylist.
Also, try to keep data in memory and not write files too often. Writing files to disks is very inefficient comparing with changing data in memory. Once user is done with all his/her operations, you can use a printwriter to write the data to your file.
To read your file into this array of objects, you can do this:
public static ArrayList<Book> readbooklist() {
ArrayList<Book> booklist = new ArrayList<Book>();
File file = new File("path/filename.fileextension");
try {
Scanner scnr = new Scanner(file);
while (scnr.hasNextLine()) {
String entry = scnr.nextLine();
String [] parts = entry.split("\t"); // Depends on how data was delimited
int series = Integer.parseInt(parts[0]);
int intA = Integer.parseInt(parts[2]);
int intB = Integer.parseInt(parts[3]);
Book single = new Book(series, parts[1], intA, intB);
booklist.add(single);
}
scnr.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
}
return booklist;
}
Remember to import proper dependency at the beginning of your class. Wish it helps!
I'd recommend to use a Map to store each line as value and the Id as the key only once. That way you don't have to reopen the file and read it each time you want to remove or add an entry, all you have to do is remove it and add it to the map. Once you are done, you can overwrite the old file you have by the values stored in the map or just create a new temp file to hold the data, delete the old file and then rename the temp file with old file's name
Store all the lines you would like to save in a String and close the scanner. Create a printwriter, print the string to the file and close it.
Example code:
File file = new File("yourTextFile.txt");
Scanner in = new Scanner(file);
String saveThisToFile = "";
while (in.hasNext()) {
String temp = in.nextLine();
if (condition to be true if you whant to keep this line) {
saveThisToFile += temp + "\n";
}
}
in.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.print(saveThisToFile);
printWriter.close();