This question already has answers here:
How can I prevent java.lang.NumberFormatException: For input string: "N/A"?
(6 answers)
Closed 5 years ago.
Hi I'm a beginner in Java and I am trying to write this program where I can enter numbers, but that when I enter "done", I get the values that I called total, numberInputs. However when i run it and that i input "done" I get Exception in thread "main" java.lang.NumberFormatException: For input string: "done". Do you know how I can fix this please?
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at repeat.numberReader(repeat.java:15)
at repeat.main(repeat.java:23)
This is my code:
import java.util.Scanner;
public class repeat{
public void numberReader(){
Scanner myScanner = new Scanner(System.in);
int total = 1;
int numberInputs = 1;
String userInput;
do {
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
total = total + Integer.parseInt(userInput);
numberInputs++;
} while (!"done".equals(userInput));
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
public static void main(String[] args){
repeat instance = new repeat();
instance.numberReader();
}
}
Thank you for your help
As indicated by the website: NumberFormatException, the exception is caused by trying to convert a string that does not represent a number, to an integer, in this case: "done"
The exception is triggered in this line:
total = total + Integer.parseInt(userInput);
You can avoid and handle this exception as follows:
public class repeat{
public void numberReader(){
Scanner myScanner = new Scanner(System.in);
int total = 1;
int numberInputs = 1;
String userInput;
boolean done = false; // Stop when true
do {
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
try{ // Managing the exception
total = total + Integer.parseInt(userInput);
} catch(NumberFormatException e){
if ("done".equals(userInput)){ // it's done!!!!
done = true;
}
}
numberInputs++;
} while (!done);
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
public static void main(String[] args){
repeat instance = new repeat();
instance.numberReader();
}
}
Read more about the try / catch
The problem with your code is in this line
total = total + Integer.parseInt(userInput);
Suppose user enters the String "done".
now your code will try to parse the string to integer i.e.
total=total+Integer.parseInt("done");
Therefore , NumberFormatException will occur.
The correct code will be
import java.util.Scanner;
public class repeat{
public void numberReader(){
Scanner myScanner = new Scanner(System.in);
int total = 1;
int numberInputs = 1;
String userInput;
while (true)
{
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
if("done".equals(userInput))
{
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
break;
}
else
{
total = total + Integer.parseInt(userInput);
numberInputs++;
}
}
}
public static void main(String[] args){
repeat instance = new repeat();
instance.numberReader();
}
}
You are checking userInput for the value "done", but you do it AFTER the call to Integer.parseInt(). Calling Integer.parseInt("done") is throwing the NumberFormatException as the string "done" cannot be parsed as an integer.
do {
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
***ERROR HERE***
total = total + Integer.parseInt(userInput);
numberInputs++;
} while (!"done".equals(userInput));
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
You can resolve this a couple of ways. The simplest would be to reorder your code so that you check the input immediately after receiving it and only parse it after. This does require having the prompt twice though (once before the loop, and once at the bottom of it. This will also have issues if the first entry is "done" as a do-while loop always executes at least one time. You could change to a standard while loop to avoid this. This also will not handle strings other than your expected "done" string.
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
do {
total = total + Integer.parseInt(userInput);
numberInputs++;
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
} while (!"done".equals(userInput));
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
Alternatively, you can also implement error handling to catch and handle the exception, but that is a bit more complicated. This sounds like homework, and error handling is probably beyond your scope, so i'd just consider the first option.
As a side note, you should consider changing "done".equals(userInput) to userInput.equals("done"). They are functionally identical, however the second statement is much more clear what your intent is, which is to see if userInput is "done". The first is harder for yourself and others to read and understand.
you need to check if input is "done" before using Integer.parseInt(userInput)
do {
System.out.println("Enter a number: ");
userInput = myScanner.nextLine();
if(!"done".equals(userInput)){
total = total + Integer.parseInt(userInput);
numberInputs++;
}
} while (!"done".equals(userInput));
System.out.println(total + "" + numberInputs + "" + (total / numberInputs));
}
Related
I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
I have created a program that allows a user to keep guessing numbers until they either guess the correct number or enter end. I have used a do-while loop to do this. When I create a new scanner inside the loop body it works as expected. However if I create it outside the loop body, it works fine if the input is integers or the first input is end However if the input end follows integer inputs it doesn't
pick up the nextLine() until the next loop. Is there a way to do this without having to creat a new scanner object each time.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
do {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.nextLine();
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}while(number != answer && !(input.equals("end")));
}
Example output for when end follow an integer input:enter code here
number is: 3
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
end
input is:
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
input is: end
Hope you enjoyed the game
input before while is: end
you can solve this by using a while loop .
See the following code.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
while(!input.equals("end")) {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.next(); //Edited here . Changed nextLine() to next().
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}
}
In here , at first , input will always be empty String . On while loop, it gets assigned to your String input i.e, end . Till it encounters end , your loop will be running.
Edited
Change input=sc.nextLine(); to input=sc.next(); . This is because , your scanner waits for next Line and doesn't consider "end" as input string .
I'm trying to make a system that asks the user how many times they want a phrase to be repeated and then it checks if the answer is an integer or a string. The program works well when I don't try to implement this system and leave it just at asking the phrase and how many times it should be repeated but it falls appart when I try to check if the amount of times is an integer or not.
import java.util.*;
public class Phrase {
public static Scanner phraseScan = new Scanner (System.in);
public static Scanner amountScan = new Scanner (System.in);
public static void main (String[] args ) {
System.out.println("What phrase do you want repeated?");
String phrase = phraseScan.nextLine();
int phraseLoops = 0;
System.out.println("How many " + phrase + "s" + " do you want?");
int desiredPhraseLoops = amountScan.nextInt();
for (;;) {
if (!amountScan.hasNextInt()) {
System.out.println("Integers only please");
amountScan.next();
}
desiredPhraseLoops = amountScan.nextInt();
if (desiredPhraseLoops >= 0) {
System.out.println("Valid amount!");
continue;
} else {
break;
}
}
System.out.println(desiredPhraseLoops + " " + phrase + "s coming your way!");
do {
System.out.println(phrase);
phraseLoops++;
} while (phraseLoops != desiredPhraseLoops);
System.out.println("You printed " + phraseLoops + " " + phrase + "s" );
}
}
What I've tried:
try {
desiredPhraseLoops = amountScan.nextInt();
} catch (InputMismatchException exception) {
System.out.println("This is not an integer.");
}
if (!amountScan.hasNextInt()) {
System.out.println("Good.");
} else {
System.out.println("Enter an Integer please.");
}
Any time I tried anything, it would ask which phrase I wanted and how many times I wanted it repeated. And then the program just stopped afterward, no matter if I put in an integer or a string, it just didnt give me any other prompts.
The output is this:
What phrase do you want repeated?
Test
How many Tests do you want?
3
And that's it.
To begin with, just use one Scanner object. You don't need more than that for keyboard input.
If you like, you can just stick with the Scanner#nextLine() method, for example:
Scanner userInput = new Scanner(System.in);
String phrase = "";
while (phrase.equals("")) {
System.out.println("What phrase do you want repeated?");
phrase = userInput.nextLine();
// VALIDATION:
// Was anything other than a empty string (spaces)
// or longer than 2 characters supplied?
if (phrase.trim().equals("") || phrase.length() < 3) {
// Nope!
System.err.println("Invalid Input!. Enter a proper phrase!");
phrase = "";
}
// Yes, allow the prompt loop to exit.
}
String phraseLoopsNumber = "";
while (phraseLoopsNumber.equals("")) {
System.out.println("How many " + phrase + "s" + " do you want?");
phraseLoopsNumber = userInput.nextLine();
// VALIDATION:
// Did the User supply a string representation of an integer value?
if (!phraseLoopsNumber.matches("\\d+")) {
// Nope!
System.out.println("Invalid Input (" + phraseLoopsNumber + ")! An integer value is expected!");
phraseLoopsNumber = "";
}
// Yes he/she/it did...Allow prompt loop to exit.
}
int numberOfLoops = Integer.parseInt(phraseLoopsNumber);
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
In the above code, the String#matches() method was used along with a small Regular Expression (RegEx). The "\\d" expression passed to the matches() method checks to see if the string it is working against contains all (1 or more) digits.
If however you're hell bent on using the Scanner#nextInt() method then you can do it this way:
int numberOfLoops = -1;
while (numberOfLoops == -1) {
System.out.println("How many " + phrase + "'s" + " do you want?");
// Trap any input errors against the Scanner.nextInt() method...
// This would be a form of validation.
try {
numberOfLoops = userInput.nextInt();
// Consume the newline from ENTER key in case a nextLine() prompt is next.
userInput.nextLine();
} catch (Exception ex) {
System.out.println("Invalid Input! An integer value is expected!");
// Consume the newline from ENTER key in case a nextLine() prompt is next.
// The first one above would of been skipped past if nextInt() threw an exception.
userInput.nextLine();
numberOfLoops = -1;
continue; // continue loop so as to re-prompt
}
// Further Validation:
// Did the User supply a number greater than 0?
if (numberOfLoops < 1 ) {
// Nope!
System.out.println("Invalid Input (" + numberOfLoops + ")! A value 1 or greater is expected!");
numberOfLoops = -1;
}
// Yes he/she did...Allow prompt loop to exit.
}
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
I have to do a program that returns the reverse of a number that is input by a user, event the numbers that start and finish with 0 (ex. 00040, it would print 04000)
I was able to do the reverse of the number, but it doesn't print out the 0's and I can't use String variables, just long variables or integers.
Here is my code:
import java.util.Scanner;
public class Assignment_2_Question_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Welcome to Our Reversing Number Program");
System.out.println("-----------------------------------------");
System.out.println();
System.out.println("Enter a number with at most 10 digits:");
long number = keyboard.nextInt();
long nbDigits = String.valueOf(number).length();
System.out.println("Number of digits is " + nbDigits);
System.out.print("Reverse of " + number + " is ");
long revNumber = 0;
while (number > 0){
long digit = number % 10;
if (digit == 0){ // The teacher told me to add this
nb0 ++; // need to not take into account the 0's inside the number
}
revNumber = revNumber * 10 + digit;
number = number/10;
}
for (int i = 0; i < nb0; i++) { // This will print the number of 0's counted by the if statement and print them out.
System.out.println("0");
}
System.out.println(revNumber);
String answer;
do{
System.out.println("Do you want to try another number? (yes to repeat, no to stop)");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes")){
System.out.println("Enter a number with at most 10 digits:");
long otherNumber = keyboard.nextInt();
long nbrDigits = String.valueOf(otherNumber).length();
System.out.println("Number of digits is " + nbrDigits);
System.out.print("Reverse of " + otherNumber + " is ");
long reversedNumber = 0;
while (otherNumber != 0){
reversedNumber = reversedNumber * 10 + otherNumber%10;
otherNumber = otherNumber/10;
}
System.out.println(reversedNumber);
}
else
System.out.println("Thanks and have a great day!");
}while(answer.equalsIgnoreCase("yes")&& !answer.equalsIgnoreCase("no"));
}
}
Can someone help me? Thank you
Probably not what is intended but clearly (based on problem statement) you must see all digits entered (to include leading 0's) otherwise it is an "impossible solution" - and you state you cannot receive input as a String...
So this snippet reads one digit at a time where each digit is received as an int:
Scanner reader = new Scanner(System.in);
reader.useDelimiter(""); // empty string
System.out.print("Enter number: ");
while (!reader.hasNextInt()) reader.next();
int aDigit;
int cnt = 0;
while (reader.hasNextInt()) {
aDigit = reader.nextInt();
System.out.println("digit("+ ++cnt + ") "+aDigit);
}
System.out.println("Done");
Prints (assume user enter 012 (enter)):
Enter number: digit(1) 0
digit(2) 1
digit(3) 2
Done
You naturally have more work to do with this but at least you have all user entered digits (including leading zeros).
You can use buffer reader;
Like this given code And if you want to do some arithmetic operations in the numbers then you can convert it into int using parseInt method.:-
import java.util.Scanner;
import java.lang.*;
class Main {
public static void main(String args[])
{
System.out.println("ENTER NUM");
Scanner SC = new Scanner(System.in);
String INP = SC.nextLine();
StringBuffer SB = new StringBuffer(INP);
SB.reverse() ;
System.out.println(SB);
}
}
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
If a user places anything else under Enter your age other than a number, how do I make it say that the input is not correct and ask again?
You can get the line provided by the user, then parse it using Integer.parseInt(String) in a do/while loop as next:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
A better approach that avoids catching an Exception based on https://stackoverflow.com/a/3059367/1997376.
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
No need to declare a variable scanner so often, simply once
care with nextLine(); for strings; presents problems with blanks, advise a .next();
use do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
use blocks try{ .. }catch(Exception){..}
to catch exceptions mismatch-input-type exception is when the input is not what I expected in the example enter a letter when a number expected
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);