Preventing input errors - java

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)

Related

Stuck with detecting next line from console

I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}
int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}
Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}

Check loop if input are all integer [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 6 years ago.
I'm making simple program where the user inputs a class number of a student(cn) and the grade of that student(ngrade). I was trying to add an exception that checks if the input of the cn and ngrade are integers. If not the user will be informed that it is invalid and asks to re enter the details.
problem: i did use while loop to check the inputs throughout the loop. but i'm getting a infinite loop.
CODE:
import java.io.*;
import java.util.*;
public class trrying {
public static void main(String[] args) {
int ngrade;
int cn;
int A = 0, B = 0, C = 0, D = 0, E = 0;
boolean test = false;
Scanner sn = new Scanner(System.in);
while (!test) {
try {
for (int i = 0; i <= 2; i++) {
System.out.println("Enter class number: ");
cn = sn.nextInt();
System.out.println("Enter numeric grade: ");
ngrade = sn.nextInt();
System.out.println("Letter Grade: ");
if (ngrade >= 90) {
A++;
System.out.println("A");
} else {
System.out.println("HELLO");
}
test = true;
}
test = false;
} catch (Exception e) {
System.out.println("ERROR! ");
// System.out.println("Enter class number: ");
}
}
}
}
One option to get the behavior you want would be to read in each input as a string, using Scanner#nextLine(), and then manually try to parse that input as an integer. If successful, accept that input and continue with your logic. If not successful, then catch the exception, and repeat the loop to get another user input.
for (int i=0; i <= 2; i++) {
String line = "";
while (true) {
System.out.println("Enter class number: ");
line = sn.nextLine();
try {
cn = Integer.parseInt(line);
break;
} catch(Exception e) {
System.out.println("Enter class number as an integer only.");
}
}
while (true) {
System.out.println("Enter numeric grade: ");
line = sn.nextLine();
try {
ngrade = Integer.parseInt(line);
break;
} catch(Exception e) {
System.out.println("Enter numeric grade as an integer only.");
}
}
System.out.println("Letter Grade: ");
if (ngrade >= 90) {
System.out.println("A");
}
else {
System.out.println("HELLO");
}
test = true;
}

Java try-catch statement inside while loop

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
}

Lonely Integer - Output is correct. But still getting additional message

Im trying to find the lonely integer in an array. My output is correct, but still getting the extra message. Please have a look at the code. I’m using Java to write the program.
Code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class LonelyInteger {
private static int inputArray[];
private static int inputLength;
private static final Scanner scanner = new Scanner(System.in);;
public static void main(String[] args) {
try {
if (getInput()) {
sortAndPrintArray();
findLonelyInteger();
} else {
System.out.println("OOPS, something is not right! Try again!");
}
} catch (NumberFormatException | InputMismatchException nfime) {
System.out.print("Number Format Exception or Input Mismatch Exception Occured: " + nfime);
} catch (Exception e) {
System.out.print("Exception Occured: " + e.getMessage());
}
}
private static boolean getInput() throws NumberFormatException, InputMismatchException, Exception {
System.out.print("Enter the array length: ");
inputLength = scanner.nextInt();
if (inputLength <= 0) {
return false;
}
inputArray = new int[inputLength];
System.out.println("Enter the array:");
for (int i = 0; i < inputLength; i++) {
inputArray[i] = scanner.nextInt();
}
return true;
}
private static void sortAndPrintArray() {
sortArray();
printSortedArray();
}
private static void sortArray() {
int temp = 0;
for (int i = 0; i < inputLength; i++) {
for (int j = 0; j < i; j++) {
if (inputArray[i] < inputArray[j]) {
temp = inputArray[i];
inputArray[i] = inputArray[j];
inputArray[j] = temp;
}
}
}
}
private static void printSortedArray() {
System.out.println("Sorted Array:");
for (int i = 0; i < inputLength; i++) {
System.out.print(inputArray[i] + " ");
}
System.out.println();
}
private static void findLonelyInteger() {
boolean foundLonelyInteger = false;
for (int i = 0; i < inputLength; i++) {
if ((i+1) == inputLength) {
System.out.println("Lonely Integer: " + inputArray[i]);
break;
}
if (inputArray[i] == inputArray[++i]) {
continue;
} else {
System.out.println("Lonely Integer: " + inputArray[i-1]);
foundLonelyInteger = true;
i--;
}
}
if (!foundLonelyInteger) {
System.out.println("Lonely integer not available!");
}
}
}
Here is my output, which is seen in Command Prompt:
Output:
Enter the array length: 5
Enter the array:
1
2
2
1
2
Sorted Array:
1 1 2 2 2
Lonely Integer: 2
Lonely integer not available!
You did not set the flag, in your findLonelyInteger() method's first if condition!
if ((i+1) == inputLength) {
System.out.println("Lonely Integer: " + inputArray[i]);
foundLonelyInteger = true; // --> HERE
break;
}
Command Prompt? Start using Eclipse! And learn debugging!
Set your foundLonelyInteger = true; while you are checking for if((i+1) == inputLength)

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