Java try-catch statement inside while loop - java

I have this method and it works fine. I need to put a try/catch statement so
the method can continue if the user puts in a letter. I don't know where to put the statement, It seems everywhere I put it it get's wrong. Could somebody please show me where to put this statement?
public void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
number = in.nextInt();
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}
if (!end) {
System.out.println("I cant find number " + number
+ " in the array, please try again ");
}
}
}

Your for loop I can't explain, you need only check values between 0 and 20,
And when you call try catch, you have to skip loop after exception
public static void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number=0;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
//check symbol
try{
number = Integer.valueOf(in.next());
}catch(Exception e)
{
System.out.println("It's not a number! ");
continue; //skip loop
}
if((number>=0)&&(number<=20))
{
System.out.println(array[number]);
end=true;
}
else
System.out.println("I cant find number " + number
+ " in the array, please try again ");
/* why do you use loop here???
* u need to check if number between 0-20
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}*/
}
}

public static void main(String[] args) {
Test test = new Test();
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
System.out.println("Please give an number between 0-20: ");
do{
try{
number = Integer.parseInt(in.next());
}
catch(Exception e){
System.out.println("Please give an number between 0-20: ");
number = -1;
}
}
while(!(number <= 20 && number >=0 ));
System.out.println(array[number]);
}

System.out.println("Please give an number between 0-20: ");
try{
number = in.nextInt();
}catch(Exception e){
number = 1; //Put random number of default number here
}

Related

