Else/If input isn't printing the correct response - java

The program asks the user questions and responds accordingly. I am using ArrayLists with if statements to accomplish this. I cannot understand why my else/if code is not working. When I respond with "North Carolina" I always receive the final response of "I would have never guessed!"
System.out.print("Where are you from? ");
states.add(scanner.next());
if (states.contains("Florida") || states.contains("florida")) {
System.out.println("So was I!\n");
} else {
if (states.contains("North Carolina") || states.contains("north carolina")) {
System.out.println("I hear that's a nice place to live.\n");
} else {
System.out.println("I would have never guessed!");
}
}

Your nesting is incorrect. When you start writing bigger more complex programs, you will learn to simplify your code for readability. Any time you have a bunch of if and if else statements the code can quickly become difficult to read/ and or debug. This is how I would write it.
public static static void main(String args[]){
List<String> states = new ArrayList<>();
whereAreYouFrom(states);
}
public static void whereAreYouFrom(List<String> states){
System.out.print("Where are you from? ");
states.add(scanner.next());
if (states.contains("Florida") || states.contains("florida")) {
System.out.println("So was I!\n");
return;
}
if (states.contains("North Carolina") || states.contains("north carolina")){
System.out.println("I hear that's a nice place to live.\n");
return;
}
System.out.println("I would have never guessed!");
}
If you want to get fancy, you can use a switch statement, but honestly the above way will probably be the most helpful to you for debugging in the future.

Related

How to get the Java Scanner utility to input twice

so heres my code
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") || response.equalsIgnoreCase("hi") || response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");}
else {
System.out.println("Invalid Input");
String responseG;
responseG = scr.nextLine();
if (responseG.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
}
}
}
im a bit of a noobie when it comes to java, I just started today, but after the else statment here, java terminates itself for some reason, and it just doesnt care about the rest of the code. I was looking online and I saw that if you wanted to take another input you used the .nextLine(); function (i dont think its called a function but you know what I mean) but after I type either hey, hello, or hi, it prints "Oh, well arent you well-mannered. Hello there, how are you?" and then I cant type anything else, and it says < terminated > . can anyone help? thanks
Edit: Apparently I'm supposed to move the "responseG" variable and next line into the if statment. When I do that it doesnt activate, (using eclipse IDE, and it just appears as white and as an error) and tells me to delete else. https://gyazo.com/1a27fa9ab8802d594cccb35ecc0cb663 picture of what happens. furthermore if i try to use an else if statment it also says to delete it
Hi, welcome to Stackoverflow!
Your program will only ask for another input from your keyboard if you don't type "hello" or "Hello", or "hey", you know what I mean. If you type "hello" then it will print a line with
"Oh, well aren't you well-mannered. Hello there, how are you?"
And the program will be terminated...
That's what your code it's telling your program to do, since you are only asking for another input in the else statement's body.
As I can see you don't want to use a for loop, since you seem to only care about a path that says hi... how are you?... good... glad to hear... but if you care for it, you can use a while() statement or a do..while() or a for() to make it save in the variable many responses with the scr.nextLine(); function (it is a function), in that case you have to define when/how the program is going to stop asking for input and will terminate.
I believe this is what does what you were trying to do, with the proper indentation, and not declaring unnecessary variables:
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") || response.equalsIgnoreCase("hi") || response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");
}
else {
System.out.println("Invalid Input");
}
//You don't need ResponseG... you've already created the response variable
response = scr.nextLine();
if (response.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
else {
System.out.println("Invalid Input");
}
}
}
You have to use a loop to keep the program working. After you get "Oh, well aren't you well-mannered. Hello there, how are you?" printed, it terminates the fact that there is no more tasks to do.
So what you want to do is move the ResponseG if statement into the your response if statement as that is stopping the code from complete since you are putting in the correct inputs. Also for future projects, to be more organized create variables at the beginning of the code.
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
String responseG;
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") ||
response.equalsIgnoreCase("hi") ||
response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");
responseG = scr.nextLine();
if (responseG.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
} else {
System.out.println("Invalid Input");
}
}
}

