Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am writing a method which takes in a .txt file and adds the information to a Student type, which has String name and int age, weight and height. I load in all the data, splitting by a comma. To convert the string to int I am trying to use Integer.pareseInt(), but this code seems to be causing an error, what might be causing this?
public static StudentCollection loadBespoke(File file){
List<Student> students = new ArrayList<>();
try (BufferedReader b_reader = new BufferedReader(new FileReader(file))){
String line;
while((line = b_reader.readLine())!= null){
String[] items = line.split(",");
String name = items[0];
System.out.println(items[1]);
int age = Integer.parseInt(items[1]); //errors
int weight = Integer.parseInt(items[2]);
int height = Integer.parseInt(items[3]);
Student student = new Student();
student.withName(name);
student.withAge(age);
student.withWeight(weight);
student.withHeight(height);
students.add(student);
}
} catch (IOException e) {
e.printStackTrace();
} return new StudentCollection(students);
}
The .txt looks like this:
Benjamin, 20, 63, null
Sarah, 19, 53, 165
And the error is:
Exception in thread "main" java.lang.NumberFormatException: For input string: " 20"
Remove spaces between elements or trim the items Integer.parseInt(items[1].trim())
Make sure items[1] has no space or tab to it.. try printing its value.. in Java you can trim using trim() method
Related
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 2 years ago.
Improve this question
I am developing a program that takes input from the console. So far it has been no problem reading input that consists of one line of input from the console. But the program does not work when it is supposed to read multiple lines. How can i improve the readInput method to read multiple lines of input and the return a single String containing all of the input from different lines.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
String input = inputstream.readLine();
return input;
}
So when you write String input = inputstream.readLine() This reads one line at a time,
As you are taking input from the user there would not be any null cases even if the user clicks enter, You need to check for the length of the input string, If it is 0 then break from the while loop.
But this isn't the case when you are reading from a file or other source you need to check whether the input is null or not.
Hope this could help you.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
StringBuilder finalString = new StringBuilder();
String input = inputstream.readLine();
while(true){
finalString.append(input);
input=inputstream.readLine();
if(input.length() == 0){
break;
}
}
br.close();
return finalString;
}
Input:
hi hello
how are you
Am fine
Output:
hi hellohow are youAm fine
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am attempting a programming question at hackerrank.com and is using Java language.
Part of the question required me to split a string by character /.
I met problems in doing this in Java.
Given input:
cu/a/ca ha/ri i/tu san/gat se/juk
My code (Java):
Scanner input = new Scanner(System.in);
String source = input.next();
String[] inputchar = source.split("/");
for (int i = 0; i < inputchar.length; i++){
System.out.print(inputchar[i] + "\n");
}
Result:
cu
a
ca
But, I expected the following output:
cu
a
ca ha
ri i
tu san
gat se
juk
However, when I tried with the following C# code, it gave me the correct result.
String source = Console.ReadLine();
String[] slashchar = source.Split('/');
for (int k = 0; k < slashchar.Length; k++)
{
Console.WriteLine(slashchar[k]);
}
I noticed the string with spaced cannot be splitted properly with my Java code.
Is there any mistakes in my Java code above?
Your Scanner does some tokenizing - on spaces. So you didn't read whole line with
input.next();
You only read until first blank.
Replace with
input.nextLine();
And try again.
Change to String source = input.nextLine(); instead of String source = input.next(); Because input.next() returns string till space, input.nextLine returns string till new line.
With java try using nextLine() like this:
Scanner input = new Scanner(System.in);
String source = input.nextLine();
String[] inputchar = source.split("/");
for (int i = 0; i < inputchar.length; i++){
System.out.print(inputchar[i] + "\n");
}
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 am working on the password login portion of a class project. Nothing fancy. User, or role will be an int and password is a String. I am just using a simple encryption for now. The problem I am having is while reading the file I am getting an input mismatch. I have done something similar in the past that required me to read ints and Strings and did not have any problems. But I just cannot figure out what is going wrong in this case. Any help as to why I am getting this error would be greatly appreciated. I am using while(inputStream.hasNextLine()) then read the int and then the String I have tried hasNextInt and hasNext and keep getting the same error.
public void readFile(){
Scanner inputStream = null;
try {
inputStream = new Scanner (new FileInputStream("login.txt"));
}catch (FileNotFoundException e) {
e.printStackTrace();
}
if(inputStream != null){
while (inputStream.hasNextLine()){
int luser = inputStream.nextInt();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
count ++;
}
inputStream.close();
}
}
Try reading it as a String and converting the string to an int
while (inputStream.hasNextLine()) {
Integer luser = Integer.parseInt(inputStream.nextLine());
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
count++;
}
But you need to make sure your file has your data in the exact format as below
12342
password
It's hard to say without knowing what error it is that you are getting, but my guess is that it is because you are not reading the entire file.
Your file probably looks like this:
1\r\n
password\r\n
When you call nextInt() it reads the int, but doesn't advance past the first \r\n so when you call nextLine() it reads to the end of the line so all you get is \r\n. You need to read past the first \r\n and then read the password.
Try
int luser = inputStream.nextInt();
inputStream.nextLine();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
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!"
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am experiencing very strange behavior with BufferedReader. I want to read an entire file however it only reads every other line.
E.g the file below
1 //ignore the left most space - shouldn't exist
2
3
4
5
6
Will output
2
4
6
Here is some of my code...
fileRead = new BufferedReader(new InputStreamReader( new FileInputStream(file)));
public void scan(){
if (fileRead != null){
try{
while ((fileRead.readLine()) != null){
String line = fileRead.readLine();
String abcLine = line;
System.out.println(line);
}
}catch(IOException e) {
System.out.println("Line can not be read");
}
}else{ System.out.println("Can not Read - File Not Found"); }
}
My best bet is the bug lies within the while statement. Is this the correct way to ensure
you read the file until you reach EOF "end of file" ?
Any insight is truly appreciated
Thank you!
You're reading two lines each time through the loop. Your current code is:
while ((fileRead.readLine()) != null){ // reads a line, ignores it
String line = fileRead.readLine(); // reads another line, stores in 'line'
... // do stuff with 'line'
}
Every call to readLine() reads a line. You probably want something more like:
String line;
while ((line = fileRead.readLine()) != null) {
... // do stuff with 'line'
}