Scanner object behaves differently for Integer vs String inputs [duplicate] - java

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Scanner issue when using nextLine after nextInt
In the following two code snippets, I first ask for the number of inputs required and let the user input that many inputs of a particular kind. When the required inputs are String types, it takes one less input unless I use s.next() first, while for Integers it works fine. I don't understand why. Can someone please explain?. Thanks
First Code with String inputs and nextLine function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
String[] inputs = new String[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextLine();
}
System.out.println("end of code");
}
Second Code with Integer inputs and nextInt function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
Integer[] inputs = new Integer[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextInt();
}
System.out.println("end of code");
}

It is because of the following line:
int num = s.nextInt();
Your next INT only returns the INT until it gets to the \n character.
If you had a test file like this:
4
1
2
3
4
Your character code will look like this:
4'\n'
1'\n'
2'\n'
3'\n'
4'\n'
So when you grab the integer, it will grab the 4 for your "nextInt()" method on the scanner. When you tell it to grab the next line "nextLine()", it will grab the remainder of that line which is just '\n' and store nothing into the first value into your array.
On the reverse side, if you tell it to grab the next integer "nextInt()", it will search until it finds the next integer, which will cause the 1 to go into the first value into the array.

Related

How to use Scanner hasNextInt() inside a while loop?

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++;
}

Unable to take input from console in java

I am new to Java and facing problem while taking input from the console.
Here's my code:
import java.util.*;
class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
System.out.println(t);
for (int n = 0; n < t; n++) {
for (int i=0;i<4;i++){
int mzeroes = sc.nextInt();
int nones = sc.nextInt();
int stringLength = sc.nextInt();
String string=sc.nextLine();
System.out.println(mzeroes);
System.out.println(nones);
System.out.println(stringLength);
System.out.println(string);
}
}
}
}
Input:
2
2 2 8 11101000
3 4 16 0110111000011111
Error:
Exception in thread "main" java.util.InputMismatchException: For input string: "0110111000011111"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at solution.main(solution.java:13)
I tried the same code but there were no errors and it executed successfully. I think you are making the mistake while giving the input. This is how the input has to be given :
As the first input is two so it will ask for two inputs in the loop and then when you pass the first input for the loop it will print out the there 3 ints one after other and the remaining string at the end. And the same goes for the second input of the loop.
Note: The String string = sc.nextLine(); will give you the string so space before the last number will also be taken in the string.
Hope this helps.

Cannot get input in simple output program in Java

I will keep this short and simple, here's the program-
class Sample{
private int n;
public void getDetails(){
Scanner y=new Scanner(System.in);
n=y.nextInt();
System.out.println("Entered 'n' = "+n);
}
public void displayDetails(){
int i,j;
int arr[]=new int[n];
Scanner x=new Scanner(System.in);
for(j=0;j<n;j++) {
arr[j] = x.nextInt();
System.out.println("Entered element = "+arr[j]);
}
System.out.println("Entered array: ");
for(i=0;i<n;i++)
System.out.print(arr[i]+" ");
}
}
public class TestClass {
public static void main(String[] args) {
Sample obj = new Sample();
obj.getDetails();
obj.displayDetails();
}
}
This simple program just takes number of elements(n) and the elements of array(arr[]) as input in different methods.
When the input is given in interactive mode, everything works fine. Here's the console output-
5
Entered 'n' = 5
1 2 3 4 5
Entered element = 1
Entered element = 2
Entered element = 3
Entered element = 4
Entered element = 5
Entered array:
1 2 3 4 5
But when I give it as Stdin input(or all input at once), it just takes the number of elements(n) and ignores my array input(arr[]). Here I had to give the array elements again. Console output-
5
1 2 3 4 5Entered 'n' = 5
1
Entered element = 1
2
Entered element = 2
3 4 5
Entered element = 3
Entered element = 4
Entered element = 5
Entered array:
1 2 3 4 5
I have no idea what is happening. Is it a bug? Please help
Part of the problem is that you are creating multiple scanners. Create one scanner and use it everywhere, like so:
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
Sample obj = new Sample();
obj.getArraySize();
obj.displayDetails();
}
}
class Sample{
private int arraySize;
Scanner scanner = new Scanner(System.in);
public void getArraySize(){
System.out.print("Enter size of array: ");
arraySize = scanner.nextInt();
System.out.println("Entered array size = " + arraySize);
}
public void displayDetails(){
//Create an integer array of size arraySize
int intArray[] = new int[arraySize];
//Repeatedly request integers for the array
for( int i=0; i<arraySize; i++) {
int nextInt = scanner.nextInt();
intArray[i] = nextInt;
System.out.println("Entered element = " + intArray[i]);
}
//Print out the entered elements
System.out.println("Entered array: ");
for( int i=0; i<arraySize; i++) {
System.out.print(intArray[i]+" ");
}
scanner.close();
}
}
console output:
Enter size of array: 5
Entered array size = 5
5 4 3 2 1
Entered element = 5
Entered element = 4
Entered element = 3
Entered element = 2
Entered element = 1
Entered array:
5 4 3 2 1
You still need to check that the next value is actually an int. If you put a different type of value in there, like a letter, it will crash. See these links for additional details:
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Java Multiple Scanners
Why is not possible to reopen a closed (standard) stream?
You areusing scanner to take userinput.
Scanner y=new Scanner(System.in);
In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() doesn’t not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().
In BufferReader class there is no such type of problem. This problem occurs only for Scanner class, due to nextXXX() methods ignore newline character and nextLine() only reads newline character. If we use one more call of nextLine() method between nextXXX() and nextLine(), then this problem will not occur because nextLine() will consume the newline character.
Please check this SO link it has good explaination.

