Java Error ArrayIndexOutofBounds [closed] - java

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.

Related

Trying to use java to read a csv file and choose specific rows/columns

I've been trying to make a java program that reads a CSV file with random names in it.Each row has a name, their relation to another name(father, sibling etc)and the name they're related to, all seperated with "," .My program can currently read the whole file and show everything in it.What I'm trying to do is have the user be able to write 2 names and, if they're in the same row, see their relation.So far it doesn't work.In my code below you can see that I made it so if the 2 name inputs(name1 and name2)match with names inside to do that sout command to show their relation, but the sout never happens.No error either, after giving input to the 2 names the program just finishes.
String csvF = "C:\\file.csv";
String line = "";
String csvSplitBy = ",";
try (BufferedReader b = new BufferedReader(new FileReader(csvF))) {
Scanner input = new Scanner(System.in);
System.out.println("Please write the first name");
String name1 = input.nextLine();
Scanner input2 = new Scanner(System.in);
System.out.println("Now please write the second name");
String name2 = input2.nextLine();
while ((line = b.readLine()) != null) {
String[] s = line.split(csvSplitBy);
if (name1 == s[0] && name2 == s[2]) {
System.out.println(name1 + "is" + s[2] + "to/of" + name2);
}
}
} catch (IOException e) {
e.printStackTrace();
} } }
After finally testing this, I am pretty sure that the line…
if (name1 == s[0] && name2 == s[2])
is failing because the == is comparing the string name1 with the “address” of s[0]… not s[0]'s contents. Change the line to the code below and it should work.
if (name1.equals(s[0]) && name2.equals(s[2])) { …

How can I remove specific elements from a linkedlist in java based on user input?

I'm very new (6 weeks into java) trying to remove elements from a csv file that lists a set of students as such (id, name, grades) each on a new line.
Each student id is numbered in ascending value. I want to try and remove a student by entering the id number and I'm not sure how I can do this.
So far I've just tried to reduce the value that user inputs to match the index as students are listed by number and I did this in a while loop. However, each iteration doesn't recognize the reduction from the previous user Input, and I think I need a way that can just search the value of the id, and remove the entire line from the csv file.
Have only tried to include the pertinent code. Reading previous stack questions has shown me a bunch of answers related to nodes, which make no sense to me since I don't have whatever prerequisite knowledge is required to understand it, and I'm not sure the rest of my code is valid for those methods.
Any ideas that are relatively simple?
Student.txt (each on a new line)
1,Frank,West,98,95,87,78,77,80
2,Dianne,Greene,78,94,88,87,95,92
3,Doug,Lei,78,94,88,87,95,92
etc....
Code:
public static boolean readFile(String filename) {
File file = new File("C:\\Users\\me\\eclipse-workspace\\studentdata.txt");
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
String[] words=scanner.nextLine().split(",");
int id = Integer.parseInt(words[0]);
String firstName = words[1];
String lastName = words[2];
int mathMark1 = Integer.parseInt(words[3]);
int mathMark2 = Integer.parseInt(words[4]);
int mathMark3 = Integer.parseInt(words[5]);
int englishMark1 = Integer.parseInt(words[6]);
int englishMark2 = Integer.parseInt(words[7]);
int englishMark3 = Integer.parseInt(words[8]);
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3);
}scanner.close();
}catch (FileNotFoundException e) {
System.out.println("Failed to readfile.");
private static void removeStudent() {
String answer = "Yes";
while(answer.equals("Yes") || answer.equals("yes")) {
System.out.println("Do you wish to delete a student?");
answer = scanner.next();
if (answer.equals("Yes") || answer.equals("yes")) {
System.out.println("Please enter the ID of the student to be removed.");
//tried various things here: taking userInput and passing through linkedlist.remove() but has never worked.
This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);

displaying data from .txt file [closed]

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 4 years ago.
Improve this question
need help, i want to display the name of the person who just logged in, here is my login code
public void Masuk(){
try {
String lokasi = "D:/settings.txt";
String username = txtUser.getText();
String password = txtPass.getText();
FileReader fr = new FileReader(lokasi);
BufferedReader br = new BufferedReader(fr);
String line, user, pass;
boolean isLoginSuccess = false;
while ((line = br.readLine()) != null) {
user = line.split(" ")[1].toLowerCase();
pass = line.split(" ")[2].toLowerCase();
if (user.equals(username) && pass.equals(password)) {
isLoginSuccess = true;
this.dispose();
new Main_Menu(this, rootPaneCheckingEnabled).show();
break;
}
}
if (!isLoginSuccess) {
JOptionPane.showMessageDialog(null, "USERNAME/PASSWORD WRONG", "WARNING!!", JOptionPane.WARNING_MESSAGE);
}
fr.close();
}catch(Exception e){
e.printStackTrace();
}
}
the login is in form, i used JDialog to dipslay the name of the person who just logged in(MainMenu), here is my MainMenu code right now
public void Berhasil(){
String data = "D:/Settings.txt";
try {
FileReader fr = new FileReader(data);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine(),nama;
nama = line.split(" ")[0].toLowerCase();
String message = "Selamat datang "+ nama;
String text;
while ((line = br.readLine()) != null)
txtBerhasil.setText(""+message);
}
catch (FileNotFoundException fnfe) {
fnfe.getMessage();
}
catch (IOException ioe) {
ioe.getMessage();
}
}
the .txt file looks like this
Name Username Password
i only want to write the name of the person who just logged in
I'm assuming you want to read some text (the user's information) from a text file. There are several ways to do it. This is one way:
File file = new File("path/to/file.txt");
Scanner sc = new Scanner(file);
String thisLine = null;
while (sc.hasNextLine()){
thisLine = sc.nextLine();
}
Now you can do whatever you want with thisLine. Say you want the first word in the first line:
String[] words = thisLine.split(" ");
System.out.println(words[0]);
This would print the first word in the first line of your txt file. I used space as the separator but it actually depends on what separator you used in yout txt file when you were saving the info. For instance, you may want to use "\t" if tab was used as the separator.

Error handling when reading from txt file [duplicate]

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;
}

how to ask the user to enter account number and then return his balance from a text file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a text file that has two columns, one for account numbers and the other for balances.
I would like to ask the user for his account number and get his balance from the text.
I have methods like deposit and withdraw, which I want to apply to the balances of the user, and then update the text file. What is the best way to do it?
Should I use an array? or there are easier ways to do?
The text file would be like this
1001 50.67
1002 500.32
1003 63.63
1004 953.53
1005 735.22
Using an array is not a practical approach to this problem. I made a sample program that does the above without an array. To make this run, make sure your account file is names BankAccounts.txt
import java.io.*;
import java.util.*;
public class BankAccount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
File dir = new File("BankAccounts.txt");
System.out.println("Please enter your bank account number.");
String bankNumber = input.nextLine();
input.close();
System.out.println("Your Balance is: "
+ balanceFromAccount(bankNumber, dir));
}
public static String balanceFromAccount(String accountNumber, File file) {
String tempNumber = "";
int i;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
for (i = 0; line.charAt(i) != ' '; i++) {
tempNumber = tempNumber.concat(line.substring(i, i + 1));
}
if (tempNumber.equals(accountNumber)) {
return line.substring(i + 1);
}
tempNumber = "";
}
br.close();
} catch (Exception e) {
}
return "Not Found!";
}
}
This program simply opens the file, finds each bank account number, checks if it is the desired one, then it returns the value if it is. If not, it says "Not Found!"

Categories

Resources