Why is this not printing the desired output? [duplicate] - java

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;
}
}
}

Related

Creating a confirmation loop

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');

Correct use for Switch? Menu option order a Sandwich OR Salad

Good Morning/Afternoon,
Below is the code I've written for my Java class ( As in school homework ). I'm not here trying to get someone to do the homework for me.
My question is: Can the switch/case be used how I have it set?
Prompt user for input 1 or 2. Answer 1 they are getting a sandwich, answer 2 they are getting a salad.
The instructions for this program starts with the customer will order a sandwich or a salad. Then proceed to add toppings for an additional charge and can decline extra toppings as well.Then print out the order and total. The professor specified to use IF statements and the Switch. However, I have a feeling I am missing something because it looks like the Switch is the replacement of the IF statements in the examples I've found on Stack. Thank you for any and all assistance!
import java.util.Scanner;
//loaded scanner to take user input
public class Restaurant
//dude change this, do 3 outputs asking for input 1 input 2 input 3 make those if statements after
{
/* Author:
Date:
Program: create a class that will offer a sandwich for $7.00 with optional three
toppings lettuce, tomato, cheese $1.00 each
or a salad with optional two toppings tomatos, cheese $0.50 each.
*/
public static void main(String[] args)
{
// Declarations sandwich,salad,Sandwich-cheese,Sandwich-tomato,Sandwich-lettuce, salad-cheese, salad-tomato.
double sandwich = 7.00;
double salad = 7.00;
double sandChe = 1.00;
double sandTom = 1.00;
double sandLet = 1.00;
double salChe = .50;
double salTom = .50;
int userInput;
int userInput1;
int userInput2;
int userInput3;
double sandTotal;
double saladTotal;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 1 for a Sandwich or 2 for a Salad");
int userInput = scanner.nextLine();
switch(userInput)
{
case 1: // a sandwich was ordered
System.out.println("Enter 1 for additional topping of lettuce or press 2");
int userInput1 = scanner.nextLine();
System.out.println("Enter 1 for additional topping of cheese or press 2");
int userInput2 = scanner.nextLine();
System.out.println("Enter 1 for additional topping of tomato or press 2");
int userInput3 = scanner.nextLine();
if (userInput1 == 1 && userInput2 == 1 && userInput3 == 1)
{
saladTotal = (sandwich + sandLet + sandChe + sandTom);
System.out.println("Your bill comes to a total of: " + sandTotal + " Thank you, Have a great day!");
if (userInput1 == 1 && userInput2 == 2 && userInput3 == 2)
{
sandTotal = (sandwich + sandLet);
System.out.println("Your bill for a salad with additional tomato toppings comes too: " + sandTotal + " Thank you, Have a great day!");
if (userInput1 == 1 && userInput2 == 1 && userInput3 == 2)
{
sandTotal = (sandwich + sandLet + sandChe);
System.out.println("Your bill for a salad with no additional toppings comes too: " + salad + " Thank you, Have a great day!");
if (userInput1 == 1 && userInput2 == 2 && userInput3 == 1)
{
sandTotal = (sandwich + sandLet + sandTom );
System.out.println("Your bill for a sandwich `enter code here`lettuce and tomato comes too: " + sandTotal + " Thank you, Have a great day!");
if (userInput1 == 2 && userInput2 == 1 && userInput == 1)
{
sandTotal = (sandwich + sandChe + sandTom);
System.out.println("Your bill for a sandwich with cheese and tomato comes too: " + sandTotal + " Thank you, Have a great day!");
if (userInput1 == 2 && userInput2 == 2 && userInput3 == 2)
{
System.out.println("Your bill for a sandwich comes too: " + sandwich + " Thank you, Have a great day!");
}// end if 1
}//end if 2
}//end if 3
}//end if 4
}//end if 5
}//end if 6
}
}
}
// switch case below
case 2: // a salad was ordered
{
System.out.println("Press 1 for additional topping of cheese or press 2");
int userInput1 = scanner.nextLine();
System.out.println("Press 1 for additional topping of tomato or press 2");
int userInput2 = scanner.nextLine();
if (userInput1 == 1 && userInput2 == 2)
{
saladTotal = (salad + salChe);
System.out.println("Your bill comes to a total of: " + saladTotal + " Thank you, Have a great day!");
if (userInput1 == 2 && userInput2 == 1)
{
saladTotal = (salad + salTom);
System.out.println("Your bill for a salad with additional tomato toppings comes too: " + saladTotal + " Thank you, Have a great day!");
if (userInput1 == 2 && userInput2 == 2)
{
System.out.println("Your bill for a salad with no additional toppings comes too: " + salad + " Thank you, Have a great day!");
if (userInput1 == 1 && userInput2 == 1)
{
saladTotal = (salad + salChe + salTom );
System.out.println("Your bill for a salad with Tomato and Cheese toppings comes too: " + saladTotal + " Thank you, Have a great day!");
}//end if 1
}//end if 2
}//end if 3
}//end if 4
}
}// end of class
In general, switch-case statements and if/else blocks are interchangeable. Switch-cases are a bit different because of the use of break (an example below). Though in most cases if-statements are used. I generally use switch-case for handling cases based on enumerations.
Lets say we have an enumeration FoodType:
public enum FoodType {
SANDWITCH,
SALAD,
FRUIT
}
So if i want to ask the user questions based on which food he chooses, I would probably do something like this:
FoodType chosenType = FoodType.SANDWITCH; // can be user input
switch (chosenType) {
case SANDWITCH:
System.out.println("you want cheese?");
case SALAD:
System.out.println("Sauce?");
break;
case FRUIT:
System.out.println("which one?");
break;
default:
throw new IllegalStateException();
}
Note here:
When SANDWITCH is chosen, questions 'you want cheese?' and 'Sauce?' are printed, because there is no break statement.
When FRUIT is chosen, only 'which one?' will be printed.
default would happen, if the user chose somthing else, which is not SANDWITCH or SALAD or FRUIT.
You could of course write this with if statements as well:
if (FoodType.SALAD.equals(chosenType)) {...}
When there are few cases I would rater use simple if statements. Also, the code inside a 'case' should not be overly long/complicated. I think if you want to know when to use which statement; there are for sure some very good blog posts or stackoverflow answers.
// Sidenote: I am aware that the default: is not be reachable code in the example.

