So I'm looking to make a little text based adventure in Java. I'm a beginner and I want to have the user choose their name, gender, etc. and then for each bit, have it ask for confirmation and then once they have confirmed all of their input, ask again to make sure.
I'm not very knowledgeable about loops or that sort of thing so if someone could leave a mini-lesson and a suggestion on how to get this working, I would very much appreciate it. Thank you!
This is purely for entertainment and I welcome any constructive criticism that would make this more effective. Please do not mind the mess of pronouns.
import java.util.*;
public class Emu {
public static void main(String[] args) {
Scanner menu = new Scanner(System.in);
System.out.println("What is your hero's name?");
String name = menu.nextLine();
System.out.println("So their name is " + name + "? (Y/N)");
char cc1 = menu.next().charAt(0);
//If yes, continues, if not, loops back to the question where the name is set
System.out.println();
System.out.println("Okay, is " + name + " a male or female? (M/F)");
char gender = menu.next().charAt(0);
String genPro, genPos, genRef, genChild, genAdult;
switch (gender) {
case 'M':
genPro = "He";
genPos = "His";
genRef = "Him";
genChild = "boy";
genAdult = "guy";
break;
case 'F':
genPro = "She";
genPos = "Hers";
genRef = "Her";
genChild = "girl";
genAdult = "woman";
break;
default:
genPro = "It";
genPos = "It";
genRef = "It";
genChild = "It";
genAdult = "It";
break;
}
System.out.println("Okay! So " + name + " is a " + genChild + "? (Y/N)");
char cc2 = menu.next().charAt(0);
//If yes, continues, if not, loops back to the question where the gender is set
System.out.println("So " + name + " is a " + genChild + "? (Y/N)");
char cc3 = menu.next().charAt(0);
//If yes, continues, if not, loops back to the question where the name is set
System.out.println(name + " was born a healthy young " + genChild + ", in the city of PLACEHOLDER");
}
}
A do-while loop is the typically used loop construct when unconditionally doing something once, and maybe having to backtrack.
Depending on how you want to handle invalid inputs (i.e. not Y or N), you may need two do-while loops. In the example below, it will keep prompting with "So their name is..." until Y or N is entered, and will only ask for the name again if N is entered.
char confirmation;
String name;
do
{
System.out.println("What is your hero's name?");
name = menu.nextLine();
do {
System.out.println("So their name is " + name + "? (Y/N)");
confirmation = menu.nextLine().charAt(0);
} while (confirmation != 'N' && confirmation != 'Y');
}
while (confirmation == 'N');
Related
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean start = true;
while(start)
System.out.printf("%70s %n", " ##### Zoos Australia ##### " + "\n");
System.out.printf("%57s %n", "Main Menu" + "\n");
System.out.printf("%72s %n", "Zoo has the following ticketing options:");
System.out.print("\n");
System.out.printf("%59s %n", "1 = Child (4-5 yrs)");
System.out.printf("%59s %n", "2 = Adult (18+ yrs)");
System.out.printf("%60s %n", "3 = Senior (60+ yrs)");
System.out.println("\n");
String choose1 = "";
String choose2 = "";
String choose3 = "";
String selected = "";
int option = 0;
{
System.out.print("Please select an option: ");
option = input.nextInt();
if (option == 1) {
choose1 = "Child";
selected = choose1;
} else if (option == 2) {
choose2 = "Adult";
selected = choose2;
} else if (option == 3) {
choose3 = "Senior";
selected = choose3;
}
}
// done
System.out.println("\n");
int price = 0;
int tickets = 0;
System.out.print("Enter the number of tickets: ");
tickets = input.nextInt();
if (selected == choose1) {
price = 10;
} else if (selected == choose2) {
price = 20;
} else if (selected == choose3) {
price = 15;
}
System.out.println("\n");
System.out.print("You are purchasing " + tickets + " " + selected + " tickets at " + "$" + price + " each!");
System.out.println("\n");
int confirm = 0;
System.out.print("Press 1 to confirm purchase: ");
confirm = input.nextInt();
if (confirm != 1) {
System.out.print("Incorrect Key. Please return to Main Menu");
System.out.println("\n");
} else {
break;
}
System.out.println("\n");
int total = tickets;
price = total * price;
System.out.print("Total amount for " + selected + " tickets: " + "$" + price);
System.out.println("\n");
String pick = "";
System.out.print("Do you wish to continue: ");
input.next();
System.out.println("\n");
if (pick == "no") {
System.out.print("Total amount payable is: " + "$" + price);
System.out.println("\n");
System.out.print("Have a nice day!");
System.out.println("\n");
}}}
Trying to do this at the end of the program where user is asked "Do you wish to continue" using a method or something but cant get it to work. Either the program returns to main menu only or the program ends and displays the total message "Total amount payable..." etc. I have tried using while with continue and break. Using boolean with true and false. But no luck. Thank you anyone that may be able to clear this up for me please.
First, you have to assign the users's input to a variable: pick = input.next(). After that, the problem is that you compare the user's input string with a "no" string by using == operator. When comparing reference types (objects) (and String is an object), in most cases == operator gives you an unpredictable result, because it compares the reference (address of an object in memory) and not the actual content. Please remember, that you always have to use the .equals() method instead. You also have to break from your loop, when the user's input is "no".
There is plenty of material concerning this issue. You can check, for instance, this one How do I compare strings in Java?
P.S. I quickly looked at the rest of your code and put some additional comments, which might help you to improve it. Good luck with learning Java!
Scanner input = new Scanner(System.in);
// boolean start = true; you don't need this line
while(true) { // 'true' condition makes it an infinite loop until you use break
// You also have to surround your while loop with curly braces,
// otherwise you fall into an infinite loop
System.out.printf("%70s %n", " ##### Zoos Australia ##### \n");
System.out.printf("%57s %n", "Main Menu\n");
System.out.printf("%72s %n", "Zoo has the following ticketing options: \n");
System.out.printf("%59s %n", "1 = Child (4-5 yrs)");
System.out.printf("%59s %n", "2 = Adult (18+ yrs)");
System.out.printf("%60s %n", "3 = Senior (60+ yrs)\n");
String choose1 = "";
String choose2 = "";
String choose3 = "";
String selected = "";
int option = 0;
System.out.print("Please select an option: ");
option = input.nextInt();
if (option == 1) {
choose1 = "Child";
selected = choose1;
} else if (option == 2) {
choose2 = "Adult";
selected = choose2;
} else if (option == 3) {
choose3 = "Senior";
selected = choose3;
}
System.out.println(); // "\n" is a redundant argument
int price = 0;
int tickets = 0;
System.out.print("Enter the number of tickets: ");
tickets = input.nextInt();
if (selected.equals(choose1)) { // you should never compare strings with == operator! Always use .equals() instead
price = 10;
} else if (selected.equals(choose2)) {
price = 20;
} else if (selected.equals(choose3)) {
price = 15;
}
System.out.println();
System.out.print("You are purchasing " + tickets + " " + selected + " tickets at " + "$" + price + " each!");
System.out.println();
int confirm = 0;
System.out.print("Press 1 to confirm purchase: ");
confirm = input.nextInt();
if (confirm != 1) {
System.out.print("Incorrect Key. Please return to Main Menu");
System.out.println("\n");
} else {
//break; you cannot use 'break' in the if statement! You have to figure out another way, how to handle an invalid input
}
System.out.println();
int total = tickets;
price = total * price;
System.out.print("Total amount for " + selected + " tickets: " + "$" + price);
System.out.println();
String pick = "";
System.out.print("Do you wish to continue: ");
pick = input.next(); // you have to assign the input to a variable
System.out.println();
if (pick.equals("no")) { // You have to ALWAYS use .equals() when comparing Strings or any other reference types! == works correctly only with primitive types
System.out.print("Total amount payable is: " + "$" + price);
System.out.println();
System.out.print("Have a nice day!");
System.out.println();
break; // you need to break from the loop in the end
}
}
}
So I'm starting to get the hang of java, and I'm creating a quiz as a mini project. However, when I get to the input part of my program, it breaks down. What's going on?
I also apologize for the formatting
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int score = 0;
int total = 0;
System.out.println("Are you ready for a quiz? (Y/N)");
char answer = in.findInLine(".").charAt(0);
if (answer == 'Y' || answer == 'y');
{
String a = "Barrow";
String b = "Juneau";
String c = "Anchorage";
String d = "Annapolis";
System.out.println("Alright! Lets get right to it!");
System.out.println("What is the Capital of Alaska?");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
char choice = in.findInLine(".").charAt(0);
if (choice == 'B' || choice == 'b')
{
System.out.println("Good Job! 1 point for you!");
score = score + 1;
}
else
{
System.out.println("Incorrect! the answer was actually " + b);
}
String e = "Yes";
String f = "No";
System.out.println("Alright, Next Question! Can you"
+ " store the value 'cat' in a variable of type int?");
System.out.println("A: " + e);
System.out.println("B: " + f);
char secchoice = in.findInLine(".").charAt(0);
if (secchoice == 'A' || secchoice == 'a')
{
System.out.println("Correct! Good Job!");
score = score + 1;
}
else
{
System.out.println("Incorrect");
}
System.out.println("What is the result of 2+2X3-5?");
int result = in.nextInt();
if (result == 3)
{
System.out.println("Correct! Good Job!");
}
else
{
System.out.println("Incorrect");
}
System.out.println("Your total score was " + score + "out of 3");
}
}
}
You are getting a NullPointerException on line 26 because of the way that findInLine() works. Basically, you have used up the one line of input you give it when it starts and the Scanner has advanced passed it to find the next one (which does not exist). In other words, you should use another method for Scanner or use an entirely different approach for getting input.
For example, it is preferable to use this technique
char answer = in.nextLine().charAt(0);
because nextLine() will wait until it has more input.
Of course, you will have to come up with some way to parse the input from the user to make sure that it is valid (i.e. if they can only choose between 'Y' and 'N' you handle the case where they choose neither).
That would look something like
char answer = parseInput(in.nextLine().charAt(0));
where parseInput(String s) is a method you write yourself.
As far as other approaches go, this tutorial from Oracle can help you get started.
Tester is called and executed if the player inputs a certain name.
Variable testerWrong doesnt add one when testerWrong++ is executed
private void Tester(){
int testerTotal;
int testerScore;
int testerWrong;
testerTotal = 0;
testerScore = 0;
testerWrong = 0;
System.out.println("");
System.out.println("Hello tester, you're the designated tester. Would you like to take the quiz? Y/N");
Scanner yesno = new Scanner(System.in);
String YesNo = yesno.next();
if(YesNo.equals("Y") || YesNo.equals("y")){ //This type of code will appear very often
System.out.println("Okay, let's being!"); //if the user input (YesNo) is Y or y then...
}else{
if(YesNo.equals("N") || YesNo.equals("n")){
System.out.println("Okay, maybe some other time");
}else{ //else...
System.out.println("Sorry, i do not recognise what you entered. Please restart the program.");
}
}
System.out.println("");
QUIZ enter = new QUIZ();
enter.e2c();
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Question #1");
System.out.println("");
System.out.println("The answer is A");
System.out.println("");
System.out.println(" - A. ");
System.out.println(" - B. ");
System.out.println(" - C. ");
System.out.println(" - D. ");
Scanner testerQ1 = new Scanner(System.in);
String TesterQ1 = testerQ1.next();
if(TesterQ1.equals("A") || TesterQ1.equals("a")){
testerScore++;
System.out.println("Correct! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
System.out.println("");
System.out.println("Next Question.");
System.out.println("");
}else{
testerWrong++;
System.out.println("Incorrect! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
System.out.println("");
}
Is there a way to make the variable execute without having to add a system output before it?
Thanks
This is not a minimal (way too many print statements) or even complete example (the QUIZ class is not included).
Narrowing your code down to a minimum example:
import java.util.Scanner;
public class Tester {
public static void main(String args[]) {
int testerScore = 0;
int testerWrong = 0;
System.out.println("The answer is A");
Scanner scanner = new Scanner(System.in);
String answer = scanner.next();
if (answer.equals("A") || answer.equals("a")) {
testerScore++;
System.out.print("Correct!");
}
else {
testerWrong++;
System.out.println("Incorrect! ");
}
System.out.println(" You hve answered " + testerScore +
" correct and " + testerWrong + " incorrect!");
}
}
This works for me. Compare your code against this and see what you are doing differently.
If you cannot find the problem that way, run your code in a debugger. Step through the program to see what it does when.
You may also want to follow Java naming conventions (variables start with lower case letters, classes start with upper case letters but aren't all upper case), to make it easier for others to read your code.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This java code is not printing what I want it to print.It is printing the last line "The above command is only acceptable "
import java.util.Scanner;
public class Recap1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hi ! I am your dumb assistant, Dumbo");
System.out.println("Tell me your name");
String YourName = input.nextLine();
System.out.println("these are a list of commands which can tell me what to do :-");
String CurrentAffairs = "Tell me the current affairs";
String Dinner = "Cook my dinner" ;
String Marriage ="Will you marry me ?";
String Name = "What is my name ?";
String gift = "Buy me a gift";
System.out.println("Tell me the current affairs ");
System.out.println("Cook my dinner ");
System.out.println("Will you marry me ?");
System.out.println("What is my name ?");
System.out.println("Buy me a gift");
System.out.println("now write a command !!!");
String FirstCommand = input.nextLine();
if (FirstCommand == CurrentAffairs)
System.out.println("The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid");
else if
(FirstCommand == Dinner)
System.out.println("I can only cook roasted human brain covered with melted intestines sprinkled with blood sauce.I need the nearest human availible to me.Will you volunter? ");
else if
(FirstCommand == Marriage)
System.out.println("You are fine but I am afraid you are not of my type");
else if
(FirstCommand == Name)
System.out.println("Your name must be " + " " + YourName);
else if
(FirstCommand == gift)
System.out.println(" Give me some money and I will buy a gift for you.Deal ?");
else
System.out.println("Only the above commands are acceptable !!!!!!!!!!!!!!");
}
}
Yeah, you've got to compare strings using .equals()
if (FirstCommand.equals(CurrentAffairs))
{
System.out.println( "The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid" );
}
and you're probably better off having this entire if statement as a switch statement.
switch ( FirstCommand )
{
case "Tell me the current affairs":
System.out.println(The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid);
break;
default:
System.out.println( "Only the above commands are acceptable !!!!!!!!!!!!!!" );
break;
}
You should use
if (FirstCommand.equals( CurrentAffairs))
NOTE: for compare two string value need to use equals() instead of == because == compare reference value not a content
Try this its working fine.
public class Recap1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hi ! I am your dumb assistant, Dumbo");
System.out.println("Tell me your name");
String YourName = input.nextLine();
System.out.println("these are a list of commands which can tell me what to do :-");
String CurrentAffairs = "Tell me the current affairs";
String Dinner = "Cook my dinner" ;
String Marriage ="Will you marry me ?";
String Name = "What is my name ?";
String gift = "Buy me a gift";
System.out.println("Tell me the current affairs ");
System.out.println("Cook my dinner ");
System.out.println("Will you marry me ?");
System.out.println("What is my name ?");
System.out.println("Buy me a gift");
System.out.println("now write a command !!!");
String FirstCommand = input.nextLine();
if (FirstCommand.equalsIgnoreCase(CurrentAffairs))
System.out.println("The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid");
else if (FirstCommand.equalsIgnoreCase(Dinner))
System.out.println("I can only cook roasted human brain covered with melted intestines sprinkled with blood sauce.I need the nearest human availible to me.Will you volunter? ");
else if (FirstCommand.equalsIgnoreCase(Marriage))
System.out.println("You are fine but I am afraid you are not of my type");
else if(FirstCommand.equalsIgnoreCase(Name))
System.out.println("Your name must be " + " " + YourName);
else if (FirstCommand.equalsIgnoreCase(gift))
System.out.println(" Give me some money and I will buy a gift for you.Deal ?");
else
System.out.println("Only the above commands are acceptable !!!!!!!!!!!!!!");
}
}
This is an efficient way to accomplish what you are trying to do. Instead of taking the string as an input, you take integer. Makes this simple and error free.
import java.util.Scanner;
public class Recap1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hi ! I am your dumb assistant, Dumbo");
System.out.println("Tell me your name");
String YourName = input.nextLine();
System.out.println("these are a list of commands which can tell me what to do :-");
String[] replies = {"The Year is 2016" + "You are reading this" + "You are smiling " + "You are stupid"
,"I can only cook roasted human brain covered with melted intestines sprinkled with blood sauce.I need the nearest human availible to me.Will you volunter? ",
"You are fine but I am afraid you are not of my type","Your name must be ",
" Give me some money and I will buy a gift for you.Deal ?"};
System.out.println("1.Tell me the current affairs ");
System.out.println("2.Cook my dinner ");
System.out.println("3.Will you marry me ?");
System.out.println("4.What is my name ?");
System.out.println("5.Buy me a gift");
System.out.println("now write a command !!!");
int FirstCommand = input.nextInt();
switch(FirstCommand)
{
case 1:
case 2:
case 3:
case 5: System.out.println(replies[FirstCommand-1]);
break;
case 4 : System.out.println(replies[FirstCommand-1]+" "+YourName);
break;
default:
System.out.println("Only the above commands are acceptable !!!!!!!!!!!!!!");
break;
}
}
}
When I type in this code it gives me a return that once I use yes for the first time, on the name, it uses that return for all of them for example: if I said my name is Justin, and I said that "Yes" it is, then say I mistyped my age, then it would not give me a chance to change it, it would say "Great!". How do I fix this? I am in 9th grade so I don't know too much about programming, sorry for the noob question. Thanks in advance!
import java.util.Scanner;
public class helloworld_main {
private static Scanner scan;
public static void main(String args[])
{
scan = new Scanner(System.in);
String name, age, year, yes, no, no1, no2;
System.out.print("Please enter your name --> "); // user prompt
name = scan.nextLine();
System.out.print("Please enter your age --> "); // user prompt
age = scan.nextLine();
System.out.print("Please enter the year you were born --> "); // user prompt
year = scan.nextLine();
// Their Name
System.out.println("So your name is... " + name + ". Right?"); // correction if name is not correct
yes = scan.nextLine();
if ("Yes".equals(yes))
{
System.out.println("Great!");
} else {
System.out.println("Oh. Please retype it.");
no = scan.nextLine();
System.out.println("Hello, " + no);
}
// The Age
System.out.println("The age you entered is..." + age + ". Right?");
if ("Yes".equals(yes))
{
System.out.println("Great!");
} else {
System.out.println("OK. Please reenter your age.");
no1 = scan.nextLine();
System.out.println("OK, I love " + no1 + " year olds!");
}
// Year Born
System.out.println("The year you were born is... " + year + ". Right?");
if ("Yes".equals(yes))
{
System.out.println("Fantastic!");
} else {
System.out.println("Ok then, please tell me what year you were born again.");
no2 = scan.nextLine();
System.out.println("Cool! I know someone else born in " + no2);
}
scan.close();
}
}
You need to read the user input again after you prompt for it again. Add:
yes = scan.nextLine();
after:
System.out.println("The age you entered is..." + age + ". Right?");
and:
System.out.println("The year you were born is... " + year + ". Right?");