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.
Related
I am making a search engine to find what document matches the words given by the user. The following is my code:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
// Takes input until user leaves a blank line or max is reached.
while (userInput.hasNext() && i < 9){
stringArray[i] = userInput.next();
i++;
}
for (int j = 0; j < i; j++){
System.out.println(stringArray[j]);
}
This is my method that actually takes the user input and I am going to add to it in a little bit to do the search but I tried to test this much (that's why it prints out the input) to see if it works but It keeps accepting input. What can I change so that it takes as many words as the user puts them until they leave a line blank? I got it to stop at 10 but I thought hasNext() would stop it when they leave a line blank but it just keeps scanning.
hasNext() & next() stop at words, not lines. With your code, the user could put all 10 words on the same line and they'd be done. Also, these methods will skip all whitespace, including newline characters, until they find the next word. You can't look for a blank line using hasNext() and next() can never return an empty string. You want hasNextLine() and nextLine() instead.
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;
while (i < stringArray.length
&& userInput.hasNextLine()
&& !(stringArray[i] = userInput.nextLine().trim()).isEmpty()) {
i++;
}
for (int j = 0; j < i; j++) { // just for testing purposes
System.out.println(stringArray[j]);
}
But why limit yourself to just 10 lines? You can use ArrayList instead for more flexibility:
Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for:");
List<String> stringList = new ArrayList<>();
String line;
while (userInput.hasNextLine()
&& !(line = userInput.nextLine().trim()).isEmpty()) {
stringList.add(line);
}
stringList.forEach(System.out::println); // just for testing purposes
Change your while loop to this:
while (!(String temp = userInput.nextLine()).trim().contentEquals("")) {
stringArray[i] = userInput.next();
i++;
}
String line;
int i = 0;
while(!(line = userInput.nextLine()).isEmpty()) {
for (String word :line.split("\\s+")){
stringArray[i]=word;
i++;
}
}
This code assigns every line from Scanner into variable line until is not user input empty. In every iteration it splits line to words and assigns to stringArray.
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.
in one line from the standard input I have 3 types of integers: the first integer is id, the second integer is N - some number, and after that follows N integers, separeted by a single space which I want to store in array or ArrayList. How can I do this using BufferedReader? I have the following code:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int ID = Integer.parseInt(line[0]);
int N = Integer.parseInt(line[1]);
My question is is there any elegant way to read the rest of the line and to store it into array?
Use Scanner and method hasNextInt()
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
arr[i]=scanner.nextInt();
i++;
}
}
How can I do this using BufferedReader?
You've already read/split the line, so you can just loop over the rest of the inputted integers and add them to an array:
int[] array = new int[N]; // rest of the input
assert line.length + 2 == N; // or some other equivalent check
for (int i = 0; i < N; i++)
array[i] = Integer.parseInt(line[i + 2]);
This will also let you handle errors within the loop (I'll leave that part to you, should you find it necessary).
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.