variable doesn't increase when code is executed

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.

Using multiple if else statements and why they loop?

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?");

Why isn't my program able to read the text file after the encountering the first error message?

import java.util.*; // needed for scanner
import java.io.*; // needed to read text file
public class MainC
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); // scanner is established
System.out.println("Welcome to the Tourist Site Simulator. In this program, we will allow you to simulate a European experience by traveling to a country in Europe"
+ "and staying there for a set number of days. "); // general explanation
int count = 0, time = 10; // for possible repetition of instructions
try {
BufferedReader file = new BufferedReader(new FileReader("Countries.txt"));
while(count == 0){
System.out.println("First of all, which of the fifty sovereign states of Europe would you like to visit?");
String country = scan.next();
while (file.ready()){
String countryF = file.readLine();
String cityF1 = file.readLine();
String cityF2 = file.readLine();
String cityF3 = file.readLine();
String squiq = file.readLine();
if(countryF.equalsIgnoreCase(country)){
count++;
int count2 = 0;
while(count2 == 0){
country = country.substring(0,1).toUpperCase() + country.substring(1);
System.out.println("Country: " + country);
System.out.println("");
System.out.println("The largest cities at this nation are " + cityF1 + ", " + cityF2 + ", " +cityF3 + ". Which one would you like to visit?");
String city = scan.next();
if(cityF1.equalsIgnoreCase(city)||cityF2.equalsIgnoreCase(city)||cityF3.equalsIgnoreCase(city)){
count2++;
city = city.substring(0,1).toUpperCase() + city.substring(1);
System.out.println("");
System.out.println("Country: " + country);
System.out.println("City: " + city);
System.out.println("");
System.out.println("How many days will you be staying?");
int days = scan.nextInt();
System.out.println("");
System.out.println("Country: " + country + " Number of Days Left: " + days);
System.out.println("City: " + city);
System.out.println("");
System.out.println("What is the your rate of currency exchange to one Euro?");
double rate = scan.nextDouble();
}else{
System.out.println("I must regretfully inform you that this city is not in our listed database. Please try again.");
System.out.println("");
}
}//while count == 2
}//while file.ready()
}//while count == 0
if(count == 0)
{
System.out.println("I must regretfully inform you that this country in not in our listed database. Please try again.");
System.out.println("");
}
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
Hi there. I was having problems with this code. What it should be doing is that if the user enters an incorrect country, a loop will be initiated and the user will be asked for the country again. My problem is that after this error message comes up and the user is asked for the country again, it repeatedly asks the question regardless of whether the input is correct or not. Thank you.
I think it may be because you have your
if(countryF.equalsIgnoreCase(country))
and then from what I can see is the if statement after that is this
if(count == 0)
So your count never gets to increment if it is the wrong country.
try this instead
if(countryF.equalsIgnoreCase(country){
}else(instead of if count == 0){
"print wrong country try again"
}
You don't really need this either
while(count ==0)
try putting a second scan catcher in the else statement.
if(countryF.equalsIgnoreCase(country){
}else(instead of if count == 0){
"print wrong country try again"
country = scan.next();
}

Categories