java.lang.NumberFormatException error after inputting a number [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am feeling quite stupid at this point for not being able to figure out something that is most likely a simple fix. I keep getting the error "Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at searchSorting.main(searchSorting.java:15)" after inputting how many numbers I want to input. Others solutions to this problem just don't seem to apply to me somehow. Thanks for the help
import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
int number, search, item, array[], first, last, middle;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
item = Integer.parseInt(in.nextLine());
double[] values = new double[item];
for (int i = 0; i < values.length; i++) {
System.out.print("Input number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
for (int index = 0; index < 5; index++)
System.out.print(values[index] + " ");
in.nextLine();
Arrays.sort(values);
System.out.println("Sorted number is: " + Arrays.toString(values));
System.out.println("Enter the number you are looking for?");
search = in.nextInt();
first = 0;
last = (item - 1);
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}}

For more info check out Scanner and Integer documentation, it's an excellent resource.
Edit: Try removing line 15 and replacing item with number in the next line

You call this:
number = in.nextInt();
Assuming the user types 123 and ENTER, this call consumes the 123 and leaves the input stream positioned before the end-of-line character.
The next relevant code is
item = Integer.parseInt(in.nextLine());
The nextLine call advances the input stream past the end-of-line, returning all characters it passed on the way. Since the ENTER key was pressed immediately after 123, the returned value is the emoty string. Which is not an integer.
You need to review your strategy of sometimes scanning numbers (nextInt) and sometimes scanning rest-of-linr (nextLine). Mixing the two needs to be done quite carefully. You might be better advised to stick to the numerical methods (nextInt/nextDouble).
For example, replacing this
item = Integer.parseInt(in.nextLine());
by this
item = in.nextInt();
automatically handles the line-ending.
From discussion in comments:
I am still confused as to why it's having me input
the value a second time on the next line
Making assumptions about how you modified the code since your initial question: it's because you've written code that reads the number twice:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt(); // **** first input ****
array = new int [number];
item = in.nextDouble(); // **** second input ****
double[] values = new double[item];
Each time you call for in.nextSomething() the Scanner is going to read more input. It should likely just be this:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
double[] values = new double[number];

Related

Printing Arrays back to user (java)

I'm quite new to java programming so excuse the basic misunderstandings and interpretations of the fundamentals.
This program is supposed to ask the user for the size of an array, then ask the user for input n amount of times and then prints the array back to the user. So far, the first 2 parts work. The program asks for the size of the array and then prints "Enter element n: " based on how many times the user specified in part 1. However, i can't seem to figure out how to print back the string input back out (In my first for loop) the second for loop i tried does not work and just ends the program straight after the first for loop finishes executing. If anyone could help me it would be much appreciated and contribute to my learning of the basics of java. Cheers.
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter array size: ");
int arraySize = scanner.nextInt();
int[] array = new int[arraySize];
for (int i = 0; i<array.length; i++){
System.out.print("Enter element " + (i + 1) + ": ");
String element = scanner.next();
}
System.out.print(array[0]);
for (int i = 1; i < array.length; i++){
System.out.print(array[i]);
}
System.out.println("}");
}
You're not storing any input value into the array.
replace this line:
String element = scanner.next();
with the following one:
array[i] = scanner.nextInt();

The Equals Function does not Work When it is In While Loop

I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
There are two places where there is a problem:
The first one sc.nextInt() method - which only reads the int
value by keeps current reading buffer on the same line. So to
ignore/skip everything what is after int on the input line (which is
probably \n or \r\n if you only enter the number) you have to
use sc.nextLine().
The second one is sc.next() method - which
only reads first token(or simply word) from your line. That is
probably why you only get "less" value assigned to response
and that will never be .equals to "less than". So you will
have to replace sc.next() one with sc.nextLine() and remove
unnecessary sc.nextLine() from the next line.
Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.
If my explanation is still not clear have a look at the code I have modified for you below:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}

