I am supposed to write a program that will prompt the user to enter the hotel rooms that are occupied. Once that is done the user enters -1 and is prompted to enter a random hotel number. If the hotel room is occupied, it prints occupied. If the room is unoccupied, it printer unoccupied. I can't seem to figure out why the unoccupied won't print. Suggestions?
import java.util.Arrays;
import java.util.Scanner;
public class GoughAndreaChapter9
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int [] arr=new int[100];
int counter=0;
int currval=0;
System.out.println("Please enter an occupied hotel room number, -1 to quit ");
do
{
currval = sc.nextInt();
if(currval==-1)
break;
if(currval>0)
arr[counter++]=currval;
}
while(currval !=-1);
// sort using java API
int [] temparr=new int[counter];
for(int i = 0; i<counter; i++)
{
temparr[i] = arr[i];
}
arr = temparr;
Arrays.sort(arr);
//binary search.
int low=0;
int high = counter-1;
System.out.println("Please enter a room to search for: ");
currval = sc.nextInt();
int status=0;
int mid;
while(low<high)
{
if(arr[low]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
else if(arr[high]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
mid = low+high/2;
if(arr[mid]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
else if(arr[mid]<currval)
{
low=mid;
}
else if(arr[mid]<currval)
{
high = mid;
}
}
if(status==0)
System.out.println("Unoccupied");
}
}
Don't ofuscate! Do this:
Room.java
public class Room {
private boolean isOccupied;
public Room() {
this.isOccupied = false;
}
public boolean obtainTheRoom() {
if(!isOccupied) this.isOccupied = true;
return !isOccupied;
}
}
Main.java
import java.util.Scanner;
public final class Main {
private static final int ROOM_AMOUNT = 50;
private static int actualRoom;
private static Scanner cmdin = new Scanner(System.in);
public static void main(String[] args) {
Room[] rooms = new Room[ROOM_AMOUNT];
// Select some random, but static rooms to be occupied
for(int i = 1; i <= ROOM_AMOUNT; i++) {
if(i % 3 - 1 == 0 || i * 2 % i + 10 - 2 == 2) {
rooms[i - 1].obtainTheRoom();
}
}
for(;;) {
System.out.print("Enter a room number:\t");
try {
actualRoom = Integer.parseInt(cmdin.next());
} catch(NumberFormatException nfe) {
loopRoomNumber();
}
if(rooms[actualRoom - 1].obtainTheRoom()) {
System.out.println("Got the room " + actualRoom + "! Now it's occupied -_-");
} else {
System.out.println("Room Occupied!");
}
}
}
private static void loopRoomNumber() {
System.out.print("That's not a valid room number!\n\n");
try {
actualRoom = Integer.parseInteger(cmdin.next());
} catch(NumberFormatException nfe) {
loopRoomNumber();
}
}
}
That should work. Good luck!
I would change your last else if statements as follows. This will work. Because otherwise you will go in an endless loop;
else if (arr[mid] < currval)
{
low = mid;
--high;
}
else if (arr[mid] > currval)
{
high = mid;
++low;
}
Note that i have decremented the high when the mid value is less than the current value, and incremented the low value when the mid value is greater than the current value
Related
I'm a beginner java developer. I want to build a program that gets a number from the user, then say it's prime or not.
Java code:
import java.util.Scanner;
import static java.lang.System.out;
public class prime
{
public static boolean prime(int n)
{
for(int i = 2; i <n ; i++)
{
if(n % i == 0){
return false;
}
}
return true;
}
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
out.println("enter a number: ");
int x = input.nextInt();
if(prime(x)){
out.println(x + "is a prime number");
}else{
out.println(x + "isn't a prime number");
}
}
}
However, I want to declare a bool variable, then ask the user if they want to continue, the user then says yes or no. I have already written this code in C#:
C# code
class Program
{
static bool prime(int n)
{
for(int i = 2; i < n ; i++)
{
if(n % i == 0)
{
return false;
}
}
return true;
}
static void main(String[]args)
{
Bool permit = true;
While(permit)
{
Console.WriteLine(“enter a number”)
int x = int.Parse(Console.ReadLine());
if(prime(x))
{
Console.WriteLine(x + "is a prime number");
}
else
{
Console.WriteLine(x + " isn't a prime number");
}
Console.WriteLine(“do you want to continue”);
Permit = Console.ReadKey.Key() == ConsoleKey.Y?true:false;
}
}
}
How can I build it in Java?
You can't directly map your C# keyboard key press detection to Java.
AFAIK, checking which key is pressed can only be done via key listeners in Java AWT/Swing GUI programs [How to Write a Key Listener]. Your program, however, is a console program and Java doesn't have any mechanisms to detect which key was pressed in a console application. See this question for more info.
Now what you could do is read the String that a certain key press produced. Something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean permit = true;
while (permit) {
// your existing code
out.println("do you want to continue?");
permit = input.next("y|Y").equalsIgnoreCase("y");
}
}
I also corrected prime method.
import java.util.Scanner;
import static java.lang.Math.abs;
import static java.lang.System.out;
public class Prime {
public static boolean prime(int n) {
for (int i = 2; i < n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
try {
out.println("enter a number: ");
int x = Integer.parseInt(input.nextLine());
if (prime(x)) {
out.println(x + " is a prime number");
} else {
out.println(x + " isn't a prime number");
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
}
out.println("do you want to continue");
if (!input.nextLine().equals("Y")) break;
}
}
}
Just check if the key pressed is the y (yes) and if yes it continues in the cycle.
static void main(String[] args)
{
ConsoleKey response;
do
{
Console.WriteLine("enter a number");
int x = int.Parse(Console.ReadLine());
if (prime(x)) {
Console.WriteLine(x + " is a prime number");
} else {
Console.WriteLine(x + " isn't a prime number");
}
Console.Write("do you want to continue? [y/n] ");
response = Console.ReadKey(false).Key;
}
while (response == ConsoleKey.Y);
}
I am currently attempting to finish my first coding Homework assignment, and My teacher and TA are utterly useless. I have been stuck on this problem and many more for days now with no response other than "There is an error" whenever I ask for help. When I try to run my code in Eclipse, it works perfectly and I have no errors that I have noticed. But, when I try to execute it from the cmd prompt I get the following message:
Exception in thread "main" java.lang.IllegalAccessException: Class org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader can not access a member of class ATM with modifiers "public static"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
I have tried googling it, and as far as I have found, the Illegal Access Exception is thrown only for Private and Final methods, which I do not have any of in my code. Any help would be greatly appreciated! Also, please realize that my code may not be good as I have had to teach myself how to code completely.
import java.util.Scanner;
public class ATM {
static Scanner read = new Scanner(System.in); //created a scanner
static String inpCard;
static int listId = -1; //created an int to store the id of the place in which the ATMCard is stored under
static int withdrawlAMT = 0;
public static void main(String[] args) {
cardServices.initializeCardDB(); //enters the array's content
// asks for card number
if(cardServices.insertCard() == true) {
//checks for the pin to be correct
if(pin.processPin() == true) {
int x = account.select();
//if the account selected is checkings, it = 1.
if(x == 1) {
//asks user for how much to withdrawal.
money.moneyAmount();
// insures you dont have to little to withdrawal
// that much, loops forever if you try to withdrawal
// to much.
if(security.verifyBalCheck(withdrawlAMT) == true) {
cardServices.processCard(withdrawlAMT, "checking");
dispense.dispensing();
System.out.println("Your new balance is " +cardServices.cardList[listId].checkBal);
System.out.println("");
cardServices.returnCard();
}
}
//if the account selected is savings, it = 2.
if(x == 2) {
// asks user for how much to withdrawal
money.moneyAmount();
// insures you dont have to little to withdrawal
// that much, loops forever if you try to withdrawal
// to much.
if(security.verifyBalSaving(withdrawlAMT) == true) {
cardServices.processCard(withdrawlAMT, "savings");
dispense.dispensing();
System.out.println("Your new balance is " +cardServices.cardList[listId].savingsBal);
System.out.println("");
cardServices.returnCard();
}
}
}
}
}
}
class ATMBal
{
static int one = 50;
static int five = 40;
static int ten = 25;
static int twenty = 20;
static int total = 1000;
}
class ATMCard //Creating the blueprint for all cards
{
public String cardNum = " "; //Made both cardNum and cardPin to string, to avoid octal numbers
public String cardPin = " ";
public float checkBal = 0;
public float savingsBal = 0;
}
class cardServices
{
static ATMCard[] cardList = new ATMCard[5];
public static void initializeCardDB()
{
cardList[0] = new ATMCard();
cardList[0].cardNum = "123456789"; //added card 1's information
cardList[0].cardPin = "1111";
cardList[0].checkBal = 550;
cardList[0].savingsBal = 1275;
cardList[1] = new ATMCard();
cardList[1].cardNum = "135792468"; //added card 2's information
cardList[1].cardPin = "2097";
cardList[1].checkBal = 90;
cardList[1].savingsBal = -1;
cardList[2] = new ATMCard();
cardList[2].cardNum = "019283746"; //added card 3's information
cardList[2].cardPin = "6194";
cardList[2].checkBal = 7915;
cardList[2].savingsBal = -1;
cardList[3] = new ATMCard();
cardList[3].cardNum = "675849302"; //added card 4's information
cardList[3].cardPin = "0071";
cardList[3].checkBal = 790;
cardList[3].savingsBal = 211;
cardList[4] = new ATMCard();
cardList[4].cardNum = "347821904"; //added card 5's information
cardList[4].cardPin = "9871";
cardList[4].checkBal = 113;
cardList[4].savingsBal = 78;
}
public static boolean insertCard()
{
System.out.print("Please insert your card: "); //ask for card number
ATM.inpCard = ATM.read.nextLine(); //read card number
for(int i = 0; i < 5; i++) //start a loop
{
if(ATM.inpCard.compareTo(cardServices.cardList[i].cardNum) == 0) //checks all card numbers in the database, to see if they matched the input card
{
ATM.listId = i;
return true;
}
if(i == 4)
{
System.out.println("I'm sorry, your card was not found in our system.");
insertCard();
return false;
}
}
return false;
}
public static void processCard(int withdrawalAmount, String account) //actual process withdrawing the amount from the card
{
if(account.compareTo("checking") == 0)
cardServices.cardList[ATM.listId].checkBal = cardServices.cardList[ATM.listId].checkBal - withdrawalAmount;
if(account.compareTo("savings") == 0)
cardServices.cardList[ATM.listId].savingsBal = cardServices.cardList[ATM.listId].savingsBal - withdrawalAmount;
}
public static void returnCard() //returns the inpCard through a tempCard to insure all stored data is removed to increase security
{
System.out.println("Thank you for using Bank of America's new ACME ATMs, have a fantastic day!");
String tempCard = ATM.inpCard;
ATM.inpCard = null;
System.out.println("Here is your card: " +tempCard);
}
}
class pin
{
public static boolean processPin()
{
System.out.print("Please enter your pin number "); //asking for pin then read pin
String inpPinNum = ATM.read.nextLine();
for(int i = 0; i < 4; i++) //created loop
{
if(inpPinNum.compareTo(cardServices.cardList[ATM.listId].cardPin) == 0)
{
return true;
}
else
if(i < 3) //checks attempt amount to insure it is less than the allowed 4
{
System.out.println("Incorrect, please re-enter your pin:");
inpPinNum = ATM.read.nextLine();
}
if(i == 3) //if the pin has been incorrectly 4 times, the user is told that the card will be eaten
{
System.out.println("You have entered your pin incorrectly to many times,"
+ " your card is being destroyed. Please go to any Bank of America to recieve a new card");
eatCard(); //the eatCard() command is called to eat the card
}
}
return false;
}
public static void eatCard() //deletes the card in the system, without returning the card
{
ATM.inpCard = null;
}
}
class security
{
public static boolean verifyBalCheck(int withdrawlAmt) //checks checking balance
{
if(!(withdrawlAmt <=cardServices.cardList[ATM.listId].checkBal))
{
System.out.println("I'm sorry, you're current balance is: " +cardServices.cardList[ATM.listId].checkBal +", and as such you do not have enough to withdrawal that amount.");
money.moneyAmount();
return false;
}
return true;
}
public static boolean verifyBalSaving(int withdrawlAmt) //checks savings balance
{
if(!(withdrawlAmt <=cardServices.cardList[ATM.listId].savingsBal))
{
System.out.println("I'm sorry, you're current balance is: " +cardServices.cardList[ATM.listId].savingsBal +", and as such you do not have enough to withdrawal that amount.");
money.moneyAmount();
return false;
}
return true;
}
public boolean verifyMachineBalance(int withdrawlAmt) //checks ATM Machine Balance
{
if(withdrawlAmt <= ATMBal.total)
{
return true;
}
return false;
}
}
class account
{
public static int select()
{
System.out.print("Would you like to withdrawal from Checkings or Savings? ");
String type = ATM.read.nextLine();
if(type.compareToIgnoreCase("checkings") == 0) //checks to see if the string is checkings, returns 1 if so
{
return 1;
}
if(type.compareToIgnoreCase("savings") == 0) //checks to see if the string is savings, returns 2 if so
{
return 2;
}
return 0;
}
}
class money
{
public static void moneyAmount()
{
System.out.print("How much would you like to withdrawl? ");
ATM.withdrawlAMT = Integer.parseInt(ATM.read.nextLine());
}
}
class dispense
{
public static void dispensing()
{
ATMBal.total = ATMBal.total - ATM.withdrawlAMT; //removes the withdrawalAmt from total
System.out.println("");
System.out.println("Your total withdrawal amount is: " +ATM.withdrawlAMT);
while(ATM.withdrawlAMT >= 20 && ATMBal.twenty > 0) //checks to figure out the biggest bills the machine is able to dispense
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 20;
ATMBal.twenty = ATMBal.twenty - 1;
}
while(ATM.withdrawlAMT >= 10 && ATMBal.ten > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 10;
ATMBal.ten = ATMBal.ten - 1;
}
while(ATM.withdrawlAMT >= 5 && ATMBal.five > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 5;
ATMBal.five = ATMBal.five - 1;
}
while(ATM.withdrawlAMT >= 1 && ATMBal.one > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 1;
ATMBal.one = ATMBal.one - 1;
}
int twenties = 20 - ATMBal.twenty; //Stoes how many of each will be dispensed
int tens = 25 - ATMBal.ten;
int fives = 40 - ATMBal.five;
int ones = 50 - ATMBal.one;
System.out.println("This is comprised of: " +twenties +" twenties, " //prints how much of each bill is being dispensed
+tens +" tens, "
+fives +" fives, and "
+ones +" ones");
}
}
I've been tasked to make a secret word guessing game and it is supposed to be game over and user is asked if they want to play again if the number of guesses for the character reaches 5.
I thought my incrementor is correct but perhaps not...
Here's the class:
public class SecretWord {
private String secretWord;
private String hintWord ;
private int numberOfTurns;
//Default Constructors
public SecretWord()
{
hintWord = "";
secretWord = "juice";
for (int i = 0; i < secretWord.length(); i++)
{
hintWord+="*";
}
this.numberOfTurns = 0;
}
//Accessors
public String getSecretWord()
{
return this.secretWord;
}
public String getHintWord()
{
return this.hintWord;
}
public int getNumberOfTurns()
{
return this.numberOfTurns;
}
//Mutators
public void setSecretWord ()
{
this.secretWord = "juice";
}
public void setHintWord ()
{
//Setting the hint word which sets the asterisks when you guess something right
char[] correctLetters = new char[secretWord.length()];
for (int i = 0; i<secretWord.length();i++)
{
hintWord+="*";
correctLetters[i] += '*';
}
}
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
//Methods
public void guessLetter(char guess)
{
String tempHintWord="";
for (int i = 0; i < secretWord.length(); i++)
{
if (secretWord.charAt(i) == guess)
{
tempHintWord += guess;
}
else
{
tempHintWord += hintWord.charAt(i);
}
}
hintWord = tempHintWord;
}
Here's the driver with my loops:
public class SecretWordGame {
//Constant for number of tries
public static final int NUM_TRIES = 5;
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Starts game
boolean quit = false;
while (quit == false)
{
System.out.println("Welcome to the word guessing game! You have " +
+NUM_TRIES+" tries to guess the secret word!");
SecretWord myWord = new SecretWord();
System.out.println("The current hint is \n"+myWord.getHintWord());
while (myWord.getNumberOfTurns() <=NUM_TRIES)
{
System.out.println("Guess a lowercase letter");
//Gets the first letter of what is entered
char tempGuess = keyboard.nextLine().charAt(0);
//Updates the hint by calling guess letter method
myWord.guessLetter(tempGuess);
System.out.println(myWord.getHintWord());
System.out.println("Guess the secret word");
String myGuess = keyboard.nextLine();
//Checks correct guess
if (myGuess.equals(myWord.getSecretWord()))
{
System.out.println("You win!");
break;
}
else
{
System.out.println("Keep trying!");
}
myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);
}
//Prompts user to play again
System.out.println("Game over! Try again?");
String userInput = keyboard.nextLine();
if(userInput.equalsIgnoreCase("no"))
{
quit = true;
}
else
{
System.out.println("Let's go again!");
}
}
System.out.println("Goodbye!");
}
Maybe the while loop (myWord.getNumberOfTurns() <=NUM_TRIES) comparison is wrong? Or perhaps the getNumberOfTurns incrementor is in the wrong place? I'm unsure.
change
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
to
public void setNumberOfTurns (int i)
{
this.numberOfTurns = i;
}
otherwise it would be set to 5 when this code is called myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);
So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));
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.