NumberFormatException not wrking java - java

I'm new to this I can't figure it out how to break the loop.
`````````` Java```````````
public static void main(String[] args) {
Scanner input= new Scanner (System.in) ;
System.out.println("Enter number list:");
try {
String data = input.nextLine();
ArrayList<Integer> myArray = new ArrayList<Integer>();
int num;
while (true){
num = Integer.parseInt(data);
myArray.add(num);}
}
catch (NumberFormatException e) {
e.printStackTrace();}

You should read new inputs inside your loop:
try {
...
while (true) {
num = Integer.parseInt(data);
myArray.add(num);
}
}
catch (NumberFormatException e) {
};
Currently you are adding the same input infinite times to your List.
P.S. perhaps you shouldn't use an infinite while loop. How do you plan to finish reading the inputs? By catching a NumberFormatException when the user enters an invalid number? It's not a good practice to use exceptions as part of your logic.

Thank you got it to work
while(true) {
Scanner input= new Scanner (System.in) ;
System.out.println("Please enter a number or anything else to stop:");
String data = input.nextLine();
int num;
try{
num = Integer.parseInt(data);
myArray.add(num);
int arraySize;
arraySize = myArray.size();
Collections.sort(myArray);
} catch (NumberFormatException e) {
break;
}
}
}

Related

how to use alternative of 'goto' in Java

How can I use any alternative to 'goto' in java?
I tried using break label. But since I am not breaking out of any loop, it is giving undefined label error.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
label1:
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{label2:
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label2
}
}
}
}
I was terminating the program on invalid input. But I need to execute the same lines on invalid input.
Rather than wanting to go to a specific point explicitly, wrap the bit you might want to repeat in a loop. If you don't want to execute the loop again, break.
For the first one:
while (true) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
// Nothing required to continue loop.
}
}
For the second one, wrap the loop body in loop:
for(int i=0; i<marksArray.length; i++)
{
while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
Or, probably better, write a method wrapping this loop:
int getInt(BufferedReader br) throws IOException {
while (true) {
try
{
return Integer.parseInt(br.readLine().trim());
} catch(NumberFormatException e) {
System.out.println("Please enter a whole number.");
}
}
}
and then call this method:
System.out.println("Enter no. of subjects");
int subNo = getInt(br);
for(int i=0; i<marksArray.length; i++) {
System.out.println("Enter marks for subject " + (i+1));
marksArray[i] = getInt(br);
}
This code snippet will loop until a correct number is inserted, in this example (it solves your first goto problem)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean noNumberEntered; //Default on false
System.out.println("Enter no. of subjects");
//TODO: check if input is integer
while(!noNumberEntered){
try
{
subNo = Integer.parseInt(br.readLine().trim());
noNumberEntered = true;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
I have reformatted your code a little bit. My basic idea was: All of the goto statements can be written in equivalent loops. The first one has now been made with a while loop, which terminates ones there comes NO exception. As for the second label, that has been done with the same mechanism (so a while-loop), however, with a label that can be exited/terminated with a "break + nameOfYourLable" - statement.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goToLabel1 = true;
while (goToLabel1) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
goToLabel1 = false; //parsing succeeded, no need to jump to label1
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{
label2: while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break label2;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
}
}
You can use a do while loop and a boolean instead, like that :
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goodEntry = true;
do {
goodEntry = true;
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
goodEntry = false;
}
} while(!goodEntry);
}
You can do the same with your second goto.
There are many ways to do that (with while loop and a boolean, with breaks...), but loops are better then goto.

Ask user to input a double instead of a String without making the program shutdown

Hy, I wrote this piece of code where I'm asking the user to input a number:
public static double[] getscores()
{
int numscores=8;
double score[] = new double[numscores];
for (int a=0;a<numscores;a++)
{
Scanner ip=new Scanner(System.in);
System.out.println("Enter a score");
score[a]=ip.nextDouble();
}
return score;
}
In the eventuality where the user accidentally enters a String, how am I supposed to tell him to input a number without making the program shut down? Thanks You
You should catch the exception thrown when the user doesn't input a double, ask the user to try again, and keep looping there until the user inputs a double. Alternatively, you can use while(true) and a break statement instea of a do { ... } while. Perhaps that is a bit shorter, but this is more readable.
Use a BufferedReader instead, because Scanner does not consume the input if it fails to parse it, so you'll get stuck in an infinite loop.
public static double[] getScores() throws IOException {
final int NUM_SCORES = 8;
double[] score = new double[NUM_SCORES];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < NUM_SCORES; i++) {
System.out.println("Enter a score:");
boolean isDouble = false;
do {
try {
score[i] = Double.parseDouble(br.readLine());
isDouble = true;
} catch (NumberFormatException e) {
System.out.println("You didn't enter a double. Please try again!");
}
} while (!isDouble);
}
br.close();
return score;
}
The user is always entering a String; Scanner#nextDouble() is a convenience method to interpret String input as a double.
Write a method that keeps reading input until a double is entered:
static double readDouble(Scanner scanner) {
double score;
while (true) {
System.out.println("Enter a score");
String input = scanner.nextLine();
try {
score = Double.parseDouble(input);
break;
} catch (NumberFormatException e) {
System.out.println("'" + input + "' is not a valid score");
}
}
return score;
}
then call it from your loop:
score[a] = readDouble(ip);
A quick but "dirty" solution would be by using try-catch:
public static double[] getscores() {
int numscores = 8;
double score[] = new double[numscores];
for (int a = 0; a < numscores; a++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter a score");
try{
score[a] = ip.nextDouble();
} catch(InputMismatchException ime) {
System.out.println("Wrong input");
a--;
}
}
return score;
}

Java, Exception works properly but the user does not get the chance to input again and in console the programs doesn't stop

I want the user to put only integers and if he enters anything else he should get my error and should be asked to input again.
But this code is not working as I want my program to be.
Please help me for this and other suggestion are also welcome.
//this is a separate main file
import java.util.*;
public class SolMul {
public static void main(String[] args) {
int g = 1;
Scanner input = new Scanner(System.in);
do{
try{
System.out.println("Please enter the number you want the table for: \n");
int z = input.nextInt();
System.out.println("Upto what number you want the table:\n");
int y = input.nextInt();
Solve multiplyObj = new Solve();
multiplyObj.multiply(z, y);
g = 2;
}catch(InputMismatchException e){
System.out.println("Error");
}
}
while(g==1);
input.close();
}
}
//this is a separate class file in a new window
public class Solve {
public void multiply(int number,int upto){
for (int x = 1; x <= upto; x ++){
System.out.printf("%d X %d = %d \n",number,x,number*x );
}
}
}
First,
input.nextInt()
doesn't capture newline. So you need to replace that with input.nextLine().
int z = Integer.parseInt(input.nextLine());
int y = Integer.parseInt(input.nextLine());
You can add an Exception catch block to handle any parsing errors. Making those changes to your code.
public static void main(String[] args) {
int g = 1;
Scanner input = new Scanner(System.in);
do {
try {
System.out.println("Please enter the number you want the table for: \n");
int z = Integer.parseInt(input.nextLine());
System.out.println("Upto what number you want the table:\n");
int y = Integer.parseInt(input.nextLine());
Solve multiplyObj = new Solve();
multiplyObj.multiply(z, y);
g = 2;
} catch (InputMismatchException e) {
System.out.println("Error -- input again");
}catch (Exception e) {
System.out.println("Error -- input again");
}
}while (g == 1);
input.close();
}
In addition to
catch(InputMismatchException e){
System.out.println("Input Mismatch Error");
}
Add another after that:
catch(Exception e){
System.out.println("Other Error");
}
Instead of input.nextLine(), use input.next()
Then check again

How do I prompt a user until they enter a valid integer?

Valid integer being a letter. I don't know the command to make it check the strings, nor do I know where to find it. Any help would be appreciated.
import java.util.Scanner;
public class Stringtest{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int test = 10;
while (test>0){
System.out.println("Input the maximum temperature.");
String maxTemp = input.nextLine();
System.out.println("Input the minimum temperature.");
String minTemp = input.nextLine();
}
}
}
Use the nextInt() to get the next integer value.
You should try/catch it in case user types a non-integer value.
Here's an example:
Scanner input = new Scanner(System.in);
// infinite loop
while (true){
System.out.println("Input the maximum temperature.");
try {
int maxTemp = input.nextInt();
// TODO whatever you need to do with max temp
}
catch (Throwable t) {
// TODO handle better
t.printStackTrace();
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = input.nextInt();
// TODO whatever you need to do with min temp
}
catch (Throwable t) {
// TODO handle better
t.printStackTrace();
break;
}
}
Just use input.nextInt(), and then a simple try-catch for an invalid int value.
You shouldn't try to save temperature indexes as Strings either.
You should use Integer.parseInt i.e User can enter any String and then you can check if it is an integer using this api, if it is not integer you will get an exception and then you can for another entry from user. Check below link for usage.
http://www.tutorialspoint.com/java/number_parseint.htm
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
Maybe you can do something like this:
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf("\"%s\" is not a valid number.\n", input);
}
number = scanner.nextInt();
} while (number < 0);

I am Facing issues in Scanner Class in java

If I enter the wrong input(example , if I enter String instead of Integer) loop is not ending, it wont get input next time. Here(below) i attach the entire program. can you please help this?. Thanks in advance!!!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
*
* #author Nithish
*
*/
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
e.printStackTrace();
}
}
}
}
On an InputMismatchException you are doing i--, so the loop condition is modified to prevent the loop from ending without the needed input. If you read the API documentation for Scanner.nextInt() you should notice the following:
If the translation is successful, the scanner advances past the input that matched.
This means that if the input cannot be translated to int, the scanner does not advance. So on the next invocation of nextInt() it will re-read the exact same, non-int, input and fail again. You will need to read past that non-integer token before attempting to get an int again.
Again, don't mess with the loop index inside of the loop as this can cause problems down the road. Instead use a while loop which is much cleaner and much easier to debug 3 months from now:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean done = false;
int result = 0;
while (!done) {
try {
System.out.print("Enter the value: ");
String temp = scanner.nextLine();
result = Integer.parseInt(temp);
done = true;
} catch (NumberFormatException e) {
System.out.println("Please only enter integer data");
}
}
scanner.close();
}
}
what about the below?
Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
System.out.println("Enter the value");
if (src.hasNextInt()) {
i = src.nextInt();
System.out.println("Thank you! (" + i+ ")");
}
else
{
System.out.println("Please only int");
}
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
//e.printStackTrace();
scanner.nextLine(); //you can add this here.
//scanner.next(); you can also use this
}
}

Categories