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.
Related
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;
}
}
}
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;
}
I have to keep inputting x and y coordinates, until the user inputs "stop". However, I don't understand how to parse the input from String to int, as whenever I do, I get back errors.
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
System.out.println("Enter x:");
String x = kb.nextLine();
if (x.equals("stop")) {
System.out.println("Stop");
break;
}
System.out.println("Enter y:");
String y = kb.nextLine();
if (y.equals("stop")) {
System.out.println("Stop"); }
break;
}
}
}
}
To Parse integer from String you can use this code snippet.
try{
int xx = Integer.parseInt(x);
int yy = Integer.parseInt(y);
//Do whatever want
}catch(NumberFormatException e){
System.out.println("Error please input integer.");
}
Nice way to do this in my opinion is to always read the input as a string and then test if it can be converted to an integer.
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
String input;
int x = 0;
int y = 0;
System.out.println("Enter x:");
input = kb.nextLine();
if (input.equalsIgnoreCase("STOP")) {
System.out.println("Stop");
break;
}
try {
x = Integer.parseInt(input);
System.out.println(x);
} catch (NumberFormatException e) {
System.out.println("No valid number");
}
}
}
}
With
String variablename = Integer.toString(x);
I am new in java. I have written a program in which the user chooses how many numbers he wants to add. If the user enters a string it will throw an exception and the programs tell the user to enter all details again.
My problem is i want the program to ask the user to re enter details from that number which he entered wrong.
Eg: the user chooses to add 4 numbers but he enters the third number as string, the program should ask the user to re-enter from the third number and not the entire details again.
My code is as follow:
import java.io.*;
import java.util.*;
class Add
{
public static void main(String args[]) throws Exception
{
boolean loop=true;
while(loop)
try
{
String yn;
do
{
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers to add: ");
int num=Integer.parseInt(s.next());
int a,sum=0;
for(int i=1;i<=num;i++)
{
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
} while(yn.equals("y")||yn.equals("Y"));
}
catch(Exception e)
{
System.out.println("Try Again\n");
}
}
}
You can resolve this, by placing the "retry" one level deeper in the code:
import java.io.*;
import java.util.*;
class Add {
public static void main(String args[]) throws Exception {
boolean loop=true;
Scanner s=new Scanner(System.in);
while(loop) {
try {
String yn;
do {
loop = true;
System.out.println("Enter how many numbers to add: ");
int num=Integer.parseInt(s.next());
int a,sum=0;
for(int i=1;i<=num;) {
try {
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;
i++;
}
catch(Exception e) {
System.out.println("Invalid input. Try Again.\n");
}
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
loop = yn.equals("y")||yn.equals("Y");
} while(loop);
}
catch(Exception e) {
System.out.println("Number of elements invalid. Try Again.\n");
}
}
}
}
As #Zhuinden indicates, one better uses Scanner.nextInt, since it is more generic...
Below code should help
int i =1;
while(i <=num){
System.out.println("Enter number["+i+"]: ");
try{
a=Integer.parseInt(s.next());
sum=sum+a;
i++;
}catch(NumberFormatException ex){
System.out.println("Please enter a valid interger");
}
}
Use additional method that reads single entry until it is valid number:
private static int readNumber(Scanner s) {
Integer value = null;
while (value == null) {
try {
value = Integer.parseInt(s.next());
} catch (NumberFormatException e) {
System.out.println("bad format, try again...");
}
}
return value;
}
Then you can use this method whenever you can read valid number:
System.out.println("Enter how many numbers to add: ");
int num = readNumber(s);
...
System.out.println("Enter number[" + i + "]: ");
a = readNumber(s);
....
Method getNumber(s) guarantee to return only when user give correct integer.
works according to what you want, but not ethical
import java.io.*;
import java.util.*;
class Add
{
public static void main(String args[]) throws Exception
{
boolean loop=true;int pos=0;int num=0,sum=0;
while(loop)
try
{
String yn;
do
{sum=0;num=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers to add: ");
num=Integer.parseInt(s.next());
int a;
for(int i=1;i<=num;i++)
{
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;pos=i;
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
} while(yn.equals("y")||yn.equals("Y"));
}
catch(Exception e)
{
Scanner s=new Scanner(System.in);
int a=0;
for(int i=pos+1;i<=num;i++)
{ System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;}
System.out.println("The Sum is:"+sum);
}
}
}
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
}
}