Java-ArrayIndexOutOfBoundsException Error

When i run the following program I get an error at line 20, and this is my code:
package J1;
import java.util.Scanner;
public class SpeedLimit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.next();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + "miles" + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
}
when i run the code, I enter the following input from the keyboard:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1
to get this result as an output:
170 miles
180 miles
90 miles
but i get the following Error when i run the code
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)
String pair = keyboard.next(); This reads only one token which are separated by " " so when you split pair by " ". It will only have one element, The String itself. So you need to read the whole line and then split it by delimited " ".
Another mistake is that when you change that line with String pair = keyboard.nextLine(); , You will still get error because System considers Enter key as input of .nextLine() method. So you need to discard that extra unnecessary input.
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
int ip1=keyboard.nextInt();
int ip2=keyboard.nextInt();
speed = speed + ip1*(ip2-last);
last = ip2;
}
output = output +speed + "miles" + "\n";
speed =0;
input = keyboard.nextInt();
}
You are reading the variable pair the wrong way and then you split it and assign it to tab which fails to automatically to fetch index cause pair variable got a problem.
*nextLine(): reads the remainder of the current line even if it is empty.
keyboard.nextLine(); //To avoid the exception you commented
String pair = keyboard.nextLine(); //here is solved
tab = pair.split(" ");
Keyboard.next() will only read the input till the space, so pair and the array will have only one number, so tab[1] results in arrayOutOfBound exception. Use the method nextLine() to read the inputs with space.
You Can try below changes in your code :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = Integer.parseInt(keyboard.nextLine());
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.nextLine();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0].trim())*(Integer.parseInt(tab[1].trim())-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + " miles " + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
i did'n really understand how you are providing the inputs. but, if "3" happens to be your first line then split(" ") would return an array of length 1. thus, tab[0] would return 3 and tab[1] will give you a nullPointerException.
try adding an check for the length of tab before executing your line 20.
this should do the trick:
if(tab.length() > 1){
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
}

Why is Scanner skipping inputs from the user

I have a small task that allows the user to enter the regions and their neighbors of any country.
I did everything and I just have a small problem which is when I run my code and the program asks the user to enter the number of regions, if the user enters 13 or and number greater than 10, the system will consider that number is like two inputs and it will not allow the user to enter anything for the second question and it will prompt him with the third question immediately. Why?
I think the problem with the Scanner class in the following command:
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
region = new CountryRegion[REGION_COUNT];
String[] neighbours;
for (int r = 0; r < region.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1) + ": ");
String regionName = kb.nextLine();
System.out.print("How many neighbors for region #" + (r + 1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
neighbours = new String[size];
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #" + (n + 1) + ": ");
neighbours [n] = kb.nextLine();
}
region [r] = new CountryRegion(regionName, neighbours);
}
else
System.exit(0);
}
for (int i = 0; i < REGION_COUNT; i++) {
System.out.print(region[i].getRegionName() +": ");
for (int k = 0; k < region[i].getRegionAjesint().length; k++) {
System.out.print(region[i].getRegionAjesint()[k] +", ");
}
System.out.println();
}
mapColor = new MapColor(region);
Any help, please?
Ok, Very simple your problem is that you are using the nextInt() method of the Scanner class and then using the nextLine() method both of these use the same buffer and here is what's happening.
When you enter the number your asking (let say 10) in the key board your actually entering
10 and the enter key (new line character (\n))
The nextInt() method from the Scanner class will read the 10 and just the 10 that meaning that the new line character (\n) is still in the keyboard buffer and next in your code you have a nextLine() which will read everything up to a new line (\n), which you already have in the buffer!!!
So the way this is all working is that the nextLine() method considers the new line character (\n) left in the buffer as it's input and there for continues to the next iteration of the loop.
The solution to your problem is to clear the buffer of the new line character (\n) you can achieve this by calling a nextLine() method before the actual one in your code like so:
...
int REGION_COUNT = kb.nextInt();
region = new CountryRegion[REGION_COUNT];
String[] neighbours;
kb.nextLine(); //CLEAR THE KEYBOARD BUFFER
for (int r = 0; r < region.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1) + ": ");
String regionName = kb.nextLine();
...
This way the nextLine() called extracts the new line character from the buffer, clearing it, and since it doesn't store it it gets discarded leaving you with a new line character free buffer ready to receive full input from the user in your nextLine() method.
Hope this helps.
Sounds like each key press is an input.
You are using nextLine() to get the String but I think you should be using next().

