newbie to nested if statements - java

I am learning to use Java and code on my own, I am network Tech and wanted to learn how to Code. I am learning from a site called programming by doing and I am stuck on one assignment:
https://programmingbydoing.com/a/twenty-questions.html
below is my code, it will compile but the issue is with the nested if statement not working properly please help!!!
import java.util.Scanner;
public class twentyQuestions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String question1, question2, guess;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I will try to guess it.");
System.out.println();
System.out.println("Question 1: Is it an animal, vegetable, or mineral?");
question1 = keyboard.next();
System.out.println();
System.out.println("Question 2: Is it bigger than a bread box?");
question2 = keyboard.next();
if (question1.equals("animal"))
{
if (question2.equals("no"))
{
guess = "squirrel";
}
else {
guess = "moose";
}
}
else if (question1.equals("vegetable"))
{
if (question2.equals("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (question1.equals("mineral"));
{
if (question2.equals("no"))
{
guess = "paper clip";
}
else
{
guess = "Camaro";
}
}
System.out.println("You're thinking of a " + guess);
}
}
}

First off all, you need to remove the semicolon after
else if (question1.equals("mineral"))
Then, you need to add a final else block at the end of the if statement to catch input that does not match any of the three inputs. Then it will be able to compile:
...
else if (question1.equals("mineral"))
{
if (question2.equals("no")) {
guess = "paper clip";
} else {
guess = "Camaro";
}
}else{
System.out.println("Invalid input");
return;
}
...

