Difference between next() and nextLine() when we are in a loop [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was working with array and i wanted to make a list that user can set a value for its length and then also user can add some String values duo to it's length that user set up.I wanted the program to show me the list that user entered to user (just practicing) and i found out a different use of next() and nextLine() that nextLine() method wouldn't work properly since i wanted to add as many String as i wanted to my Array.here is what i am thinking:
System.out.println("Welcome to addingCourse wizard :)");
System.out.println("Please enter the amount of your course: ");
int z = input.nextInt();
String[] course = new String[z];
for (int i = 0; i < course.length ; i++) {
course[i] = input.nextLine();
}
System.out.println("Ok. Here is your list...");
for (int i = 0; i < course.length; i++) {
System.out.println(course[i]);
}
problem is nextLine() wouldn't allow us to add items as we wanted in array.for example if you want your list to be 100, it will allow you to just enter 99 items although next() method allow course.length items and print all items

Take a look at these lines
int z = input.nextInt();
String[] course = new String[z];
for (int i = 0; i < course.length ; i++) {
course[i] = input.nextLine();
}
Whenever you hit the enter key, this creates a new line /n character. As soon as you read your integer on the first line, nextInt isnt consuming said char. Take a good look at the output after your lines are being printed, the first line is an empty line.
To consume this new line, add another nextLine() right after you finish reading your int.
int z = input.nextInt();
input.nextLine(); //Consumes the new line character

Related

Java : Scanner odd behaviour [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 7 years ago.
I tried to get inputs via scanner and in the past, I use enter to get to the next set of inputs.
For ex.
Input 1 <enter>
Input 2 <enter>
However this time, it only accepts in the same line , taking spaces as delimiter.
Scanner in = new Scanner(System.in);
int a,b,n,t;
String input_line;
String inputs[]= new String[3];
t = in.nextInt();
in.reset(); //Tried resetting Scanner to see if this works
input_line = in.nextLine();
inputs = input_line.split(" ");
for(String s:inputs)
System.out.println(s);
For instance, I expect to take the variable t in first line and then move on to the second line for input_line scanning. But if I hit enter after entering t, the program ends.
What am I missing here?
(Merging with another question was suggested but , let me explain, the Scanner does not skip any inputs).
Without any testing I would think you would need something like this
Scanner in = new Scanner(System.in);
int a,b,n,t;
String input_line;
String[] input_numbers = new String[3];
t = in.nextInt();
in.nextLine();
input_line = in.nextLine();
while(!input_line.equals("")){
input_numbers = input_line.split(" ");
// do what you want with numbers here for instance parse to make each string variable into int or create new scanner to do so
input_line = in.nextLine();
}
}

Java Scanner while loop

I'm trying to take in a string input which consists of multiple lines of numbers separated by ',' and ';' .
Example:
1,2;3,4;5,6;
9,8;7,6;
0,1;
;
Code:
ArrayList<Integer> alist = new ArrayList<>();
String delims = ";|\\,";
int i = 0;
Scanner input = new Scanner(System.in);
input.useDelimiter(delims);
while (input.hasNext()) {
alist.add(i, input.nextInt());
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
i++;
}
System.out.print('x');
When I run this in eclipse:
1,2;3,4;5,6; ( <= what i typed in console)
321133123413351436153716 ( <= output)
I'd expect something more like:
0 1
1 2
2 3
3 4
4 5
5 6
x
Why am I getting this sort of output?
One problem is that System.in is basically an infinite stream: hasNext will always return true unless the user enters a special command that closes it.
So you need to have the user enter something that tells you they are done. For example:
while(input.hasNext()) {
System.out.print("Enter an integer or 'end' to finish: ");
String next = input.next();
if("end".equalsIgnoreCase(next)) {
break;
}
int theInt = Integer.parseInt(next);
...
For your program, you might have the input you are trying to parse end with a special character like 1,2;3,4;5,6;end or 1,2;3,4;5,6;# that you check for.
And on these lines:
System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');
It looks like you are trying to perform String concatenation but since char is a numerical type, it performs addition instead. That is why you get the crazy output. So you need to use String instead of char:
System.out.print(i + " ");
System.out.print(alist.get(i) + "\n");
Or just:
System.out.println(i + " " + alist.get(i));
Edit for comment.
You could, for example, pull the input using nextLine from a Scanner with a default delimiter, then create a second Scanner to scan the line:
Scanner sysIn = new Scanner(System.in);
while(sysIn.hasNextLine()) {
String nextLine = sysIn.nextLine();
if(nextLine.isEmpty()) {
break;
}
Scanner lineIn = new Scanner(nextLine);
lineIn.useDelimiter(";|\\,");
while(lineIn.hasNextInt()) {
int nextInt = lineIn.nextInt();
...
}
}
Since Radiodef has already answered your actual problem(" instead of '), here are a few pointers I think could be helpful for you(This is more of a comment than an answer, but too long for an actual comment):
When you use Scanner, try to match the hasNextX function call to the nextX call. I.e. in your case, use hasNextInt and nextInt. This makes it much less likely that you will get an exception on unexpected input, while also making it easy to end input by just typing another delimiter.
Scanners useDelimiter call returns the Scanner, so it can be chained, as part of the initialisation of the Scanner. I.e. you can just write:
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
When you add to the end of an ArrayList, you don't need to(and usually should not) specify the index.
int i = 0, i++ is the textbook example of a for loop. Just because your test statement doesn't involve i does not mean you should not use a for loop.
Your code, with the above points addressed becomes as follows:
ArrayList<Integer> alist = new ArrayList<>();
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
for (int i = 0; input.hasNextInt(); i++) {
alist.add(input.nextInt());
System.out.println(i + " " + alist.get(i));
}
System.out.println('x');
Edit: Just had to mention one of my favorite delimiters for Scanner, since it is so suitable here:
Scanner input = new Scanner(System.in).useDelimiter("\\D");
This will make a Scanner over just numbers, splitting on anything that is not a number. Combined with hasNextInt it also ends input on the first blank line when reading from terminal input.

Scanner and for loop [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I'm working on a piece of code and I'm trying to initialize a vector. However, the code somehow skipped through the first one and initialized a blank to my vector. Anyone knows why? Here's a snippet of my code:
public class Test{
private Vector<String> vecStr;
public void run(){
vecStr = new Vector<String>();
System.out.println("How many strings do you want for your string vector?");
int numStr = keyboard.nextInt();
System.out.println("Enter your string values.");
for (int i=0;i<numStr;i++){
System.out.println(i + "Input");
vecStr.add(keyboard.nextLine());}
}
}
}
Let's say I input 4, somehow, the code gives me:
0
1
input:
2
input:
3
input:
It skipped the 0 one. Can someone please tell me why that happened? And if I were to display the Vector, it would give me : [ , blah, blah, blah]. How come there is a blank at the first element?
Scanner doesn't work on a line basis, but token basis. So, after your first nextInt() (for numStr) the scanner's cursor stays at the end of the input line (not start of next line). Therefore, first nextLine() execution right after that results in empty string. Subsequent calls to nextLine() then works correctly.
You can use input stream readers:
Vector<String> vecStr = new Vector<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many strings do you want for your string vector?");
int numStr = Integer.parseInt(reader.readLine());
System.out.println("Enter your string values:");
for (int i=0;i<numStr;i++){
System.out.println(i + " Input: ");
vecStr.add(reader.readLine());
}
System.out.println("vector contains:");
System.out.println(vecStr);

A simple Java code that doesn't work well

The following simple code in Java behaves somewhat in a strange way that I can not understand.
final public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("\nHow many names? ");
int n = sc.nextInt();
String[] a = new String[n];
a[0] = sc.nextLine(); //This line serves no purpose at all. It's useless and should be removed.
for (int i=0; i<n; i++)
{
System.out.print("\nEnter the name:->");
a[i] = sc.nextLine(); //request for input only inside the loop.
}
for (int i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}
}
The above is working well with no problem at all and displays the number of names inputted into the array a[] on the console but when I remove the line a[0] = sc.nextLine(); //This line serves no purpose at all. It's useless and should be removed., it displays for number of users first. let's say 3. there is no problem but when the loop starts iterating, it will ask for the name and first time the message Enter the name:-> is displayed twice
and the output would be something like shown below.
How many names? 3
Enter the name:-> Don't allow to enter the name here.
Enter the name:->Tiger
Enter the name:->Pitter
Tiger
Pitter
Although I entered 3 for "How many names?", it allows only two names to enter. Why?
Note again that the code shown above is working well. The problem occurs only when the line specified with bold latters in the above paragraph is commented out.
When you use Scanner.nextInt(), it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a Scanner.nextLine(). You can discard the result instead of assigning it to a[0]:
int n = sc.nextInt();
sc.nextLine();
It's for this reason that I suggest always using nextLine (or BufferedReader.readLine()) and doing the parsing after using Integer.parseInt().
You are reading three lines. The problem you have is that nextInt() reads an int value, it doesn't read and consume the end of the line. (A common mistake)
You need the nextLine() after it to say that you want to ignore the rest of the line.
The nextInt call reads from input until the end of the int, but does not read the newline character after the int. So, the first iteration displays "enter the name", then calls nextLine() which reads the end of the line where you typed the number of players (an empty string). Then the second iteration starts and displays "enter the name", and nextLine() blocks until you type a newline character.

Java Scanner class reading strings [duplicate]

This question already has answers here:
Java Scanner class reading strings
(5 answers)
Closed 8 years ago.
I got the following code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.next();
}
System.out.println(names[0]);
When I run this code, the scanner will only pick up the first name and not the last name. And it will sometimes skip a line when trying to enter a name, it will show up as if I had left the name blank and skip to the next name. I don't know what's causing this.
I hope someone can help me!
EDIT: I have tried in.nextLine(); it fixes the complete names but it still keeps a line, here is an example of the output:
How many names are you going to save: 3
Type a name: Type a name: John Doe
Type a name: John Lennon
Instead of:
in.next();
Use:
in.nextLine();
nextLine() reads the characters until it finds a new line character '\n'
After your initial nextInt(), there's still an empty newline in your input. So just add a nextLine() after your nextInt(), and then go into your loop:
...
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine(); // gets rid of the newline after number-of-names
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
...
Scanner.next stops reading when it encounters a delimiter, which is a whitespace. Use the nextLine method instead.
Try using:
System.out.println()
Instead of:
System.out.print()

Categories