cannot catch the exception more than one time - java

when running the code, if I input any character other than number, the exeception "java.util.InputMismatchException" gets catched, but next time if I input any character other than number, the program gets terminated with error "Exception in thread "main" java.util.InputMismatchException". how to make it able to catch more than one simultaneous exceptions untill a valid input is given.
/*
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the
student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses
in an integer array and determine the frequency of each rating.
*/
import java.util.Scanner;
public class StudentPoll
{
static Scanner input=new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Rate the quality of food from 1 to 5." +
"\n1 being “awful” and 5 being “excellent”.\n");
int[] array=new int[10];
int num =0;
for(int i=0;i<array.length;i++)
{
do{
System.out.println("Student "+(i+1)+" Enter Your Response:");
try
{
num=input.nextInt();
}
catch(java.util.InputMismatchException e)
{
System.out.println("Enter numbers only.");
input.nextLine();
num=input.nextInt();
}
if(num<=0 || num>5)
{
System.out.println("Enter 1 to 5 only.");
}
}while(num<=0 || num>5);
array[i]=num;
}
int[] frequency=new int[6];
for ( int i = 0; i < array.length; i++ )
{
frequency[array[i]]=frequency[array[i]]+1;
}
System.out.printf("* :%d (awful)\n",frequency[1]);
System.out.printf("** :%d\n",frequency[2]);
System.out.printf("*** :%d\n",frequency[3]);
System.out.printf("**** :%d\n",frequency[4]);
System.out.printf("*****:%d (excellent)\n",frequency[5]);
}
}`

Because when first exception occur in the try block that is caught by the catch block. And if the user again give a invalid input then again the exception thrown. But there is no mechanism in your code to catch that exception. Therefore the main thread stopped. Catch block will not responsible to catch exception that is throw inside that block.
import java.util.Scanner;
public class StudentPoll
{
static Scanner input=new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Rate the quality of food from 1 to 5." +
"\n1 being “awful” and 5 being “excellent”.\n");
int[] array=new int[10];
int num =0;
for(int i=0;i<array.length;i++)
{
do{
System.out.println("Student "+(i+1)+" Enter Your Response:");
try
{
num=input.nextInt();
}
catch(java.util.InputMismatchException e)
{
input.next(); // consume the leftover new line
System.out.println("Enter numbers only.");
}
if(num<=0 || num>5)
{
System.out.println("Enter 1 to 5 only.");
}
}while(num<1 || num>5); // change in the logic
array[i]=num;
}
int[] frequency=new int[6];
for ( int i = 0; i < array.length; i++ )
{
frequency[array[i]]=frequency[array[i]]+1;
}
System.out.printf("* :%d (awful)\n",frequency[1]);
System.out.printf("** :%d\n",frequency[2]);
System.out.printf("*** :%d\n",frequency[3]);
System.out.printf("**** :%d\n",frequency[4]);
System.out.printf("*****:%d (excellent)\n",frequency[5]);
}
}

Your Problem statements is after the wrong input the program doesn't wait for next user input
You can achieve this my accepting the input via java.util.Scanner & making for loop within do while.
try the below code it should work as per your need.
/*
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the
student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses
in an integer array and determine the frequency of each rating.
*/
import java.util.Scanner;
public class StudentPoll {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Rate the quality of food from 1 to 5."
+ "\n1 being “awful” and 5 being “excellent”.\n");
int[] array = new int[10];
int num = 0;
do {
for (int i = 0; i < array.length; i++) {
System.out.println("Student " + (i + 1)
+ " Enter Your Response:");
Scanner sc = new Scanner(System.in);
try {
num = sc.nextInt();
} catch (java.util.InputMismatchException e) {
System.out.println("Enter numbers only.");
num = 0;
--i;
continue;
}
if (num <= 0 || num > 5) {
System.out.println("Enter 1 to 5 only.");
num = 0;
--i;
continue;
}
array[i] = num;
}
} while (num <= 0 || num > 5);
int[] frequency = new int[6];
for (int i = 0; i < array.length; i++) {
frequency[array[i]] = frequency[array[i]] + 1;
}
System.out.printf("* :%d (awful)\n", frequency[1]);
System.out.printf("** :%d\n", frequency[2]);
System.out.printf("*** :%d\n", frequency[3]);
System.out.printf("**** :%d\n", frequency[4]);
System.out.printf("*****:%d (excellent)\n", frequency[5]);
}
}

Because you do not have another try-catch statement in your catch statement, you can just re-run the loop if you want to catch the exception again. So you would replace:
catch(java.util.InputMismatchException e)
{
System.out.println("Enter numbers only.");
input.nextLine();
num = input.nextInt();
}
with:
catch(java.util.InputMismatchException e)
{
System.out.println("Enter numbers only.");
input.nextLine();
continue;
}

Related

How do I add the ability for the program to continue even after the first input is given?

I'm writing a Hailstone Sequence program and I want to add the ability for the program to keep calculating even after the first input and output is already printed. Basically, instead of re-running the program, you could keep giving inputs.
public class HailStoneSequence {
static Scanner MyScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter a number to generate the Hailstone Sequence for that number. ");
int num = MyScanner.nextInt(); //Taking input from user
while (num>1)
{
if (num%2 == 0)
{
num /= 2;
System.out.print(num+" ");
}
else
{
num = (num*3)+ 1;
System.out.print(num+" ");
}
}
}
}
Just surround the block of code with a while loop that checks if the input is for example 0, in that case 0 would mean the end of the execution.
import java.util.Scanner;
public class HailStoneSequence {
static Scanner MyScanner = new Scanner(System.in);
public static void main(String[] args) {
int num = 1;
while(num != 0) {
System.out.println("Enter a number to generate the Hailstone Sequence for that number. ");
num = MyScanner.nextInt(); //Taking input from user
while (num>1)
{
if (num%2 == 0)
{
num /= 2;
System.out.print(num+" ");
}
else
{
num = (num*3)+ 1;
System.out.print(num+" ");
}
}
}
}
}
You can use a while loop to keep your program running like so:
System.out.println("Enter a number to generate the Hailstone Sequence for that number:(0 to quit) ");
int num = MyScanner.nextInt(); //Taking input from user
while(num != 0){
//logic
System.out.println("Enter a number to generate the Hailstone Sequence for that number:(0 to quit) ");
num = MyScanner.nextInt(); //Taking input from user
}
Then at the end of your logic take the input again. the program will continue to run until the user enters a key(in this case, 0)
You can do something like this:
String input = "";
do {
// Your code here
System.out.println("Continue?");
input = MyScanner.next();
} while (!input.equals("exit");

Java Simple program using Loop structure [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
Sample input : 3456
Sample output :
Digits : 3, 4, 5, 6
Sum : 18
This is the code that I had try, but unfortunately it is wrong since i do not use loop.Please anybody can help me?
import java.util.Scanner;
public class Lab1_5 {
public static void main (String args[])
{
int insert1, insert2, insert3, insert4;
int sum ;
Scanner console = new Scanner(System.in);
System.out.print("Please enter First Number: ");
insert1 =console.nextInt();
System.out.print("Please enter Second Number: ");
insert2 =console.nextInt();
System.out.print("Please enter Third Number: ");
insert3 =console.nextInt();
System.out.print("Please enter Fourth Number: ");
insert4 =console.nextInt();
System.out.println("Digits: "+ insert1+","+insert2+","+insert3+","+insert4);
sum = insert1+insert2+insert3+insert4;
System.out.print("Sum: "+ sum);
}
}
You can use a for loop as seen in this example:
public static void main(String args[]){
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Number: ");
//get number input:
int num = sc.nextInt();
//convert number to String:
String str = Integer.toString(num);
//iterate through each char in string:
for(int i = 0; i < str.length(); i++){
//convert char value to int, and add it to the sum:
sum += Character.getNumericValue(str.charAt(i));
}
}
Here's how you can get the sum with a loop:
What this does is it gets one number from the user and loops trough the individual digits of the number.
public static void main(String[] args)
{
int sum = 0;
Scanner console = new Scanner(System.in);
System.out.print("Please enter a Number: ");
String num = console.nextLine();
try
{
num = num.trim();
int index = 0;
int n = Integer.parseInt(num);
System.out.print("Digits: ");
while (n > 0)
{
int digit = n % 10;
sum += n % 10;
n = n /10;
char d = num.charAt(index++);
System.out.print(d + ", ");
}
System.out.print("Sum: " + sum);
}
catch (NumberFormatException e)
{
System.out.print("Invalid Number entered");
}
// Close the scanner
console.close();
}
Here is another version that won't give you an integer overflow for input values over Integer.MAX_VALUE.
public static void main(String[] args)
{
int sum = 0;
Scanner console = new Scanner(System.in);
System.out.print("Please enter a Number: ");
String num = console.nextLine();
try
{
num = num.trim();
System.out.print("Digits: ");
for (int i = 0; i < num.length(); i++)
{
char d = num.charAt(i);
int n = Integer.parseInt(String.valueOf(d));
sum += n;
System.out.print(d + ", ");
}
System.out.print("Sum: " + sum);
}
catch (NumberFormatException e)
{
System.out.print("Invalid Number entered");
}
console.close();
}
public class Lab1_5 {
public static void main (String args[])
{
int insert;
int sum ;
int[] numArray = new int[4];
Scanner console = new Scanner(System.in);
for(int i=0; int<4; i++){
if(i == 1) {
System.out.println("Please enter First Number: ");
} else {
System.out.println("Please enter the next Number: ");
}
numArray[i] = console.nextInt();
sum += numArray[i];
}
System.out.println("Digits: "+ numArray[0]+","+numArray[1]+","+numArray[2]+","+numArray[3]);
System.out.println("Sum: "+ sum);
}
}

How can the numbers in array count to odd or even number?

I wrote the code in java but it does not count to odd or even. It only counts in even numbers. If I miss anything?
import java.util.Scanner;
public class OddEven {
//create the check() method here
static void check(int[] x, int n) {
x = new int[100];
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
x[n++] = in.nextInt();
}
if (x[n] % 2 == 0) {
System.out.println("You input " + n + " Even value");
} else if (x[n] % 2 == 1) {
System.out.println("You input " + n + " Odd value");
}
while (in.hasNextInt()) ;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//read the data here
System.out.print("Input a list of Integer number : ");
int[] x = new int[100];
int n = 0;
check(x, n);
in.close();
}
}
Check these loops:
This essentially puts all the ints in x.
while(in.hasNextInt()) {
x[n++] = in.nextInt();
}
This just loops until it doesn't have an it.
while(in.hasNextInt());
Which means, the if block is not even in a loop. However, the first while loop post increments n, which means even if you have one number, it will assign:
x[0] = 123;
but then n=1. which means, the if block will check the next field. But by default it is 0, which will display that it is even.
This would make more sense:
x= new int[100];
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
x[n] = in.nextInt();
if(x[n]%2==0){
System.out.println("You input "+n+" Even value");
}else if(x[n]%2==1){
System.out.println("You input "+n+" Odd value");
}
n++;
}

JAVA Display how many ODD and EVEN numbers using only one counter?

I have a program here in java that asks the user to input ten integer numbers and would print out how many are ODD and how many are EVEN.
import java.io.*;
public class Count {
public static void main(String[] args) {
int i, , even_ctr=0, odd_ctr = 0;
String input = " ";
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
n = Integer.parseInt(input);
if(n % 2 == 0)
even_ctr++; //counter for even
if(n % 2 == 0)
odd_ctr++; //counter for odd
}System.out.println("EVEN: " + even_ctr + "\nODD: "+ odd_ctr);
}
}
I am trying to change the program by using only one counter instead of two counter. Anyone knows how?
import java.io.*;
public class NewClass {
public static void main(String[] args) {
int i,n, even_ctr=0;
String input = " ";
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
n = Integer.parseInt(input);
if(n % 2 == 0)
even_ctr++;
}System.out.println("EVEN: " + even_ctr + "\nODD: "+ (10-even_ctr));
}
}
Just keep the first counter incrementing for ODD number detection (OR EVEN but either of them). At the end of the computation, if ODD counter = 4, and total number of numbers entered are 10, then 10 - ODDcounter = 10 - 4 = 6 are the number of even numbers.
For this it looks like it would be equally useful to use the Scanner so that you can avoid the step of having to parse the string.This also would require you to import java.util.Scanner but you can use the scanner to take in strings or integers.
Scanner in = new Scanner(System.in);
int input;
int evenCount = 0;
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.nextInt();
}catch(IOException e){
System.out.println("Error!");
}
if(input % 2 == 0)
evenCount++;
}
System.out.println("EVEN: " + evenCounter + "\nODD: "+ (10 - evenCounter);
Include in.close(); at the end of the method to close the scanner or the reader which ever you use.
package evenoddten;
import java.util.Scanner;
public class EvenOddTen {
public static void main(String[] args) {
int num1 = 0, num2, even = 0, count = 0;
Scanner scr = new Scanner(System.in);
System.out.print("Total Nos:");
num2 = scr.nextInt();
while(count<num2) {
System.out.println("Enter no:");
num1 = scr.nextInt();
if (num1%2 == 0) {
even = even + 1;
}
count = count+1;
}
System.out.println("Even nos are:"+even);
System.out.println("Odd nos are:"+(count - even));
}
}

Loop to validate user input

I am fairly new to Java and I am trying to write a small program that asks a user to enter 3 integers between 1-10, stores them in an array and then adds up the integers and tells the user the answer. I have written this so far and it works:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 3 numbers in the range 1 to 10: ");
for (int i = 0; i < numArr.length; i++) {
numArr[i] = keyboard.nextInt();
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My problem is I am also meant to validate the input as in if they enter a double, a string or a number outside the 1-10 range. I have tried a while loop but I just cannot get the program to work, below is what I have so far. If I take out the first while loop the second one works i.e. it checks if it is an integer:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < numArr.length; i++) {
//check if between 1 and 10
while (i > 10 || i < 1) {
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt()) {
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
numArr[i] = keyboard.nextInt();
}
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
My question is how do I get it to check if it is an integer and if it is the range 1-10?
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
int[] numArr = new int[3];
int sum=0,x;
Scanner keyboard = new Scanner(System.in);
for(int i=0; i<numArr.length; i++)
{
//check if between 1 and 10
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt())
{
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
x = keyboard.nextInt();
if(x>0 && x<=10)
numArr[i]=x;
else{
System.out.println("Retry Enter a number in the range 1 to 10:");
i--;
}
}
for (int counter=0; counter<numArr.length; counter++)
{
sum+=numArr[counter];
}
System.out.println("The sum of these numbers is "+sum);
}
}
To check simple use Integer.parseInt() and catch the NumberFormatException (together with Scanner.next()).
Once format is correct you can do an int comparison (i>0 && i<11).
I suggest you to use NumberUtils under org.apache.commons.lang.math
It has isDigits method to check whether given string contains only digits or not:
if (NumberUtils.isDigits(str) && NumberUtils.toInt(str) < 10) {
// your requirement
}
Note that toInt returns zero for big numbers!
Maybe for just this reason adding a whole library seems unnecessary but for bigger projects you will need such libraries like Apache Commons and Guava
You can wrap the System in into a BufferedReader to read whatever the user has to input, then check if its an 'int' and repeat input from user.
I have modified your code a little bit to make it work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Feb11a {
public static void main(String[] args) throws NumberFormatException, IOException
// You may want to handle the Exceptions when calling the getInt function
{
Feb11a tester = new Feb11a();
tester.perform();
}
public void perform() throws NumberFormatException, IOException
{
int[] numArr = new int[3];
int sum = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < numArr.length; i++)
{
int anInteger = -1;
do
{
// First get input from user.
System.out.println("Enter a number in the range 1 to 10: ");
anInteger = getInt(in);
} while (anInteger > 10 || anInteger < 1); // then check for repeat condition. Not between 1 and 10.
numArr[i] = anInteger; // set the number into the array.
}
for (int counter = 0; counter < numArr.length; counter++)
{
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
public int getInt(BufferedReader br) throws NumberFormatException, IOException
{
String str = br.readLine();
int toReturn = Integer.parseInt(str);
return toReturn;
}
}

Categories