Working on a Java Program that utilizes For Loops to separate Even, Odd, and Negative Inputted Integers. Try Catch Handler Gives Out-of-bounds Error? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 12 months ago.
I am working on a Java program that determines Evens, Odds, and Negative numbers from 12 inputted integers.
It then separates them into different arrays. The course I am following suggests building an exception handler and I utilized the Try-Catch Method for the Exception error I may receive.
It then creates an Out of Bounds error for counting these numbers when I enter a String.
I've commented on the area in which I have trouble reprompting the user. So far, I've tried prompting at the error with twelveInt [i] = in.nextInt(); and just in.next();.
Why is the program affected outside of the loop?
Here is the program:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
boolean ehandle = true;
for (int i = 0; i < twelveInt.length; i++) {
while(ehandle){
try{
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt [i] = in.nextInt();
ehandle = false;
}
catch(Exception e){
System.out.println("Please enter integers only");
// Unsure of what to add here to handle the errors and allow me to reprompt. in.next();
//does not work nor does twelveInt [i] = in.nextInt();
}
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
The problem in your code is that after you run your loop and enter your first number, you then define ehandle = false.
This means that you never enter the rest of your loop since you exit the while loop. Therefore, you never increment the values of countEven, countOdd, or countNeg.
This results in an error because when you try running this line: int [] evens = new int [countEven]; , countEven is still 0, so you get an error when you try to iterate it.
To avoid this error, you can modify your try catch error as so:
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
for (int i = 0; i < twelveInt.length; i++) {
System.out.println("Enter the #" + (i + 1) + " integer.");
boolean error = true;
while (error) {
try {
twelveInt [i] = in.nextInt();
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
error = false;
}
catch (Exception e) {
System.out.println("Please enter integers only");
in.next();
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
}
}
We first try taking in the user input, and if we get an exception error, we will use the catch so our code does not terminate. NOTE: we must do in.next() otherwise we will get an infinite loop (since integers leave a trailing newline, resulting in infinite exceptions).
I hope this helped! Please let me know if you need any further clarifications or details :)
If you want to reiterate your while(ehandle) loop when you get an exception, you can put continue in your catch block. But you should set ehandle back to true at the top of your for-loop.
for (int i = 0; i < twelveInt.length; i++) {
ehandle = true;
while (ehandle) {
try {
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt[i] = in.nextInt();
ehandle = false;
} catch(Exception e) {
System.out.println("Please enter integers only");
continue;
}
...

Scanner method .hasNextInt() and if statement - works only 1 time. For next loop - automatically (didn't wait any input) gives false

I tried to do an input check (need to take 3 numbers using Scanner).
Before that, I used a similar method (.hasNext(int)) in another task - everything worked fine. In this case, it doesn't work.
The first "while" loop works correctly, on the second loop .hasNextInt() returns false and loops the loop - not giving the opportunity to enter data.
boolean num1IsInt = false;
boolean num2IsInt = false;
boolean num3IsInt = false;
int scaicius1 = 0;
int scaicius2 = 0;
int scaicius3 = 0;
System.out.println("Įveskite 3 skaičiai, po viena after each press enter");
while (!num1IsInt) { //check first number is int
Scanner sc1 = new Scanner(System.in);
System.out.println("(1)Įveskyte pirmas skaicius");
if (sc1.hasNextInt()) {
scaicius1 = sc1.nextInt();
num1IsInt = true;
} else {
System.out.println("Not correct integer");
continue;
}
sc1.close();
}
while (!num2IsInt) { //check second number is int
Scanner sc2 = new Scanner(System.in);
System.out.println("(2)Įveskyte antras skaicius");
if (sc2.hasNextInt()) {
scaicius2 = sc2.nextInt();
num2IsInt = true;
} else {
System.out.println("Not correct integer");
continue;
}
sc2.close();
}
while (!num3IsInt) { //check third number is int
Scanner sc3 = new Scanner(System.in);
System.out.println("(3)Įveskyte trecias skaicius");
if (sc3.hasNextInt()) {
scaicius3 = sc3.nextInt();
num3IsInt = true;
sc3.close();
} else {
System.out.println("Not correct integer");
continue;
}
sc3.close();
}
System.out.println("First number = " + scaicius1);
System.out.println("First number = " + scaicius2);
System.out.println("First number = " + scaicius3);
Thank you - #Thomas Kläger. I change code like was at the begin (with only one Scanner, cose with 3 scanners it's didn't work) and add to all else statements reader for this "ghost element which loop my code".
boolean num1IsInt = false;
boolean num2IsInt = false;
boolean num3IsInt = false;
int scaicius1 = 0;
int scaicius2 = 0;
int scaicius3 = 0;
System.out.println("Įveskite 3 skaičiai, po viena after each press enter");
**Scanner sc = new Scanner(System.in);**
while (!num1IsInt) { //check first number is int
System.out.println("(1)Įveskyte pirmas skaicius");
if (sc.hasNextInt()) {
scaicius1 = sc.nextInt();
num1IsInt = true;
} else {
System.out.println("Not correct integer");
**sc.next();**
}
}
while (!num2IsInt) { //check second number is int
System.out.println("(2)Įveskyte antras skaicius");
if (sc.hasNextInt()) {
scaicius2 = sc.nextInt();
num2IsInt = true;
} else {
System.out.println("Not correct integer");
sc.next();
}
}
while (!num3IsInt) { //check third number is int
System.out.println("(3)Įveskyte trecias skaicius");
if (sc.hasNextInt()) {
scaicius3 = sc.nextInt();
num3IsInt = true;
} else {
System.out.println("Not correct integer");
sc.next();
}
}
sc.close();
System.out.println("First number = " + scaicius1);
System.out.println("First number = " + scaicius2);
System.out.println("First number = " + scaicius3);

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

Preventing input errors

I made this java code to input a number:
public static void main(String[] args)
{
int temp;
do{
Scanner scan = new Scanner(in);
out.print("enter number ");
temp = scan.nextInt();
if(temp >= 5 && temp <= 40){
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("|");
}
out.println();
y--;
z+=2;
}
for(int c = 0; c < 1 + temp/10; c++) {
for (int i = 0; i <= x / 2; i++)
{
System.out.print(" ");
}
System.out.println("|");
}
}else{
out.print("enter a number between 5 and 40");
}
}while(temp != 0);
}
}
However, this will return an error if I enter for example a letter or an invalid character. I would like to know how to, instead of making the program crash, make it display an error message and then asking again the question until the entry is correct?
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int temp=0;
boolean error=false;
do{
error=false;
try
{
Scanner scan = new Scanner(System.in);
System.out.print("enter number ");
temp = scan.nextInt();
if(temp==0)
break;
if(temp >= 5 && temp <= 40)
{
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
System.out.print(" ");
}
for(int k = 0; k<z; k++)
{
System.out.print("|");
}
System.out.println();
y--;
z+=2;
}
for(int c = 0; c < 1 + temp/10; c++)
{
for (int i = 0; i <= x / 2; i++)
{
System.out.print(" ");
}
System.out.println("|");
}
}
else
{
System.out.println("enter a number between 5 and 40");
}
}catch(Exception e)
{
System.out.println("Enter a valid number..try again");
error=true;
}
}while(temp != 0 || error);
}
}
When the error or exception occurs i.e. in scan.nextInt() an Exception is thrown and as you have not caught the exception the JVM stops executing the program.
So always write statements which can throw Exceptions within a try{ } block and immediately follow it with a catch(Exception e) {} block to catch the exception. If no exception occurs then catch block will not execute. If any error occurs inside try{} block : control jumps to catch block and it is executed and all other statements in try{} (after the erroneous line) are ignored.
try
{
..
error
.. // skipped
..
}
catch(Exception e)
{
...
...// handle exception
}
// control comes here after executing catch block
Read in the value from the user as a string and then try to parse it to a number in a try {} catch{} block, if an exception is thrown parsing it, tell the user only numbers are acceptable. if not continue processing with the number they gave you.
The Scanner has a method to check if the next token is an integer: hasNextInt.
You could do this:
package com.sandbox;
import java.util.Scanner;
public class Sandbox {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer:");
while (!scanner.hasNextInt()) {
System.err.println("Wrong! Enter an integer");
scanner.next();
}
System.out.println("Your integer was: " + scanner.nextInt());
}
}
This worked as you'd want on a windows console. I'm a little concerned it'll work incorrectly on Linux/Mac. Anyone mind testing it out for me? If this works, I like it best because there's no try/catch.
Extending from #Shouvik Roy's answer..
import java.util.Scanner;
public class Bingo {
public static void main(String[] args){
boolean isInt = false;
int temp;
System.out.print("enter a number ");
do{
Scanner scan = new Scanner(System.in);
try
{
temp = scan.nextInt();
isInt = true;
}
catch(Exception e)
{
System.out.println("Couldn't read number. Reason - "+e.getMessage());
System.out.println("Enter a valid number ");
}
}while(!isInt);
}
}
------------------Edit-------------------
boolean isInt = false;
System.out.print("enter a number ");
do{
try
{
Scanner scan = new Scanner(in);
temp = scan.nextInt();
isInt = true;
}
catch(Exception e)
{
System.out.println("Couldn't read number. Reason - "+e.getMessage());
System.out.println("Enter a valid number ");
}
}while(!isInt)

