Simple Seat Reservation in Java - java

package Demo;
import java.util.Scanner;
public class seat_reservation{
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
// Initialization
final int ROWS = 2;
final int COLS = 3;
char [][] seats = new char [ROWS][COLS];
int i, j, seatNum, counter = 0;
char seatLetter = 'A';
int choice = 0;
String seatEnter;
boolean cont = true; // loops of running the program
while( choice != 4 ){
System.out.print( "1. Assign Seats" );
System.out.print( "2. Exit" );
System.out.print( "Select your choice: " );
choice = read.nextInt();
switch( choice ){
case 1:
//Set the value.
for (i=0; i < seats.length; i++) {
for (j=0; j < seats[i].length; j++)
seats[i][j] = seatLetter++;
seatLetter = 'A'; // to reset the value to A for the new loop
}
//To display the list of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j]+" ");
System.out.println();
}
//condition
while (counter < 6 && cont) {
do {
System.out.print("Please type the chosen seat(starts with row and column,e.g:2A):" + "");
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0)+"");
if (seatNum != 0)
seatLetter = seatEnter.charAt(1);
i++;
//if user enters wrong input, error message will appear.
if (seatLetter!='A'){
if (seatLetter!='B'){
if(seatLetter!='C'){
if(seatLetter!='D')
System.out.println ("Invalid! Please enter the correct seat:");
}
}
}
}
//continue to loop until the condition true
while (seatNum < 0 || seatNum > 7 || seatLetter < 'A' || seatLetter > 'D');
if (seatNum == 0) {
cont = false;
} else {
if (seats[seatNum-1][seatLetter-65] == 'X')
System.out.println("Seat have been taken.Please choose another seat:");
else {
seats[seatNum -1][seatLetter-65] = 'X';
counter++;
}
// To display updated lists of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j] + " ");
System.out.println();
}
System.out.println(" ") ;
//}
//}
// displays fully booked message
if (counter == 6)
System.out.println("All seats are now fully-booked.");
break;
}
}
case 2://syntax error here
if (counter == 6)
System.out.println( "All seats are now fully-booked." );
System.out.println( "End of Program" );
System.exit(0);
break;
default:
System.out.println("Error input");
break;//syntax error here as well.
}
}
}
}

The problem is caused due to:
choice = read.nextInt();
The scanner.nextInt() only takes the next token from the input. Rest are ignored by it.
So when you're trying to take the next input from this line and process it, the error occurs:
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0) + "");
As the previous read.nextInt() left the rest except first token, when you hit enter after giving 1 as input, it took only the 1 and the enter or newline token was captured by the read.nextLine(). That is why it got no charAt(0) and thus thrown StringIndexOutOfBoundException.
Try:
choice = Integer.parseInt(read.nextLine());
or,
choice = read.nextInt();
read.nextLine(); // this will capture the residue

Related

Hangman game: How to find the word?