THANK YOU ALL here is my final code that works thanks to everyone...:
import java.util.Scanner;
public class twentyQuestions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String question1, question2, guess = "";
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I will try to guess it.");
System.out.println();
System.out.println("Question 1: Is it an animal, vegetable, or mineral?");
question1 = keyboard.next();
System.out.println();
System.out.println("Question 2: Is it bigger than a bread box?");
question2 = keyboard.next();
if (question1.equals("animal"))
{
if (question2.equals("no"))
{
guess = "squirrel";
}
else {
guess = "moose";
}
}
else if (question1.equals("vegetable"))
{
if (question2.equals("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (question1.equals("mineral"))
{
if (question2.equals("no"))
{
guess = "paper clip";
}
else
{
guess = "Camaro";
}
}
else{
System.out.println("Invalid input");
return;
}
System.out.println("You're thinking of a " + guess);
}
}

Related

AIrline Reservation

I am trying to do a basic Java Airline Reservation App. Here is my code, It seems that after I press '1' it is terminating and not running the rest of the code. I am not sure if it is something wrong with my loop or why it is terminating. Please if anyone has any ideas or answers I would love to hear them! thanks
import java.util.Scanner;
public class Reservation {
boolean[] seat = new boolean[11];
Scanner input = new Scanner(System.in);
public void start() {
while (true) {
makeReservation();
}
}
public void makeReservation() {
System.out.println("Please type 1 for first class and type 2 for economy");
int section = input.nextInt();
if (section == 1) {
firstClassSeat();
} else {
economySeat();
}
}
public void firstClassSeat() {
for (int count = 1; count <= 5; count++) {
if (seat[count] = false) {
seat[count] = true;
System.out.printf("First Class. Seat# %d\n", count);
break;
} else if (seat[10] == true) {
if (seat[5] == true) {
} else {
System.out.println("First class is fully booked, would you like an econmy seat");
int choice = input.nextInt();
if (choice == 1) {
firstClassSeat();
start();
} else {
System.out.println("Next flight is in 3 hours");
System.exit(0);
}
}
}
}
}
public void economySeat() {
for (int count = 6; count <= 10; count++) {
if (seat[count] = false) {
seat[count] = true;
System.out.printf("First Class. Seat# %d\n", count);
break;
} else if (seat[10] == true) {
if (seat[5] == true) {
} else {
System.out.println("Economy is fully booked. Would you like First Class? 1 for Yes 2 for No");
int choice = input.nextInt();
if (choice == 1) {
firstClassSeat();
start();
} else {
System.out.println("Next flight is in 3 hours");
System.exit(0);
}
}
}
}
}
}
First off, there is no need to compare booleans inside an if. seats[i] == false is the same as !seats[i].
Nothing is happening because you have an assignment:if(seat[count]=false instead of comparison:if(seat[count]==false. That's the first error, after fixing that you will start assigning seats.
Next, you're calling firstClassSeat inside the same method, when I think you wanted to call economySeat (when first class is full). You need to fix the logic behind the checks and economy/first class suggestions.

How do I exit a nested while loop in java?

EDIT: Since my program still doesn't work, I posted the entire method just in case there is another problem.
I want to exit this program if the user inputs 'n' when prompted:
char again = 'y';
while (again == 'y' || again == 'Y')
{
String ans = IBIO.inputString ("Unscramble: OBORSLW (Hint: Shellder latches onto its tail.) ");
int tries = 0;
while (!ans.toLowerCase ().equals ("slowbro"))
{
System.out.println ("Incorrect. Wrong answer. Try again.");
tries++;
ans = IBIO.inputString ("\nUnscramble: OBORSLW (Hint: Shellder latches onto its tail.) ");
if (tries > 3)
{
System.out.println ("The correct answer was SLOWBRO.");
again = IBIO.inputChar ("Play again? (y/n) ");
break;
}
}
System.out.println ("Correct.");
System.out.println ("\nQuestion #2 - ");
String ans2 = IBIO.inputString ("\nUnscramble: RVLEGERA (Hint: It rolls down slopes without slowing down.) ");
int tries2 = 0;
while (!ans2.toLowerCase ().equals ("graveler"))
{
System.out.println ("Incorrect. Wrong answer. Try again.");
tries2++;
ans2 = IBIO.inputString ("\nUnscramble: RVLEGERA (Hint: It rolls down slopes without slowing down.) ");
if (tries2 > 3)
{
System.out.println ("The correct answer was GRAVELER.");
again = IBIO.inputChar ("Play again? (y/n) ");
if (again != 'y' || again != 'Y')
break;
}
}
System.out.println ("Correct.");
System.out.println ("\nQuestion #3 -");
String ans3 = IBIO.inputString ("\nUnscramble: TYSGLA (Hint: It's almost invisible and is gaseous.) ");
int tries3 = 0;
while (!ans3.toLowerCase ().equals ("gastly"))
{
System.out.println ("Incorrect. Wrong answer. Try again.");
tries3++;
ans3 = IBIO.inputString ("\nUnscramble: TYSGLA (Hint: It's almost invisible and is gaseous.) ");
if (tries3 > 3)
{
System.out.println ("The correct answer was GASTLY.");
again = IBIO.inputChar ("Play again? (y/n) ");
if (again != 'y' || again != 'Y')
break;
}
}
printSlow ("Correct.");
printSlow ("\nWell Done, " +name+ "! You have passed the test! I'm so happy for you!!");
break;
}
}
Whenever I purposely input a false value multiple times, I get told the right answer, and can try again if I want to. This part works. However, if I don't want to continue, the program just continues by itself and proceeds to the next question. How can I stop the entire program?
char again = 'y';
while (again == 'y' || again == 'Y')
{
String ans = IBIO.inputString ("Unscramble: OBORSLW (Hint: Shelder latches onto its tail.) ");
int tries = 0;
boolean flag= false;
while (!ans.toLowerCase ().equals ("slowbro"))
{
System.out.println ("Incorrect. Wrong answer. Try again.");
tries++;
ans = IBIO.inputString ("\nUnscramble: OBORSLW (Hint: Shelder latches onto its tail.) ");
if (tries > 3)
{
System.out.println ("The correct answer was SLOWBRO.");
again = IBIO.inputChar ("Play again? (y/n) ");
flag = true;
break;
}
}
if(flag==true){
break;
}
your mean this ?
EDIT: I have modify codes to suit your requirements. Please check it out.
Original: I think first of all you have to write out what is your IBIO class here so that people are able to help you debug.
I have found out IBIO class online and tested your program, but it has performed correctly.
Below is my code.
Main.java:
public class Main {
private static boolean verifyAnswer(String candidate, String answer) {
if (candidate.toLowerCase().equals(answer))
return true;
else {
System.out.println("Incorrect. Wrong answer. Try again.");
return false;
}
}
private static boolean playGame(int questionNumber, String answer, String question) {
String candidate;
System.out.println("Question #" + questionNumber + " - ");
int tries = 0;
do {
tries++;
if (tries > 3) {
System.out.println("The correct answer was " + answer + ".");
char again = IBIO.inputChar("Play again? (y/n) ");
if (again != 'y' && again != 'Y')
System.exit(0);
else
return false;
}
candidate = IBIO.inputString(question);
} while (!verifyAnswer(candidate, answer));
System.out.println("Correct.");
return true;
}
public static void main(String[] args) {
while (!playGame(1, "slowbro", "Unscramble: OBORSLW (Hint: Shellder latches onto its tail.) ")) ;
while (!playGame(2, "graveler", "Unscramble: RVLEGERA (Hint: It rolls down slopes without slowing down.) ")) ;
while (!playGame(3, "gastly", "Unscramble: TYSGLA (Hint: It's almost invisible and is gaseous.) ")) ;
}
}
IBIO.java:
//---- IBIO - Below are simplified input and output methods ----
//===========================================================
// IBIO Standard Input and Output
// These methods must be copied into your program(s).
//===========================================================
public class IBIO {
static void output(String info) {
System.out.println(info);
}
static void output(char info) {
System.out.println(info);
}
static void output(byte info) {
System.out.println(info);
}
static void output(int info) {
System.out.println(info);
}
static void output(long info) {
System.out.println(info);
}
static void output(double info) {
System.out.println(info);
}
static void output(boolean info) {
System.out.println(info);
}
static String input(String prompt) {
String inputLine = "";
System.out.print(prompt);
try {
inputLine = (new java.io.BufferedReader(
new java.io.InputStreamReader(System.in))).readLine();
} catch (Exception e) {
String err = e.toString();
System.out.println(err);
inputLine = "";
}
return inputLine;
}
static String inputString(String prompt) {
return input(prompt);
}
static String input() {
return input("");
}
static int inputInt() {
return inputInt("");
}
static double inputDouble() {
return inputDouble("");
}
static char inputChar(String prompt) {
char result = (char) 0;
try {
result = input(prompt).charAt(0);
} catch (Exception e) {
result = (char) 0;
}
return result;
}
static byte inputByte(String prompt) {
byte result = 0;
try {
result = Byte.valueOf(input(prompt).trim()).byteValue();
} catch (Exception e) {
result = 0;
}
return result;
}
static int inputInt(String prompt) {
int result = 0;
try {
result = Integer.valueOf(
input(prompt).trim()).intValue();
} catch (Exception e) {
result = 0;
}
return result;
}
static long inputLong(String prompt) {
long result = 0;
try {
result = Long.valueOf(input(prompt).trim()).longValue();
} catch (Exception e) {
result = 0;
}
return result;
}
static double inputDouble(String prompt) {
double result = 0;
try {
result = Double.valueOf(
input(prompt).trim()).doubleValue();
} catch (Exception e) {
result = 0;
}
return result;
}
static boolean inputBoolean(String prompt) {
boolean result = false;
try {
result = Boolean.valueOf(
input(prompt).trim()).booleanValue();
} catch (Exception e) {
result = false;
}
return result;
}
//=========== end IBIO ===========================================//
}
My environment: Intellij Community 2016.1.1 + jdk 8 + Windows 7 x64

Java Scanner ignores answer

Hi it's my first post here and I have a problem:
I have a program in which, at some point, asks the user if he wants to share the stars, and if he supposedly does, the program goes back to collecting them and after some time comes back to the question if he wants to share them again.
The problem is that, when the user comes back to that point, the program ignores whatever answer u give to it and goes to the "else answer block".
It looks like this:
"Do you want to share your stars?
yes
Please answer with yes or no"
Code:
import java.util.Random;
import java.util.Scanner;
public class App {
static Scanner skan = new Scanner(System.in);
static int starCount = 0;
static Random random = new Random();
public static void main(String[] args) {
starReaching();
}
static void starReaching() {
boolean starCollected = false;
int i = 0;
int j = random.nextInt(101);
while (i < j) {
i++;
System.out.println("Stars are out of reach");
}
if (i > j || i == j) {
starCollected = true;
}
if (starCollected == true) {
starCollector();
}
}
static void starCollector() {
System.out.println("You caught a star !");
starCount++;
if (starCount == 10) {
System.out.println("You have 10 stars ! :)");
System.out.println("Do you want to share your stars?");
String line = skan.nextLine();
if (line.equals("yes")) {
skan.reset();
starGiver();
} else if (line.equals("no")) {
wishMaker();
} else {
System.out.println("Please answer with yes or no");
System.exit(0);
}
} else {
starReaching();
}
}
static void starGiver() {
System.out.println("How many do you want to share?");
int starsToShare = skan.nextInt();
if (starsToShare < 10 || starsToShare == 10 && starsToShare > 0) {
starCount = starCount - starsToShare;
System.out.println("Stars shared !");
System.out.println("You now have " + starCount + " stars");
System.out.println("Go collect them again!");
starReaching();
} else if (starsToShare > 10) {
System.out.println("You don't have enough stars to share that much!");
starGiver();
} else {
System.out.println("That's not a valid option");
starGiver();
}
}
static void wishMaker() {
}
}
Every time you call skan.nextLine() you read a new line and advance the scanner's pointer, and this is the reason your code is failing: you're calling this too often.
Instead of
if (skan.nextLine().equals("yes")) {
skan.reset();
starGiver();
} else if (skan.nextLine().equals("no")) {
wishMaker();
} else {
do:
String line = scan.nextLine(); // read from Scanner **once** only
if (line.equals("yes")) {
skan.reset();
starGiver();
} else if (line.equals("no")) {
wishMaker();
} else {
Okay i've found the little bugger, i was using skan.nextInt without using skan.nextLine after that, thank you for the quick help, much love

How should I loop this program?

Basically I need to loop this. I created a game where you answer questions about fish in runescape and I would like it to loop like say would ‘you go again’ or something. How would I go about this?
import java.util.Scanner;
public class GameDriver
{
public static void main(String a[])
{
Game g = new Game();
Scanner s = new Scanner(System.in);
String buf = null;
for(int i = 0; i < 4; i++)
{
System.out.print(g.askQuestion());
buf = s.nextLine();
if(g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
}
}
You could do while (true) loop and then if the user enters quit just break the loop like so:
if (buf.equals("quit"))
break;
PFB complete code for ‘you go again’ program:
import java.util.Scanner;
public class GameDriver {
public static void Gamer(Scanner s) {
Game g = new Game();
String buf = null;
for (int i = 0; i < 4; i++) {
System.out.print(g.askQuestion());
buf = s.nextLine();
if (g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
}
public static void main(String a[]) {
Scanner s = new Scanner(System.in);
try {
while (true) {
System.out.print("Press Enter to continue; Type Exit to quit");
if (s.nextLine().equalsIgnoreCase("exit")) {
s.close();
break;
}
Gamer(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
As per i understand your question,you want to loop over the for loop.Kindly correct me if i m wrong.
char c='y';//'y' means user wants to go again
while(c=='y')// to check the user reply.
{
for(int i = 0; i < 4; i++)
{
System.out.print(g.askQuestion());
buf = s.nextLine();
if(g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
System.out.println("Do you wanna go again?");
c=s.next.charAt(0);
}
This is shortest solution keeping all your code logic as is :
import java.util.Scanner;
public class GameDriver {
public static void Gamer(Scanner s) {
Game g = new Game();
String buf = null;
for (int i = 0; i < 4; i++) {
System.out.print(g.askQuestion());
buf = s.nextLine();
if (g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
System.out.print("Press Enter to continue; Type Exit to quit");
if (s.nextLine().equalsIgnoreCase("exit")) {
s.close();
System.exit(0);
}
Gamer(s);
}
public static void main(String a[]) {
Gamer(new Scanner(System.in));
}
}

Hangman, exits the game without getting the user response (loop)

I got a couple issues with my code. I know it is not the best looking design/coding but I don't claim to be a good programmer yet. I have to other classes does their work correctly. Dictionary class which contains a word list and HangmanAnimation class which draws the hangman onto console.
Now, I want my game to ask to player if he/she wants to play again after the game finished. Actually, it does asking if player wants to play again but exits the game before the player can type anything.
I would appreciate any other suggestions aswell. Thanks in advance! You guys really rock! :)
public class HangmanGame {
public static void main(String[] args) {
HangmanUI ui = new HangmanUI();
ui.initialize();
String input = "";
if(ui.newGame(input).equalsIgnoreCase("yes"))
main(null);
}
}
public class HangmanUI {
private final Dictionary d = new Dictionary();
private final HangmanAnimation ha = new HangmanAnimation();
private String wordInProgress = d.getWordInProgress();
Scanner sc = new Scanner(System.in);
private int maxTries = 5;
String word;
public void initialize() {
int easyWords = 1;
int hardWords = 2;
System.out.println("Welcome to Hangman game.");
System.out.println("=========================");
System.out.println("Rules: You need to find the given word in 5 tries.");
System.out.println("You will continue guessing letters until you can either");
System.out.println("solve the word or all five body parts are on the gallows.");
System.out.println("In that case you will lose the game. Try not to enter");
System.out.println("same letter more than once. Those are counts too.");
System.out.println();
System.out.println("Choose your game level or Quit:");
System.out.println("1) Easy");
System.out.println("2) Hard");
System.out.println("3) Quit");
try {
int playersChoice = sc.nextInt();
switch (playersChoice) {
case 1:
d.wordList(easyWords);
break;
case 2:
d.wordList(hardWords);
break;
case 3:
System.out.println("Thank you for your time!");
System.exit(0);
default:
System.out.println("Invalid input. Try again!");
initialize();
}
word = d.pickRandomWord(d.getWordList());
hideWord(word);
while(maxTries > 0) {
if(wordInProgress.contains("-")) {
System.out.println(wordInProgress);
revealLetter(notifyGuess());
} else {
System.out.println("Good work! You found the word.");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Use only digits!");
}
}
//TODO: Do not count same letter more than once & let player to know.
public char notifyGuess() {
ArrayList<Character> charSet = new ArrayList<>();
System.out.print("Please enter a letter: ");
char c = sc.next().charAt(0);
if(Character.isDigit(c)){
System.out.println("You can't use numbers. Please enter a letter.");
notifyGuess();
} else if(charSet.contains(c)) {
System.out.println("You already used '" + c + "' before.");
notifyGuess();
} else
charSet.add(c);
return c;
}
public void hideWord(String word) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
sb.append("-");
}
wordInProgress = sb.toString();
}
public void revealLetter(char c) {
try {
String temp = wordInProgress;
char[] charArray = wordInProgress.toCharArray();
for (int i = 0; i < word.length(); i++) {
if(c == word.charAt(i))
charArray[i] = word.charAt(i);
}
wordInProgress = new String(charArray);
if(temp.equals(wordInProgress)){
maxTries--;
ha.drawHanging(maxTries);
} else {
System.out.println("Good! There is '" + c + "' in the word.");
}
} catch (StringIndexOutOfBoundsException e) {
System.err.println("You have to enter a character!");
}
}
public String newGame(String input) {
System.out.println("Do you want to play again? (yes/no)");
input = sc.nextLine();
return input;
}
}
Try using this:
System.out.println("Do you want to play again? (yes/no)");
input = sc.next(); //<== here is the change
return input;

Categories

Resources