I am trying to make a simple text adventure game in Java and when I type Quit it ends the game. But instead it will ask if you want to do the quest even if you type quit which is suppose to end the code, I tried using loops to fix this error but had to luck. Any idea where I went wrong?
import java.util.*;
public class TextGame {
public static void main(String[] args) {
//Boolean run = true;
//while (run){
Scanner in = new Scanner(System. in );
System.out.println("~SPECTRE~");
System.out.println("");
System.out.println("Please Choose One Below");
System.out.println("");
System.out.println("New");
System.out.println("Quit");
System.out.println("");
String option;
System.out.print("Select one of the options here: ");
option = in .next();
if (option.equals("New")) {
System.out.println("Hello adventurer! Welcome to the land of Spectre.");
String name;
System.out.print("What is your name adventurer? ");
name = in .next();
System.out.println("Hello there! " + name);
} else if (option.equals("Quit")) {
System.out.println("*Returns to desktop*");
}
String quest;
System.out.print("Would you like to go on a quest? ");
quest = in .next();
if (quest.equals("Yes")) {
System.out.println("Here is a list of quests that I would like you to do ");
System.out.println("");
System.out.println("1) Fight the evil troll of Port Howlham");
System.out.println("");
System.out.println("2) Deliver supplys to the soliders in need");
System.out.println("");
System.out.println("3) Find the Kings lost son");
System.out.println("");
System.out.println("4) Find the Gemstone of Darlingbee to defeat the evil witch of Hobbitstone");
} else {
option.equals("");
System.out.println("*Please pick New Game or Quit*");
}
}
}
try this:
} else if (option.equalsIgnoreCase("Quit")) {
System.exit(0);
}
Or this:
} else if (option.equalsIgnoreCase("Quit")) {
return;
}
You're probably looking to exit the program. Use System.exit(0);
else if(option.equals("Quit"))
{
System.exit(0);
}
The 0 argument is a status code that indicates normal termination of the program.
You can use System.exit(code) to finish the program. Put this at the end of the else if block:
if (option.equals("Quit") {
...
System.exit(0);
}
The code can be any integer:
The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
Related
The code is for multiple choice question. If the answer is incorrect, the user should try until they find the right answer. When the answer is correct, there is no problem, but if it is wrong then it gets stuck, and it is keep saying "Your answer is incorrect!". What should I do?
import java.util.*;
public class Question {
public static void main(String[] args) {
System.out.println();
System.out.println("Question 1");
System.out.println();
System.out.println("What is 2+2?");
System.out.println("A. 2");
System.out.println("B. 4");
System.out.println("C. 6");
System.out.println("D. 8");
Scanner input = new Scanner(System.in);
char getAnswerFromUser = input.next().charAt(0);
char answer = 'B';
boolean isAnswerTrue = false;
while(!isAnswerTrue) {
if(getAnswerFromUser == answer ) {
System.out.println("Your answer is correct!");
isAnswerTrue = true;
} else{
System.out.println("Your answer is incorrect!");
isAnswerTrue = false;
}
}
}
}
You are not actually getting a new answer from the user inside your loop. You are only getting it once, in the line where you define the variable getAnswerFromUser. You need to actually get a new answer. I suggest putting it into a separate method to keep that step clean from the step where you use that answer.
I have a program where the user is asked multiple choice questions and one of the choices to every question is to exit.
If exit is chosen, I then have to ask whether user wants to start again, if yes, I want to loop back to a certain checkpoint. If not, the program terminates.
Below is a simplified sample with only one question. The program I'm trying to build has multiple.
Is there a way that does not involve nested loop upon nested loops upon nested loops?
import java.util.Scanner;
class RandomStuff {
/* this is not the actual program, just a simplified version to show what I'm trying to figure out
let's pretend perfect input
*/
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
// checkpoint I wish to loop back to. Not the beginning of the program
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
/* loop to checkpoint*/ }
else
System.exit(0);
break;
}
/* afterwards, a few other rounds of asking an input an looping to the same checkpoint
when appropriate. Essentially I'm looking for a method to loop back to checkpoint
from any decision to be made
*/
keyboard.close();
}
}
Use of recursive functions is the best alternative for loops. Instead of writing your choices in the main method you can use anther method like below:
import java.util.Scanner;
class Random{
public static void Choice(Scanner keyboard){
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
Choice(keyboard);
//Function will be called again
}
else
System.exit(0);
break;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Choice(sc);
}
}
But this can also easily be done with the use of a single do-while loop
See this:
import java.util.Scanner;
class Random{
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
boolean run = true;
do{
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
continue;
}
else
run = false;
//terimanting the loop
break;
}
}
while(run);{
System.out.println("User chose to exit");
System.exit(0);
}
}
}
I tested both the programs and they run fine on my end, if you have any problem or you can't understand something, just tell me.
I'm looking to repeat a "game" if it is already satisfied in my case where user has to guess the random number. I can't understand where to to get back to the main game unless i have to create another "do - while" loop inside it and retype the game again in the section where it says: System.out.println("you have tried: " + count + " times. Would you like to play again? y/n"). Is there a way to just bring back to the actual guess loop rather than create another one?
Hopefully makes sense.
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
int guess;
int count;
count = 0;
int num;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
**System.out.println("you have tried: " + count + " times. Would you like to play again? y/n");**
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
}
The simplest solution would be to move the entire "guess loop" into a separate method. Then in the case when you want it to repeat, just call the method recursively.
If you want to reuse code you can make functions (or methods here, because we are inside a class). They can be used to encapsulate code and call it from anywhere to use it.
You can define a methods like that:
public static void methodName() {
// code go here
}
Then, you can call it from anywhere like that :
pass.methodName(); // It will execute the code inside methodName()
In reality, this is a lot more complex than that, you can give methods values and return others, change the scope of it to make it internal only or reachable by other classes. But I presume that you are a beginner so I keep it simple. I strongly recommend you to make a quick research about Object Oriented Programmation!
For your code, you can put the game's while loop in a method and call it at the beginning and each time the player wants to restart the game. Good luck with your game!
I manage to do this way. It seems working but one thing is letting me down at the very last when I key in "n" or other key than "y". Exception in thread "main" java.util.InputMismatchException. Is there a more softer way to finish it?
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void randomnum(){
Scanner scanner = new Scanner(System.in);
int guess;
int count;
count = 0;
int num;
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
System.out.println("you have tried: " + count + " times.");
String answer;
do{
System.out.println("Do you want to play again? y/n");
answer = scanner.next();
if (answer.equals("y")) {
System.out.println("let's play again");
randomnum();
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
}
else {
System.out.println("you are logout!");
break;
}
}while (answer.equals("Y"));
randomnum();
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
randomnum();
}
}
I'm currently developing a math game for elementary students and I'm trying to let the user continuously enter an answer until they get the question correct. Then I want them to move onto the next question. When I run the code below it gives me 2 chances to enter the correct answer but it wont show my 'Correct' message after the second time.
import java.util.Scanner;
public class test{
public static void main (String[]args){
Scanner kb= new Scanner(System.in);
double r5q1,r5q2,r5q3,r5q4,r5q5;
System.out.println("Welcome to the money level.. This is the last and most difficult level!");
//Question 1
System.out.println("Question 1: I have $10.00 and I buy a candy bar for $3.00. How much change will I get?");
r5q1=kb.nextDouble();
if(r5q1==7)
System.out.println("Correct!");
else
System.out.println("Try again!");
r5q1=kb.nextDouble();
}
}
This is a photo of my code
Put your input taking code inside do while loop and in while condition check for correct output
do{
statements(s)
}while(condition);
try this.
import java.util.Scanner;
public class Main
{
public static void main (String[] args)
{
Scanner cin = new Scanner(System.in);
int ans = 123;
do {
System.out.println("Your question here.\n");
} while (cin.nextInt() != ans);
System.out.println("correct!\n");
}
}
while(userAnswer != realAnswer){
System.out.print("Wrong answer. Try again: ");
userAnswer = in.nextInt(); // or whatever you need instead of int
}
You have to use a while loop. This loop repeats its "contents" (the code inside the curly brackets) while its condition (the boolean value inside the normal brackets) is true. In this case, the condition is that the input is incorrect and the "content" is the code which prints the "Try again!" message.
Here's a demonstration:
Scanner scanner = new Scanner(System.in);
while (scanner.nextDouble() != 7) {
System.out.println("Try again!");
}
System.out.println("Correct!");
declare a flag value. And initially set it to 0. flag=0;
do{
if(r5q1==7){
flag=1;
break;
}
else{
continue;
}
}while(r5q1!=7);
if(flag==1)
{
System.out.println("Correct");
}
else
{
System.out.println("Wrong");
}
Thanks admin! That worked very well!
import java.util.Scanner;
public class test{
public static void main (String[]args){
Scanner kb= new Scanner(System.in);
double r5q1,r5q2,r5q3,r5q4,r5q5;
System.out.println("Welcome to the money level.. This is the last and most difficult level!");
//Question 1
System.out.println("Question 1: I have $10.00 and I buy a candy bar for $3.00. How much change will I get?");
r5q1=kb.nextDouble();
do{
System.out.println("Try again!");
r5q1=kb.nextDouble();
}while(r5q1!=7);//This is the answer to the question
System.out.println("Correct!");
//Question 2
System.out.println("Question 2: I have $15.00 and I buy 5 apples for $1.00 each. How much change will I get?");
r5q1=kb.nextDouble();
do{
System.out.println("Try again!");
r5q2=kb.nextDouble();
}while(r5q2!=10); //This is the answer to the question
System.out.println("Correct!");
}
}
I am trying to make a program which can accept certain integer type input from user, but stop the input as soon the user enters "stop".
I have tried doing so, but it's not working properly. Have a look.
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.io.*;
class Iron {
public static void main(String args[]) throws InterruptedException {
Scanner in = new Scanner(System.in);
System.out.println("Do you wanna play?, type yes to start.");
String a = in.nextLine();
String b; String c="goo";
String d,e="helloWorld";
String al="helloworld";
int f=0,g;
if (a.equalsIgnoreCase("yes")) {
System.out.println("Thanks for staring the game ");
TimeUnit.SECONDS.sleep(1);
System.out.println("-------Welcome to Need For Fun-------");
System.out.println();
TimeUnit.SECONDS.sleep(1);
while (!c.equalsIgnoreCase("yes")) {
System.out.println();
System.out.println("Enter your name_");
b = in.nextLine();
System.out.println("Is your name " + b + "?");
System.out.println("If yes type yes or if not type something else");
c = in.nextLine();
}
TimeUnit.SECONDS.sleep(0);
System.out.println("So, the game is quite similar to hand cricket");
System.out.println("You will win, if your number and Computer's number are equal");
System.out.println("To stop the game any time type start");
System.out.println();
TimeUnit.SECONDS.sleep(1);
System.out.println("So ready to play the game?, type yes to confirm.");
d = in.nextLine();
if(d.equalsIgnoreCase("yes"));
{
while(!al.equalsIgnoreCase("stop")) {
System.out.println();
try {
System.out.println("Type your number");
e = in.nextLine();
f = Integer.parseInt(e);
}
catch(NumberFormatException e1) {
al = in.nextLine();
if(al.equalsIgnoreCase("stop"))
break;
}
if (f < 10) {
g = (int) (Math.random() * 10);
if (f == g)
System.out.println("Congrats, you won. ");
else
System.out.println("Oops!, try again");
} else if (f>10)
System.out.println("Please enter a number between 1-10");
}
System.out.println("Thanks for playing, better luck next Time");
}
}
}
}
It does stops when I type stop, but I need to enter it two times.
Here's the run tab where I executed my program.
Do you wanna play?, type yes to start.
yes
Thanks for staring the game
-------Welcome to Need For Fun-------
Enter your name_
gourav
Is your name gourav?
If yes type yes or if not type something else
yes
So, the game is quite similar to had cricket
You will win, if your number and Computer's number are equal
To stop the game any time type start
So ready to play the game?, type yes to confirm.
yes
Type your number
4
Oops!, try again
Type your number
54
Please enter a number between 1-10
Type your number
4
Oops!, try again
Type your number
stop
3
Oops!, try again
Type your number
stop
stop
Process finished with exit code 0
change this block
catch(NumberFormatException e1) {
al = in.nextLine();
if(al.equalsIgnoreCase("stop"))
break;
}
to
catch(NumberFormatException e1) {
if(e.equalsIgnoreCase("stop"))
break;
}