I have a class that takes input from the Scanner class and outputs via the PrintWriter class. When the program hits the for loop it automatically runs the first iteration without waiting to get input from the user.
It should read Insert item 1:
However it reads Insert Item 1 Insert Item 2.
After the first iteration everything runs fine.
Any help in regards to why this is happening would be greatly appreciated.
InputSplicer(Scanner input)
{
this.input = input;
array = new ArrayList<String>();
}
void splice()
{
System.out.println("What is the output file destination?");
outputFile = input.next();
outputFileFile = new File(outputFile);
try {
output = new PrintWriter(outputFileFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("How many items are in the query?");
lengthOf = input.nextInt();
for(int i = 1; i <= lengthOf; i++)
{
System.out.println("Insert item " + i);
//spaces in output are not working for example item 1 cannot equal jason tavano can equal jasontavano
s = input.nextLine();
s.trim();
if(s.equalsIgnoreCase("null"))
{
s = "";
}
if(i != lengthOf)
array.add(s + pipe);
else
array.add(s);
}
for(int i = 0; i < array.size(); i++)
output.print(array.get(i));
output.close();
}
}
Scanner.nextInt() does not read the remaining new line character that follows it. Later Scanner.nextLine() reads in characters from the stream until a new line character is found. You should use Scanner.nextLine() after using Scanner.nextInt() to begin read the lines following the number.
problem:
s = input.nextLine();
When you input the number from the nextInt it will consume the newLine character from it thus iterating to the second loop in your for loop
solution:
consume the newLine character first before going to the loop
sample:
System.out.println("How many items are in the query?");
lengthOf = input.nextInt();
input.nextLine(); //will consume the newLine character from the input lengthOf
The nextInt() method doesn't remove the enter char from the stream, so you should clear the stream after that to clear the remaining of that line.
The simplest way to clear it would be to call a nextLine() before starting the loop
Related
I cannot get out of while loop.
I do not why sc.hasNextInt() does not return false after last read number.
Should I use another method or is there a mistake in my code?
public static void main(String[] args) {
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int[] numbers = new int[sc.nextInt()];
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
**while ( sc.hasNextInt()) {**
numbers[index++] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
}
Do the following:
Use the input length as the end of the loop.
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int len = sc.nextInt();
int[] numbers = new int[len]; // use len here
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
for (index = 0; index < len; index++) { // and use len here
numbers[index] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
And don't close the scanner.
When you are receiving your input from the console, the Scanner hasNextInt() method placed inside a while loop condition will continue to read (meaning the loop will continue), until one of the following happens:
You submit a non-numeric symbol (e.g. a letter).
You submit a so-called "end of file" character, which is a special symbol telling the Scanner to stop reading.
Thus, in your case you cannot have the hasNextInt() inside your while loop condition - I am showing a solution below with a counter variable that you can use.
However, the hasNextInt() method inside a while loop has its practical usage for when reading from a different source than the console - e.g. from a String or a file. Inspired from the examples here, suppose we have:
String s = "Hello World! 3 + 3.0 = 6 ";
We can then pass the string s as an input source to the Scanner (notice that we are not passing System.in to the constructor):
Scanner scanner = new Scanner(s);
Then loop until hasNext(), which checks if there is another token of any type in the input. Inside the loop, perform a check if this token is an int using hasNextInt() and print it, otherwise pass the token to the next one using next():
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
System.out.println("Found int value: " + scanner.next());
} else {
scanner.next();
}
}
Result:
Found int value: 3
Found int value: 6
In the example above, we cannot use hasNextInt() in the while loop condition itself, because the method returns false on the first non-int character that it finds (so the loop closes immediately, as our String begins with a letter).
However, we could use while (hasNextInt()) to read the list of numbers from a file.
Now, the solution to your problem would be to place the index variable inside the while loop condition:
while (index < numbers.length) {
numbers[index++] = sc.nextInt();
}
Or for clarity`s sake, make a specific counter variable:
int index = 0;
int counter = 0;
while (counter < numbers.length) {
numbers[index++] = sc.nextInt();
counter++;
}
I want to allow the user to input strings until a blank line is entered, and have the strings stored in an ArrayList. I have the following code and I think it's right, but obviously not.
String str = " ";
Scanner sc = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
System.out.println("Please enter words");
while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
list.add(sc.nextLine());
}
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
You consume the next line one time more as you can as you invoke a single time sc.hasNextLine() but twice sc.nextLine().
Instead, invoke a single time nextLine() and then use the variable where you stored the result to retrieve the read line :
while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
list.add(str);
}
I want to write a while-loop with (hasNextLine()) to run the code, and I hope that it can break when I input successive two new-line(with the button "Enter" of the keyboard).
Can I break the loop without any break condition like string.equals(quit) etc;
Scanner sc = new Scanner(System.in);
int[] input_Num = new int [3000] ;
int i = 0 ;
while ( sc.hasNextLine() ){
input_Num[i] = sc.nextInt();
System.out.println(input_Num[i]);
System.out.println(sc.hasNextLine());
}
however, the System.out.println(sc.hasNextLine()); will always return true to break the loop.
It will always turn true until end of file, and while it does the loop will not be broken.
But all you have to do is test for an empty line.
This can do something along the lines of what you want.
Basically, if you want to read lines, you need to read lines. You can't use hasNextLine and then nextInt, they don't work well together.
Scanner scn = new Scanner(System.in);
String line;
int empty = 0;
int input;
while(true)
{
line=scn.nextLine().trim();
if(line.equals(""))
{
++empty;
if(empty==2) break;
}
else
{
empty=0;
input = Integer.parseInt(line);
// ... do stuff with input
}
}
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.
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.