Im trying to make a text based game that looks like a PC terminal, i cant find a way to tell the user if they use a wrong sentence

//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}

Working with methods for a safecracker game

I am just busy with learning Java and my task is making a safecracker game. I need to do this game with classes and methods. But I came to until a point and I can't go further. Below I share my code and my questions. If you could have a look I will be so appreciate.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
entrance();
playGame();
quitGame();
}
private static void entrance() {
System.out.println("Welcome to the SafeCracker!\nI need your help to open the safe box." +
"\nThe code is with 3 digits and we need to find it out as quick as possible.\nLet's write your guess!");
}
private static int playGame() {
int[] safeCode = {takeRandomSafeCode(), takeRandomSafeCode(), takeRandomSafeCode()};
int guess = takeGuess();
//Below I need to use a for each loop but I don't get the logic of it. I stuck here. I need to check every numbers one by one but how?
for (int safeDigit : safeCode) {
if (safeDigit == guess) {
System.out.println("Your number is correct");
}
}
return playGame(); // with this return type I also have a problem.
If I return this method, it keeps going to play again and again.
But I don't know also which return type I need to give.
}
private static int takeGuess() {
Scanner keyboard = new Scanner(System.in);
int userGuess = keyboard.nextInt();
return userGuess;
}
private static int takeRandomSafeCode() {
Random random = new Random();
int result = random.nextInt(10);
return result;
}
private static int quitGame() {
System.out.println("Do you want to play again?\nPress 1 for play again\nPress 2 for quit the game!");
Scanner key = new Scanner(System.in);
int userWannaPlay = key.nextInt();
if(userWannaPlay == 1) {
System.out.println(playGame());
} else if (userWannaPlay == 2) {
System.out.println(quitGame());
} else {
System.out.println("You entered an invalid number. If you want to play again or quit, you need to click 1 or 2!");
}
return userWannaPlay; //And also quitGame method. I want to ask the users that if they want to play or not and according to answer I would like to run "playGame" method again or quit game.
}
}
Try to use a loop for your game.
You can set quitGame variable from playGame method or you can create a new method for user decision.
public static void main(String [] args){
entrance();
do{
playGame();
}while(!quitGame)
}
public void playGame(){
//Your code is here
}
If I return this method, it keeps going to play again and again. But I
don't know also which return type I need to give.
Your playGame*( method calls itself recursively in its last line return playGame(). I guess you did that to return anything at all. If you think about your problem you may come to the conclusion that you don't want to return anything at all (as you do not know what to do with it). In this case you may return nothing aka void as you did in your main method.
And also quitGame method. I want to ask the users that if they want
to play or not and according to answer I would like to run "playGame"
method again or quit game
You have to think about what you want. You want to call a method again and again depending on a condition. For that you can either use a loop or recursion. For exmaple you could change you main method slightly and add a do-while-loop.
public static void main(String[] args) {
entrance();
int condition;
do {
playGame();
condition = quitGame();
} while (condition == 1);
Don't forget to change you quitGame method because there you are trying to solve your problem recursively (remove the if clause). If you want to do it recursively though ignore the above and look at this snippet:
private static int quitGame() {
System.out.println("Do you want to play again?\nPress 1 for play again\nPress 2 for quit the game!");
Scanner key = new Scanner(System.in);
int userWannaPlay = key.nextInt();
if(userWannaPlay == 1) {
playGame(); // you dont need a println here
} else if (userWannaPlay == 2) {
// you dont need to anything here
System.out.println("Quitting...");
} else {
System.out.println("You entered an invalid number. If you want to play again or quit, you need to click 1 or 2!");
// call quitGame again to ask for the choice again
quitGame();
}
return userWannaPlay; // if you do it like this, this return is also unnecessary and you could use a void method without returning anything
}

Restarting program from a certain point after an if

I started studying Java not too long ago, I am currently trying to make a little game to see if I got the things I saw right.
I want to make a "game" that let's you choose between two dialogue options which have different consequences.
This is the code I used:
package programs;
import java.util.Scanner;
public class Programma1_0 {
public static void main(String[] args) {
System.out.println(
"You wake up in a laboratory. You don't remember ever being there. You actually don't remember anything.");
System.out.println("A door opens, a girl comes towards you.");
System.out.println("Girl:<<Hi, I see you woke up. How are you feeling?>>");
System.out.println("(Write Good or Bad)");
Scanner first = new Scanner(System.in);
String firstch = first.nextLine();
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
} else {
System.out.println("(I told you to write Good or Bad)");
}
}
}
So far it's working as intended. The only problem is that if I write something other than Good or Bad i get the message "(I told you to write Good or Bad)" and the program terminates. Is there a way to automatically restart it? If i put more choices in, I want the program to automatically restart from the question where it terminated (So I don't play through half of the game, get a question wrong and have to restart the program from the start), is that possible?
Thanks.
You can accomplish this by putting this before your if statement.
while (true) {
if (firstch.equals("Good") || firstch.equals("Bad"))
break;
else {
System.out.println("(I told you to write Good or Bad)");
firstch = first.nextLine();
}
}
Then you can also remove the last else part of your if statement.
Now it will continue asking for a new input till it gets either "Good" or "Bad"
You can simply put your if-else statement inside the do-while loop, that way you can loop through until you get correct response
int i = 0;
do {
System.out.println("(Write Good or Bad)");
firstch = first.nextLine();
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
i = 0;
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
i = 0
} else {
System.out.println("(I told you to write Good or Bad)");
i = 1;
}
} while (i == 1);
You can partition your program into separate methods. Here I created a method called retrieveAnswer() which its only task to create a Scanner and get input. This method will return a String as seen in the public static String header.
Another method I created was entitled getResult() which takes a String argument and will now compare the String passed from
String firstch = retrieveAnswer();
getResult(firstch);
If the result goes to the else block, it will call retrieveAnswer() and pass the value returned to getResult() as seen in getResult(retrieveAnswer()) which will then restart the whole process.
There are multiple solutions to this, but I just took the recursion route instead. Good luck with Java! If you are confused, look more into methods as they are VERY essential in programming.
import java.util.Scanner;
public class Source {
public static void main(String[] args) {
System.out.println(
"You wake up in a laboratory. You don't remember ever being there. You actually don't remember anything.");
System.out.println("A door opens, a girl comes towards you.");
System.out.println("Girl:<<Hi, I see you woke up. How are you feeling?>>");
System.out.println("(Write Good or Bad)");
String firstch = retrieveAnswer();
getResult(firstch);
}
public static String retrieveAnswer(){
Scanner first = new Scanner(System.in);
String firstch = first.nextLine();
return firstch;
}
public static void getResult(String firstch){
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
} else {
System.out.println("(I told you to write Good or Bad)");
getResult(retrieveAnswer());
}
}
}