I have to create a hangman game. I am stuck in the last step. In fact, when the user finds the word my input asks yet a letter.
Here an example: (the word to find is "non")
Enter your letter please : n
n _ n
Enter your letter please : o
n o n
Enter your letter please :
n o n
My problem is probably my wordFind, I don't understand how to manipulate this ?
String[] words = {"yess", "non"};
String wordRandom = words[(int) (Math.random() * words.length)];
boolean[] letterGuess = new boolean [wordRandom.length()];
boolean wordFind = false;
int numberAttempt = 5;
while(numberAttempt > 0 && !wordFind){
System.out.println("Number of attempt(s) " + numberAttempt);
for(int i=0; i < wordRandom.length(); i++){
if(letterGuess[i]){
System.out.print(wordRandom.charAt(i));
}
else{
System.out.print("- ");
}
}
System.out.println(" ");
System.out.print("Enter your letter please : ");
char letter = input.next().charAt(0);
int letterFound = 0;
boolean alreadyFound = false;
for(int i=0; i < wordRandom.length(); i++){
if(wordRandom.charAt(i) == letter){
if(letterGuess[i]){
alreadyFound = true;
}
letterGuess[i] = true;
letterFound++;
}
}
if(alreadyFound){
System.out.println("Letter already proposed and it has been found ! ");
} else{
if(letterFound == 1){
System.out.println("The letter is correct ! ");
}
else if(letterFound > 0){
System.out.println("The letter is " + letterFound + " times in the word ! ");
}
else{
numberAttempt--;
System.out.println("The letter is not in the word ! ");
}
}
}
You need to add a solved condition like this
boolean wordFind = false;
int numberAttempt = 5;
boolean solved = false;
while(numberAttempt > 0 && !wordFind && !solved){
after you update letterFound, set solved
letterFound++;
if (letterfound == wordRandom.length()) {
solved = true
}
Then at the end after the while loop, if solved is true, congratulate the user.
You can create a variable int amountCorrect = 0; and use that as a check. Every time the user gets a right letter, add to amountCorrect the number of letters there are. At the beginning of the while loop, create a boolean check that checks if the amountCorrect variable is the same as the length of the wordRandom. I know your code is kind of long, so I put a comment next to the lines where I added code:
String[] words = { "yess", "non" };
String wordRandom = words[(int) (Math.random() * words.length)];
boolean[] letterGuess = new boolean[wordRandom.length()];
boolean wordFind = false;
int numberAttempt = 5;
int amountCorrect = 0; // The amountCorrect variable
while (numberAttempt > 0 && !wordFind) {
System.out.println("Number of attempt(s) " + numberAttempt);
// This is the boolean check
if (amountCorrect == wordRandom.length()) {
System.out.println("You Win!");
break;
}
for (int i = 0; i < wordRandom.length(); i++) {
if (letterGuess[i]) {
System.out.print(wordRandom.charAt(i));
} else {
System.out.print("- ");
}
}
System.out.println(" ");
System.out.print("Enter your letter please : ");
char letter = input.next().charAt(0);
int letterFound = 0;
boolean alreadyFound = false;
for (int i = 0; i < wordRandom.length(); i++) {
if (wordRandom.charAt(i) == letter) {
if (letterGuess[i]) {
alreadyFound = true;
}
letterGuess[i] = true;
letterFound++;
// add to amountCorrect
amountCorrect++;
}
}
if (alreadyFound) {
System.out.println("Letter already proposed and it has been found ! ");
} else {
if (letterFound == 1) {
System.out.println("The letter is correct ! ");
}
else if (letterFound > 0) {
System.out.println("The letter is " + letterFound + " times in the word ! ");
}
else {
numberAttempt--;
System.out.println("The letter is not in the word ! ");
}
}
}

Stuck in logic for movie guess game in java (by udacity)

I am making a movie guessing game(much like hangman but doesn't contain the stick figure and stuff) on Java that takes input from the user, letter by letter. I am stuck where I want the letter entered to replace all instances of that letter in the title of the movie. My code is not working completely.
Later, I am gonna apply the logic that stops the user from entering the same letter again. But at the moment I need to fix this particular issue. Any help?
This is the game process function in my game class.
public void GameProcess(char[] dashedarray) {
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
while (run) {
if (dashedarray[i] == ' ') {
spaces++;
i++;
continue;
} else {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if (moviename.charAt(i) == guess) {
dashedarray[i] = guess;
correct++;
}
else if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
}
}
else
{
wrong++;
}
}
i++;
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}
}
You don't need i at all. spaces is to count the number of spaces in your answer, which does not need to be guessed. You should do that outside of the loop.
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
for (int i = 0; i < dashedarray.length; i++) {
spaces++;
}
while (run) {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
boolean match = false;
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
match = true;
}
}
}
// It matched nothing, this input is wrong.
if (!match) {
wrong++;
}
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}

Java battleship program not printing board correctly

