I want to get two string inputs into a string array
String[] b = new String[n];
by using scanner but the scanner automatically takes blank value in
b[0].i.e. it skips the first loop.
Scanner scn = new Scanner(System.in);
int no = 0;
int n = scn.nextInt();
String[] b = new String[n];
for (int j = 0; j < n; j++) {
System.out.println("Enter the string");
b[j] = scn.nextLine();
}
the output occurs like
2
Enter
Enter
abc
can anyone suggest me why this problem occurs??
This is because nextInt() does not read the \n in your input. This is then read by your nextLine()
More explanation,
When you enter a number when prompted by the nextInt() call. You type a number and press Enter This makes your input look like this
10\n
nextInt() reads only the 10 and leaves out \n.
Then, your nextLine() reads only the \n.
This explains your output.
You can get the expected output by having an extra nextLine() after the nextInt().
See this for more information on it.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed last year.
So, I know this is probably a really stupid question, I am a beginner trying to learn Java basics and I have a problem with string array that I can't quite figure out. When I try to enter words into string array and the number of words is set by user (for example 5) I always can enter one less word (for example 4 instead of 5). My code is down below.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of words");
int n = scan.nextInt();
String arr[] = new String[n];
System.out.println("Please enter the words");
for (int i = 0; i < arr.length; i++) {
arr[i] = scan.nextLine();
}
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}
}
It is because when you use nextInt(), it is not reading the newline character. You can avoid this using 2 approaches.
Use nextLine i.e. use Integer.parseInt(scanner.nextLine()) instead of nextInt().
int n = Integer.parseInt(scan.nextLine());
String arr[] = new String[n];
Call nextLine before for loop so that the redundant newline is consumed before your for loop.
int n = scan.nextInt();
String arr[] = new String[n];
scan.nextLine();
System.out.println("Please enter the words");
'''
Scanner sc = new Scanner(System.in);
ArrayList<Integer> arrayIntegers = new ArrayList<Integer>();
System.out.print("#ofints: ");
String[] arrayStrings = new String [sc.nextInt()];
sc.nextLine();
for (int i = 0; i < arrayStrings.length; i++)
{
arrayStrings[i] = sc.nextLine();
}
'''
-How can this be done with using hasNext() method (breaks if space is entered) so there is no need for user prompt statement.
so e.g.:
1
2
3
Instead of:
#ofints: 3
1
2
3
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default.
Check this (stop on enter "exit"):
Scanner sc = new Scanner(System.in);
String inputStr;
while (sc.hasNext()) {
inputStr = sc.next();
if (inputStr.equals("exit")) break;
System.out.println(inputStr);
}
P.S. The hasNextLine() method checks to see if there's another line in the input of the Scanner object, no matter if the line is blank or not.
In this code I can get upto only 2 values instead of 3 input values. Why does it so? Please explain me.
Scanner input = new Scanner(System.in);
System.out.println("Enter how many string to get");
int size;
size = input.nextInt();
String arr[] = new String[size];
System.out.println("Enter strings one by one");
for(int i = 0; i < size; i++) {
arr[i] = input.nextLine();
System.out.println(i);
}
nextInt will get the integer from the input buffer and will leave the new line character in the buffer. So when you call nextLine after that, the new line character in the buffer will be returned. To fix this, add a nextLine after calling nextInt
Scanner input = new Scanner(System.in);
System.out.println("Enter how many string to get");
int size;
size = input.nextInt();
input.nextLine();//get the new line character and ignore it
String arr[] = new String[size];
System.out.println("Enter strings one by one");
for(int i = 0; i < size; i++) {
arr[i] = input.nextLine();
System.out.println(i);
}
See the answer from this link , it explains in detail what you are experiencing: Using scanner.nextLine()
In short the first nextLine reads the rest of the line from your nextInt call.
Use input.nextInt() instead of input.nextLine().
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
next() reads the input only till the space. It doesnt read the space between words.
I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}
What I want to do is ask the user for a number of strings to read into an array, and then ask the user to input that number of strings and read them into the array. When I run this code it never asks me for an input the first cycle of the first for-loop, just prints out "String #0: String #1: " and then I can input text. Why is that and what did I do wrong?
import java.util.Scanner;
public class ovn9
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Number of inputs: ");
int lines= sc.nextInt();
String[] text=new String[lines];
for(int x=0; x<text.length; x++)
{
System.out.print("String #"+x+": ");
text[x] = sc.nextLine();
}
for(int y=0; y<text.length; y++)
System.out.println(text[y]);
}
}
Buffering.
nextInt() does not consume the newline in the input buffer that was put there when you entered the number of inputs. In the iteration 0 of the for loop, there's already a line of input in the buffer and nextLine() can complete immediately and the program will wait for new input line only in iteration 1. To ignore the newline in the input, you can add just another nextLine() call before entering the for loop.
Maybe you should change your loop to use 'sc.next()'
for ( int x = 0; x < lines; x++ ) {
System.out.print("String #" + x + ": ");
text[x] = sc.next();
}
It can be explained by the Java API
String next(): Finds and returns the next complete token from this scanner.
String nextLine(): Advances this scanner past the current line and returns the input that was skipped.