Abbreviation Decoder Script in Java

I am working on a program that is supposed to pull abbreviated text meanings from a list that is created from if-else statements. I am running into trouble with the logic of making the program see an incorrect input and provide a suggestion from the supported list. Here is the code we were given to edit.
import java.util.Scanner;
public class TweetDecoder {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String origTweet = "";
System.out.println("Enter abbreviation from tweet: ");
origTweet = scnr.next();
if (origTweet.equals("LOL")) {
System.out.println("LOL = laughing out loud");
}
else if (origTweet.equals("BFN")) {
System.out.println("BFN = bye for now");
}
else if (origTweet.equals("FTW")) {
System.out.println("FTW = for the win");
}
else if (origTweet.equals("IRL")) {
System.out.println("IRL = in real life");
}
else {
System.out.println("Sorry, don't know that one.");
}
return;
}
}
This is for a class so I would like to know if someone can push me in the right direction rather than give the full answer or the string that I should be using. I feel like is should be something to do with String Comparison or String Access Operations but I cant seem to get it nailed down. If someone can assist I would greatly appreciate it. Thank you in advance!
it wouldn't let me add a comment, so i suppose here will do.
I would suggest looking into the .startsWith method. Its a method contained in the String class.
For example,
if(origTweet.startsWith("L")) //
System.out.println("Perhaps you meant LOL");
sorry if this isn't what you meant / wanted

Categories

Resources