I am having a problem with my java battleship program not printing the coordinates that the user enters. When the user guesses a spot on the board its supposed to update the space with an "X" if its a hit, if not then the board remains the same. But when a user guesses wrong on my program, it prints everything except the space where the user guessed. I believe that my else statement where the board updates is the problem, but any modification I did resulted in the board not printing anything.
import java.util.Random;
import java.util.Scanner;
class Battleship {
public static char randChar(){
final String alphabet = "ABCDE";
final int N = alphabet.length();
char rand;
Random r = new Random();
rand = alphabet.charAt(r.nextInt(N));
return rand;
}
public static void main (String[] args) throws java.lang.Exception {
char[] letters = {' ', 'A', 'B', 'C', 'D', 'E'};
int[] numbers ={1, 2, 3, 4, 5};
int[][] ships = new int[7][2];
char colGuess;
int rowGuess;
Boolean boardFlag=false;
Scanner scan = new Scanner(System.in);
//creates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
System.out.print(letters[j] + "" + numbers[i-1]);
}
System.out.print(" ");
}
System.out.println();
}
//assigns ships to random spots
assignShips(ships);
System.out.println("Enter your guess for the column:");
colGuess = scan.next().charAt(0);
//converts to uppercase
colGuess = Character.toUpperCase(colGuess);
System.out.println("Enter your guess for the row:");
rowGuess = scan.nextInt();
//shows player what they entered
System.out.println("you entered: " + (char) colGuess + rowGuess);
//calls method to check for a hit
fire(colGuess, rowGuess, ships);
boardFlag = fire(colGuess, rowGuess, ships);
System.out.println(boardFlag);
//updates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
if(letters[j] == colGuess && numbers[i - 1] == rowGuess) {
if(boardFlag==true) {
System.out.print(" " + "X");
}
}
else {
System.out.print(letters[j] + "" + numbers[i - 1]);
}
}
System.out.print(" ");
}
System.out.println();
}
}
public static void assignShips(int[][] ships) {
Random random = new Random();
for(int ship = 0; ship < 7; ship++) {
ships[ship][0] = randChar();
ships[ship][1] = random.nextInt(5);
//gives location of ships, for testing purposes
System.out.print("Ship:" + (ship+1)+ " is located at"+(char)ships[ship][0]+ships[ship][1]+"\n");
}
}
//checks user input to see if we have a hit
public static Boolean fire(char colGuess, int rowGuess, int[][] ships) {
Boolean hitFlag=false;
for(int ship = 0; ship < ships.length; ship++){
if(colGuess ==ships[ship][0] && rowGuess == ships[ship][1]){
hitFlag=true;
}
}
if(hitFlag == true) {
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
}
else {
System.out.println("sorry chief we missed em");
}
return hitFlag;
}
}
The reason its not showing up when you miss is because your net telling it to print anything.
if(letters[j] == colGuess && numbers[i-1] == rowGuess){
if(boardFlag==true) {
System.out.print(" "+"X");
}
}
Your only handling the coordinate the user input if they hit. To fix this you would need an else statement after your if(boardFlag == true)to handle printing if you miss.
The problem is in your update board portion of the code because you don't do anything if the guessed location isn't a hit.
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag) {
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
Full Update Portion:
//updates the board
for (int i = 0 ; i <= 5 ; i++){
for (int j = 0 ; j <= 5 ; j++){
if (i == 0) {
System.out.print(letters[j]+" ");
} else if (j == 0){
System.out.print(numbers[i-1] );
} else {
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag){
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
}
System.out.print(" ");
}
System.out.println();
}
This block (old version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em");
}
Should be (new version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em at " + (char)colGuess+rowGuess);
}
this will print:
sorry chief we missed em at D3 //D3 is a random possible set of coordinates
Rather than:
sorry chief we missed em //Old version
So all you have to add is (char)colGuess+rowGuess, which prints the coordinates of your previous guess.
Comment if you have any questions!

How to store user input for continued use?

How can I repeat this program but keep the user input when it is displayed to them a second time or the third time etc. The program asks them where they want to sit, then the display shows them an X in place of where they said. I want the X to stay for the next time it asks for their input until the user decides to quit the program by choosing "2".
import java.util.Scanner;
import java.util.Arrays;
class AirplaneSeating {
static Scanner inNum = new Scanner(System.in);
static Scanner inStr = new Scanner(System.in);
static void option() {
String[][] seatingChart = new String[10][4];
int rows = 10;
int columns = 4;
seatingChart = new String[rows][columns];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
seatingChart[i][j] = "" + ((char)('A' + i)) + ((char)('1' + j));
}
}
for(int i = 0; i < rows ; i++) {
for(int j = 0; j < columns ; j++) {
System.out.print(seatingChart[i][j] + " ");
}
System.out.println("");
}
System.out.println("What seat would you like to reserve? ");
String str = inStr.nextLine();
System.out.println("You chose: " + str);
for(int i = 0; i < rows ; i++) {
for(int j = 0; j < columns ; j++) {
if(seatingChart[i][j].equals(str)) {
System.out.print("X" + " ");
} else {
System.out.print(seatingChart[i][j] + " ");
}
}
System.out.println("");
}
}
public static void main(String[] args) {
int choice;
do {
System.out.println("Choose from one of the following options:");
System.out.println("\tl. Choose a seat to reserve: ");
System.out.println("\t2. Quit");
System.out.print("Enter 1 or 2: ");
choice = inNum.nextInt();
switch(choice) {
case 1:
option();
break;
case 2:
System.out.println("\nGoodbye!");
break;
default:
System.out.println(choice + " is not an option. Please choose 1, 2, 3, 4, or 5.");
}
}while(choice !=2);
}
}
Use BufferedReaders,BufferedWriters and a .txt file. They're pretty simple to use and allow you to save something in a text document which can later be accessed to reload previous information.

