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");
}
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 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
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 6 years ago.
Improve this question
I wrote simple program that deletes letter or word from text. Everything works perfectly, but I can't write " " [space] in console. When I do that it does nothing. What should I write into console to tell it that I want to delete space from text?
import java.io.*;
import java.util.*;
public class StringDelete {
public static void main(String args[]) {
String x = "bla bla bla";
System.out.println(x);
System.out.println("What do you want to delete?");
Scanner sc = new Scanner(System.in);
String fr = sc.next();
int po = 0;
int le = x.length();
int i = 0;
do {
po = x.substring(i).indexOf(fr);
if (po != -1) {
x = x.substring(0, po+i) + x.substring(po+i + 1);
}
i += po;
}while(i<le&&po!=-1);
System.out.println(x);
}
}
Here:
String fr = sc.next();
You are using next() method.
When this method encounters a whitespace character, it returns the string before that character.
eg:
for "asd fgh" it returns asd".
for "xyz" it returns "xyz"
for " " it reurns ""(empty string)
Hence, when you write " "(space), the string before it is empty String, and it returns the empty string.
Instead of next(), use nextLine().
String fr = sc.nextLine();
You should replace the line String fr = sc.next(); with String fr = sc.nextLine();.
You can find more info here.
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 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.