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());
}
}
}
Related
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");
}
}
}
So I've seen a bunch of other posts about this, but they didn't apply since a) I'm trying to return to the main method while SKIPPING a while loop inside of the main. I'm making a text adventure game and it works in steps (separate methods), by calling the next step from within the step at the end. for example, the first step is EastStoryline1(), and the second is EastStoryline2(), and at the end of the code for EastStoryline1(), it says "EastStoryline2()".
So the actual main is pretty small, since it's just one method looping into the next. There are also 2 while loops in the main. The first comes right after I establish the scanner and boolean playagain, which basically surrounds the rest of the main starts the game while playagain = true. the second loop comes right after the first, which basically says while def (the players health) > 0, play the events of the game. After the second loop, but still in the first loop, the code calls the method Die(), and then asks the player whether they want to play the game.
SO basically, what code do I put inside Die() in order to break out of any existing loop chain and bring it to the next code after Die() is called in the main. The problem is that I also use Die() in other methods, and each time it's called I want it to return to the code after Die() in the main. Here's the code for the main (sorry for bad formatting):
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
boolean playagain = true;
while(playagain == true)
{
while(def > 0)
{
TitleScreen("TXT ADVENTURE!");
System.out.println("Pick a character: Rogue, Paladin, or Priest
(capitals DO matter!)");
String character = keyboard.next();
CharacterChoice(character);
System.out.println("You wake up on a dusty road, with no memory of who
you are or how you got here. You can only remember your name, and how to
fight. To the east lies a small dock with a boat. To the west, there seems
to be a sand-scarred mountain range. Do you go east, or west?");
String ew = keyboard.next();
EastWest(ew);
}
Die();
System.out.println("Do you want to play again?");
String playornah = keyboard.next();
if(playornah.equals("yes") || playornah.equals("Yes"))
{
playagain = true;
}
else
{
playagain = false;
}
}
}
And this was the code for Die I used system.exit(0), but now I want it to return to the main after Die is called there instead of just ending the program):
public static void Die()
{
System.out.println("GAME OVER");
System.exit(0); //I tried using break but it wouldn't compile
}
So what to I code in Die() in order for (no matter where it's called) return to the main after the spot where Die() is called.
public static void Die()
{
System.out.println("GAME OVER");
System.exit(0); //I tried using break but it wouldn't compile
}
System.exit(0); ends the program. If you want to just end the method either:
Let the method end naturally when it has no more statements. (Just remove System.exit(0);)
Replace System.exit(0); with a return; statement
From the docs:
A method returns to the code that invoked it when it
completes all the statements in the method,
reaches a return statement, or
throws an exception (covered later),
whichever occurs first.
You can't return from an external method, How ever you can use a try-finally to return it once you have run your code.
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.
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
}
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