Scanner in Java not working

I'm trying to write a very simple number guessing game (code is below). After 1 round is finished, the user is supposed to be able to decide whether he/she wants to play another round or not. Problem is, the program always skips the last question (never letting the user answer 'y' or otherwise. What am I missing here? Is there something about java.util.Scanner I don't know about?
import java.util.Random;
import java.util.Scanner;
public class GuessNum {
public GuessNum() {
int numRandom = 0;
int numGuess;
int life = 5;
String want = "";
Random rand = new Random();
Scanner scan = new Scanner(System.in);
do {
int lifeLeft = 5;
numRandom = rand.nextInt(9)+1;
System.out.print("\nGuess the Number [1..10]\n");
System.out.print("===================\n");
System.out.print("You have " + lifeLeft + " chances.\n");
do {
do {
System.out.print("What number do I have in mind: ");
numGuess = scan.nextInt();
if (numGuess < 1 || numGuess > 10)
System.out.println("Invalid input. Range is 1-10.");
} while (numGuess < 1 || numGuess > 10);
if (numGuess != numRandom && lifeLeft != 0)
System.out.println("Wrong! You only have " + --lifeLeft + " chances left.");
} while (numGuess!=numRandom && lifeLeft > 0);
if (numGuess == numRandom)
System.out.println("Correct! -- in " + (life - lifeLeft) + " guess(es).");
if (lifeLeft == 0) {
System.out.println("You have no more lives..");
System.out.println("This is the number: " + numRandom);
}
System.out.print("\nEnter 'y' if you want to play again or any other character to exit: ");
want = scan.nextLine();
} while (want.equals("y") || want.equals("Y"));
}
public static void main(String[] args) {
new GuessNum();
}
}
Use want = scan.next(); instead of nextLine().
The reason for your problem is that following the preceding nextInt(), you're still on the same line, and nextLine() returns the rest of the current line.
Here's a smallest snippet to reproduce the behavior:
Scanner sc = new Scanner(System.in);
System.out.println("nextInt() = " + sc.nextInt());
System.out.println("nextLine() = " + sc.nextLine());
When you type in, say, 5 and then hit Enter, the output is:
nextInt() = 5
nextLine() =
That is, nextLine() did not block for your input, because the current line still has an empty string remaining.
For comparison, when you type in, say 5 yeah! and then hit Enter, then the output is:
nextInt() = 5
nextLine() = yeah!
Note that " yeah!" actually comes from the same line as the 5. This is exactly as specified in the documentation:
String nextLine(): Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
On half-open ranges
Assuming that the number to guess is between 1 and 10 inclusive, the following code is "wrong":
numRandom = rand.nextInt(9)+1; // this can only be in 1..9 range inclusive!
Here's an excerpt from the documentation of java.util.Random:
int nextInt(int n): Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
That is, like a lot of methods in Java's API, Random.nextInt(int) uses the half-open range, with inclusive lower bound and exclusive upper bound.
Related questions
Are upper bounds of indexed ranges always assumed to be exclusive?
Use scan.next()+ scan.nextLine(); instead
eg.
Scanner scan = new Scanner(System.in);
String s = scan.nextLine() +scan.nextLine();
Problem occurs because the last newline character for the last line of input is still queued in the input buffer and the next nextLine() will be reading the remainder of the line (which is empty).
So, when you use next it goes to the next token, then you can get the remaining input using nextLine()

Categories