How can I make an input read out multiple integers on a single line?

How can I make it so that I can prompt the user to input multiple integers on one line that are seperated by spaces. And if the first integer is 0 or less than 0 it will print out "Bad Input" when all the integers are inputted and the user presses enter. Also how can I make it so that when the user enters a negative number at the end of the line, it will stop entering numbers and make multiply all of them together.
This is what I have so far but i'm not sure I am doing this right.
import java.util.Scanner;
public class tempprime {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int count = 1;
String inputnumbers;
System.out.print("Enter integers: ");
inputnumbers = input.nextLine();
for (int i = 0; i < inputnumbers.length(); i++){
if (inputnumbers.charAt(i) == ' ')
count++;
}
int[] numbers = new int[count];
}
}
You already have it so the user can enter in values until they hit enter. Now you can do is use a split operation to break the string up into an array of values.
String[] values = inputnumbers.split('\s');
Then you could replace charAt with access to the array.
Alternatively, Scanner already allows the user to enter in as many integers as they need on the same line. nextLine() finds the first occurance of a new line, but you can use input.nextInt(), grabs the next int stopping at a space, multiple times and read them in one at a time. You can also check if there are any more values remaining using the scanners hasNext methods.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You can see an example of reading multiple ints below. The user can enter them in one at a time, or 3 at a time and should still work the same.
Scanner in = new Scanner(System.in);
System.out.print("Enter 3 ints:");
int a,b,c;
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
System.out.printf("A: %d B: %d C: %d", a, b ,c);

Splitting several integers in java

I am very new to java. I am trying to prompt the user to enter 4 integer numbers followed by a space and eventually print them out at the end. I am a little confused with the order of how I write things out and using the split(" ");
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
int numbers = keyboard.nextInt();
// Need split(" "); here?
} // End main string args here
} // End class calculations here
Any help or advice is appreciated. I have looked at other ways on stackoverflow but somehow I keep getting errors.
Read it in one String with keyboard.nextLine
Use the split method of String for get an array of Strings
Convert every element of the array to int with Integer.parseInt
Print your ints.
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
// Scan an entire line (containg 4 integers separated by spaces):
String lineWithNumbers = Keyboard.nextLine();
// Split the String by the spaces so that you get an array of size 4 with
// the numbers (in a String).
String[] numbers = lineWithNumbers.split(" ");
// For each String in the array, print them to the screen.
for(String numberString : numbers) {
System.out.println(numberString);
}
} // End main string args here
} // End class calculations here
This code will print all numbers, in case you actually want to do something with the Integers (for example mathematical operations) you can parse the String to an int, like so:
int myNumber = Integer.parseInt(numberString);
Hope this helps.
If would suggest to use the abilities of the Scanner class to retrieve numbers from the user input:
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[4];
System.out.println("Enter 4 integer numbers here: ");
for (int i = 0; i < 4 && keyboard.hasNextInt(); i++) {
numbers[i] = keyboard.nextInt();
}
System.out.println(Arrays.toString(numbers));
This code creates an array of size 4 and then loops over the user input reading the numbers from it. It will stop parsing the input if he has the four numbers, or if the user enters something different than a number. For example, if he enters 1 blub 3 4, then the array will be [1, 0, 0, 0].
This code has some advantages compared to the nextLine approaches of the over answers:
you don't have to care about the integer conversion (exception handling)
you can either write these number onto one line or each number on its own line
If you like to read an arbitrary amount of numbers, then use a List instead:
List<Integer> numbers = new ArrayList<>();
System.out.println("Enter some integer numbers here (enter something else than a number to stop): ");
while (keyboard.hasNextInt()) {
numbers.add(keyboard.nextInt());
}
System.out.println(numbers);

Categories