Checking for user input to be only integers in Java

I'm doing lottery game for my assignment (user inputs 6 number, i will generate 8 unique winning numbers and 2 last numbers are supplementary). I need help with user input checking if input numbers are from 1 to 45 and input must be int, when input is not integer it throws an error.
This programming way is procedure way, how can i change it into object oriented way? I know that I must make methods in another java file and then link it back to this main. Can you suggest me how to do it?
I have tried try and catch, if and else (for input check) but i don't know how to check user input when it's in array. Thank you for help.
Here is my code:
class Lottery {
public static void main ( String[] args ) {
System.out.println("\nWelcome to the Lottery game.");
System.out.println("You can enter numbers from 1 to 45.");
// User input into an array
int[] input = new int[6];
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease enter your 6 lucky numbers: ");
for(int j = 0; j < 6; j++) {
input[j]=scanner.nextInt();
}
int check = scanner.nextInt();
if(check < 0 && check > 45) {
System.out.println("\nERROR: Please enter only numbers from 1 to 45!");
}
// Printing out unique winning numbers from random generator
System.out.println("\nWinning numbers: ");
MultiRandomGenerator mrg = new MultiRandomGenerator();
int[] set;
set = mrg.getSet();
for (int i = 0; i < set.length; i++) {
System.out.print(set[i] + " ");
}
// Loops for counting how many numbers user has guessed right
int count = 0; // for 6 numbers
int scount = 0; // for 2 last supplementary numbers
for(int i = 0; i < input.length; i++) {
for(int k = 0; k < set.length; k++) {
if (k < 6) {
if (set[k] == input[i]) {
count++;
} else {
if (set[k] == input[i]) {
scount++;
}
}
}
}
}
System.out.print("\n\nYou guessed right " + count + " winning numbers.");
System.out.print("\nYou guessed right " + scount + " suplementary numbers.");
// If statments for printing out winning prizes
if (count == 6) {
System.out.println("\nYou have won 1st price!");
} if (count == 5 && scount == 1) {
System.out.println("\nYou have won 2st price!");
} if (count == 5) {
System.out.println("\nYou have won 3st price!");
} if (count == 4) {
System.out.println("\nYou have won 4st price!");
} if (count == 3 && scount == 1) {
System.out.println("\nYou have won 5st price!");
} if (count == 1 && scount == 2) {
System.out.println("\nYou have won 6st price!");
} else {
System.out.println("\nSorry, you didn't won anything.");
}
}
}
Sample code to go through array and find the invalid user input.
set = mrg.getSet();
String[] userDataStatus = new String[45];
for (int i = 0; i < set.length; i++)
{
try
{
String inputdata = set.get(i);
if(inputdata != null && inputdata.trim().length() > 0)
{
int currentNumber = Integer.parseInt(userdata);
userDataStatus[i] = "Y";//Y represent valid number
}
}
catch (NumberFormatException ex )
{
userDataStatus[i] = "N";//If it throws exception then save as 'N'
}
}
Use the above String array and display error messaage to users.
You can check in your loop, something like
int val;
try
{
input[j] = Integer.parseInt( scanner.nextString() );
}
catch (NumberFormatException ex )
{
}

Categories