Java UserInputs from User to Contain no Strings

I'm making a program of battleship with the user going against the computers random inputs choices in an 8x8 grid.
What I'm having trouble with is that I don't want my program to crash if my user inputs a String, such as "asdfklasdn", "h", etc... It doesn't crash if its an integer, such as 1,5,etc. Is there any way to change this without changing the rows and columns to strings? If I use try catch, it just gives me an error in the if-else statements right after in the userFire method.
Any help will be much appreciated. Thank you!
import java.util.*;
import java.util.Scanner;
public class Battleship
{
Scanner input = new Scanner(System.in);
public static final boolean DEBUG = false;
public static void breakln()
{
System.out.println("─────────────");
}
public static void createBoard(String [][]board)
{
for( int r = 0; r<board.length; r++)
{
for(int c= 0; c<board[0].length; c++)
{
board[r][c] = "-";
}
}
}
public static void showBoard(String[][] board)
{
breakln();
for(int r =0; r<board.length;r++)
{
if(DEBUG == true)
{
for(int c = 0; c<board[0].length;c++)
{
System.out.print(" " +board[r][c]);
}
System.out.println("");
}
else
{
for(int c = 0; c<board[0].length;c++)
{
if(board[r][c].equals("S"))
{
System.out.print(" " + "-");
}
else
{
System.out.print(" " + board[r][c]);
}
}
System.out.println("");
}
}
breakln();
}
public static void createShip(String[][] board, int size)
{
if(Math.random()<0.5)
{
int col = (int)(Math.random()*5);
int row = (int)(Math.random()*7);
for(int i = 0; i<size; i++)
{
board[row][col+i]="S";
}
}
else
{
int col = (int)(Math.random()*7);
int row = (int)(Math.random()*5);
for(int i = 0; i<size; i++)
{
board[row+i][col]="S";
}
}
}
public static int userFire(String[][] board, int hits, int torps)
{
Scanner input = new Scanner(System.in);
int row,col;
System.out.println("You have: " + torps + " torpedos");
System.out.println("Select row to fire in: ");
row = input.nextInt();
while(row>8||row<1)
{
System.out.println("Invalid. Enter a valid row (1-8)");
row = input.nextInt();
}
System.out.println("Select column to fire in: ");
col = input.nextInt();
while(col>8 || col<1)
{
System.out.println("Invalid. Enter a valid column (1-8)");
col = input.nextInt();
}
if(board[row-1][col-1].equals("S"))
{
hits++;
System.out.println("HIT ");
board[row-1][col-1] = "×";
}
else
{
System.out.println("MISS");
board[row-1][col-1] = "Ø";
}
return hits;
}
public static void endOfGame(int hits, int torps)
{
if(hits<4)
System.out.println(" LOSE ");
if(torps<1)
System.out.println("You have lost all your torpedos.");
else
if(hits>=4)
{
System.out.println("WINNER");
}
System.out.println("");
}
public static void main(String[] args)
{
System.out.println(" BATTLESHIP ");
System.out.println("");
String[][] board = new String[8][8];
createBoard(board);
createShip(board,4);
int torps = 25;
int hits = 0;
while(torps>0 && hits<4)
{
showBoard(board);
hits = userFire(board,hits,torps);
torps--;
}
endOfGame(hits, torps);
}
}
I've tried everyone's answers, but I received errors in this code.
if(board[row-1][col-1].equals("S"))
{
hits++;
System.out.println("╠══ HIT ══╣");
board[row-1][col-1] = "×";
}
else
{
System.out.println("╠══ MISS ══╣");
board[row-1][col-1] = "Ø";
}
return hits;
Add try/catch block inside row=input.nextInt() or every variable who receives input;
Here's sample code
try{
row = input.nextInt();
}
catch(Exception)
{
}
Just catch the exception, e.g.
try {
row = input.nextInt();
} catch (InputMismatchException e) {
System.err.println("Input is not an integer"); // or do some error handling
}
Try this out:
System.out.println("Invalid. Enter a valid row (1-8)");
String userInput = input.next();
try {
row = Integer.parseInt(userInput);
} catch (NumberFormatException exp) {
// Failed : Invalid input. Take actions if required.
// May be prompt user for correct input
}
You can use while(input.hasNextInt()) and println a message saying you only want ints?
Or a catch block as BroSlow said.
try {
xxx = input.nextInt();
} catch(NumberFormatException nfe) {
doXXXLoop();
}
// ....
public void doXXXLoop() {
System.out.println("Not a valid number. Enter another:");
try {
xxx = input.nextInt();
} catch(NumberFormatException nfe) {
doXXXLoop();
}
}
Unlike other code, this will easy repeat until a valid int is entered. Replace XXX with Row or Col or whatever you want.

Categories