I want it to ask the user for an input again if he misspells "im sad" and go through the whole switch process.
When I type "imsed" it says "I don't understand" as it's supposed to and asks for another input but when I type in the other input, it just ends.
I can't use arrays yet.
do {
if (a.contains("sad")) {
System.out.println("bot: " + "Hey there! Dont be sad, Here is a pun to cheer you up");
System.out.println();
i = 1 + dice.nextInt(3);
switch (i) { // start of switch
case 1:
System.out.println("Why did the traffic light felt embarrased?\n"
+ "Because everyone saw it changing");
a = input.nextLine();
break;
case 2:
System.out.println("Why was Cinderella thrown off the basketball team?"
+ "\nShe ran away from the ball.");
a = input.nextLine();
break;
case 3:
System.out.println("Why is Peter Pan always flying?\n"
+ "He neverlands.");
a = input.nextLine();
break;
} //end of switch
} else if (a.contains("again")) {
e = 1 + dice.nextInt(3);
switch (e) { // start of switch
case 1:
System.out.println("How do you know it's an emotional wedding?\n" + "When the cake is in tiers");
a = input.nextLine();
break;
case 2:
System.out.println("What does a house wear?" + "\nA Dress.");
a = input.nextLine();
break;
case 3:
System.out.println("How do you know a frenchmen plays video games?\n" + "He says wii when you ask him.");
a = input.nextLine();
break;
} //end of switch
}
} while (a.equals("again")
if (a.contains("im happy")) {
System.out.println("bot: " + "Have a great day ahead!");
}
if (!a.equals("im sad")
|| !a.equals("im happy"
|| !a.equals("again")) {
System.out.println("bot: " + "I don't understand");
a = input.nextLine();
}
Related
The prompt is:
Convert the following if-else-if statement into a switch statement. Don’t rewrite the constants or variable definitions, just the if statement.
final char BLT = 'b';
final char VEGAN = 'v';
final char TUNA = 't';
final char ROAST_BEEF = 'r';
double price;
int sandwichType;
System.out.println("Enter sandwich type: ");
sandwichType = keyboard.nextLine().charAt(0);
if (sandwichType == VEGAN || sandwichType == TUNA) {
price = 3.99;
} else if (sandwichType == BLT) {
price = 4.19;
} else if (sandwichType == ROAST_BEEF) {
price = 4.99;
} else {
System.out.println("That's not a valid sandwich type.");
System.exit(0); // This ends the program
}
System.out.println("Your total is is $" + (price*1.0825));
My current code is this:
switch (sandwichType) {
case 1:System.out.println("The price is $" + (3.99*1.0825));
case 2: System.out.println("The price is $" + (4.19*1.0825));
case 3: System.out.println("The price is $" + (4.99*1.0825));
break;
You are forgetting breaks in between the switch cases. You also will want to use the char names of the different sandwiches instead of numbers. Finally, if none of the cases match the given sandwhichType, you'll want to have a default case, this would be essentially be your else statement from the previous code. The one tricky piece is the first case which accepts two different types which can be done by having a case followed by another case.
switch (sandwhichType)
{
case VEGAN:
case TUNA:
price = 3.99;
break;
case BLT:
price = 4.19;
break;
case ROAST_BEEF:
price = 4.99;
break;
default:
System.out.println("That's not a valid sandwich type.");
System.exit(0);
break;
}
System.out.println("Your total is is $" + (price*1.0825));
The cases should be options
case BLT:
You also need a default case
default:
break;
And break; after every case.
I have looked around and haven't found any questions that has been directly answered for my problem, if i'm wrong, sorry. I'm writing a program that is supposed to take in your birth information, year, month, day, hour, minute and then ask if they would like to do it again but using a method and loop until a Y/N is entered.
My problem is im not able to get the method to take in the Y/N and end the program, as well as end when a N is entered.
I think there is supposed a while or some sort of loop that needs to be in the method but im having a hard time figuring that out.
All my other methods work except for this one, any help would be appreciated, thanks.
This is the code I have for my method now:
public static boolean getYNConfirm(Scanner pipe, String prompt)
{
String choice="";
System.out.println(prompt);
choice = pipe.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
return true;
}
else
{
return false;
}
}
And this is the code for my main program:
public static void main(String[] args)
{
int year, month, day, hour, minutes;
String msg="";
boolean done = false;
Scanner in = new Scanner(System.in);
while(!done)
{
year = SafeInput.getIntInRange(in, "Enter the year you were born: ", 1965, 2000);
month = SafeInput.getIntInRange(in, "Enter your month of birth: ", 1, 12);
switch (month)
{
case 1:
msg = "January";
break;
case 2:
msg = "February";
break;
case 3:
msg = "March";
break;
case 4:
msg = "April";
break;
case 5:
msg = "May";
break;
case 6:
msg = "June";
break;
case 7:
msg = "July";
break;
case 8:
msg = "August";
break;
case 9:
msg = "Septemeber";
break;
case 10:
msg = "October";
break;
case 11:
msg = "November";
break;
case 12:
msg = "December";
break;
}
hour = SafeInput.getIntInRange(in, "Enter the hour you were born in: ", 1, 24);
minutes = SafeInput.getIntInRange(in, "Enter the minutes you were born: ", 1, 59);
System.out.println("You were born: " + year + " , " + msg + " , " + hour + " hr. " + minutes + " mins. ");
SafeInput.getYNConfirm(in, "Would you like to play again?");
}
}
}
Thanks for any help.
Value of done is always false. Change on last line:
done = SafeInput.getYNConfirm(in, "Would you like to play again?");
EDIT:
Your logic does not fit if you return true Change here too:
if(choice.equalsIgnoreCase("Y"))
{
return false;
}
else
{
return true;
}
you need to change the value of done base on the return of the getYNConfirm method. So the last line should be
done = SafeInput.getYNConfirm(in, "Would you like to play again?");
I'm trying to get the user to give input and then after everything from all the cases was read out to them, re-loop to the output.displayMainMenu(); until they were to enter 4 to exit the program.
output.displayMainMenu();
int entry = keyboard.nextInt();
while(entry >= 1 || entry <=4) {
output.displayMainMenu();
switch(entry) {
case 1:
output.displayStockChoices(portfolio);
portfolio.editPostion();
portfolio.displayPositions();
break;
case 2:
portfolio.updateCurrentPrice();
break;
case 3:
System.out.print(investor.toString() + "Account Balance: " +portfolio.calcTotalAccountValue());
break;
case 4:
System.out.print("Done.");
break;
default:
System.out.print("please enter 1-4!");
}
break;
}
It's better to use a do-while loop because the code inside the loop need to be ran at least one time. I agree with #AntonH, that are several issues in this code. I rewrote it considering the mentioned issues.
int entry = 0;
do {
output.displayMainMenu();
try {
entry = keyboard.nextInt();
} catch (InputMismatchException e) {
System.out.print("Invalid input. ");
}
switch (entry) {
case 1:
output.displayStockChoices(portfolio);
portfolio.editPosition();
portfolio.displayPositions();
break;
case 2:
portfolio.updateCurrentPrice();
break;
case 3:
System.out.print(investor.toString() + "Account Balance: "
+ portfolio.calcTotalAccountValue());
break;
case 4:
System.out.print("Done.");
break;
default:
System.out.print("please enter 1-4!");
}
} while (entry >= 1 && entry < 4);
// Don't forget to close Scanner object when program finish
keyboard.close();
I've spent hours on this program trying to figure out how to repeat the main menu to show until the user write 3 (to quit the program).
The program asks the user to enter 2 integer numbers, then Main menu shows to choose from 3 options.
I chose the do while loop to force it show at least once, but i don't know what's my mistake?
package javaapplication33;
import static java.lang.System.exit;
import java.util.Scanner;
public class JavaApplication33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers: ");
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn = showMenu();
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
}
public static int showMenu() {
int optionn = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("--------------");
System.out.println("1.Add the numbers");
System.out.println("2.Multiply the numbers");
System.out.println("3.Quit");
System.out.println("--------------");
System.out.println("Enter your choice:");
optionn = keyboard.nextInt();
return optionn;
}
You could consider just a while loop, instead of a do-while.
int optionn = 0;
while (optionn != 3)
{
optionn = showMenu();
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}
}
Additionally, there's no reason to clear out your optionn variable in your showMenu method.
try this
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
int optionn = showMenu();//SHOWS THE MENU AGAIN
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
Your showmenu() method isnt in your while that why i dosent repeat
The two lines of code that needed fixing - have comments, see below:
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}// End of switch statement
optionn = showMenu(); // <--- changed
} while (optionn != 3); // <--- changed
A couple of mistakes.
First you should be getting the user input inside the do/while loop. Just move your optionn=showMenu() inside the do (That way you can show the options again and allow the user to choose again).
Second you want to keep on looping while optionn!=3 instead of optionn==3 (You want to continue looping if the user doesn't want to exit).
I would also not use exit(0) and also move your exit print statement to inside the loop (So you print it before you exit your function). Something like this:
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn;
do {
optionn = showMenu(); //Allow user to select from menu every iteration
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
System.out.println("Thank you. Good Bye."); //Moved from the bottom
return; //I would use return instead of the exit(0) here.
//exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn != 3); //Make sure this is != not ==
Hope this helps!
Alrighty so, I'm supposed to make a quiz that consists of 5 questions with 4 possible answers. The user then will answer the questions via keyboard input. At the end if they have 5 out of 5 the program should outprint, "excellent" at 4 it should output "Very Good" and at 3 or less is should outprint "Time to brush up on your knowledge of global warming" along with a link to the site with information used to create the questions. included in the coding must be, "Do-While", and "Switch" Statements. I think its almost there but I keep getting errors and I'm really having a hard time figuring out what to do next! Help a lady out?
Edit Here are my received errors:
"Multiple markers at this line
- chosenAnswer1 cannot be resolved
- chosenAnswer1 cannot be resolved to a
variable
- answer1string cannot be resolved to a
variable"**
(My code is below)
import java.io.* ;
public class globalwarming {
public static void main(String[] args) {
InputStreamReader keyInput = new InputStreamReader(System.in) ;
BufferedReader read = new BufferedReader(keyInput) ;
try {
System.out.println("1. Carbon Dioxide (CO2)_____________;");
System.out.println("A. Is colorless, odorless, non-toxic, and non-combustible.");
System.out.println("B. Is produced when Carbon sources are burned (i.e. oil, coal, gas, wood…)");
System.out.println("C. Atmospheric concentration has increased by over 34% since 1960.");
System.out.println("D. All of the above");
String chosenAnswer1 = read.readLine();
int answer1 = 4;
String answer1string = "" + answer1;
String Question1answers;
switch (answer1) {
case 1: Question1answers = "A. Is colorless, odorless, non-toxic, and non-combustible.";
break;
case 2: Question1answers = "B. Is produced when Carbon sources are burned (i.e. oil, coal, gas, wood…)";
break;
case 3: Question1answers = "C. Atmospheric concentration has increased by over 34% since 1960.";
break;
case 4: Question1answers = "D. All of the above";
break;
default: Question1answers = "No response selected";
break;
}
System.out.println("2. Greenhouse gases are; ");
System.out.println("A. A myth created by popular media.");
System.out.println("B. Keep heat close to earth sustaining life, however is rapidly increasing heat levels, which is detrimental to the environment.");
System.out.println("C. Green colored gases that poison and kill plant life.");
System.out.println("D. Nothing to be concerned about, continue buying and consuming products that release CO2 emissions… Nothing to see here.");
String chosenAnswer2 = read.readLine();
int answer2 = 2;
String answer2string = "" + answer2;
String Question2answers;
switch (answer2) {
case 1: Question2answers = "A. A myth created by popular media.";
break;
case 2: Question2answers = "B. Keep heat close to earth sustaining life, however is rapidly increasing heat levels, which is detrimental to the environment.";
break;
case 3: Question2answers = "C. Green colored gases that poison and kill plant life.";
break;
case 4: Question2answers = "D. Nothing to be concerned about, continue buying and consuming products that release CO2 emissions… Nothing to see here.";
break;
default: Question2answers = "No response selected";
break;
}
System.out.println("3. Smart Cars help combat global warming by,");
System.out.println("A. Reducing CO2 emissions slowing the rapid warming of the planets atmosphere.");
System.out.println("B. Consuming more energy thereby eliminating oil supplies.");
System.out.println("C. Require fewer resources to manufacture.");
System.out.println("D. None of the above.");
String chosenAnswer3 = read.readLine();
int answer3 = 1;
String answer3string = "" + answer3;
String Question3answers;
switch (answer3) {
case 1: Question3answers = "A. Reducing CO2 emissions slowing the rapid warming of the planets atmosphere.";
break;
case 2: Question3answers = "B. Consuming more energy thereby eliminating oil supplies.";
break;
case 3: Question3answers = "C. Require fewer resources to manufacture.";
break;
case 4: Question3answers = "D. None of the above.";
break;
default: Question3answers = "No response selected";
break;
}
System.out.println("4. There is more carbon dioxide in the air today than;");
System.out.println("A. There ever has been before.");
System.out.println("B. Than at any other time in the last 800,000 years.");
System.out.println("C. Than there will be in 20 years.");
System.out.println("D. Both A and B.");
String chosenAnswer4 = read.readLine();
int answer4 = 2;
String answer4string = "" + answer4;
String Question4answers;
switch (answer4) {
case 1: Question4answers = "A. There ever has been before.";
break;
case 2: Question4answers = "B. Than at any other time in the last 800,000 years.";
break;
case 3: Question4answers = "C. Than there will be in 20 years.";
break;
case 4: Question4answers = "D. Both A and B.";
break;
default: Question4answers = "No response selected";
break;
}
System.out.println("5. In the last century sea levels have risen how many inches?");
System.out.println("A. 5 Inches");
System.out.println("B. 0 Inches");
System.out.println("C. 7 Inches");
System.out.println("D. 22 Inches");
String chosenAnswer5 = read.readLine();
int answer5 = 3;
String answer5string = "" + answer5;
String Question5answers;
switch (answer5) {
case 1: Question5answers = "A. 5 Inches";
break;
case 2: Question5answers = "B. 0 Inches";
break;
case 3: Question5answers = "C. 7 Inches";
break;
case 4: Question5answers = "D. 22 Inches";
break;
default: Question5answers = "No response selected";
break;
}
}
int i = 5;
String strI = "" + i;
int count = 0;
do {
if (chosenAnswer1 == answer1string) {
count++;
}
if (chosenAnswer2 == answer2) {
count++;
}
if (chosenAnswer3 == answer3) {
count++;
}
if (chosenAnswer4 == answer4) {
count++;
}
if (chosenAnswer5 == answer5) {
count++;
}
} while (count <= 5);
if (count == 5) {
System.out.println("Excellent!");
} else if (count == 4) {
System.out.println("Very good!");
} else if (count > 3) {
System.out.println("Time to brush up on your knowledge of global warming.");
System.out.println("http://www.dosomething.org/actnow/tipsandtools/11-facts-about-global-warming");
}
/*
System.out.println(Question1answers);
System.out.println(Question2answers);
System.out.println(Question3answers);
System.out.println(Question4answers);
System.out.println(Question5answers);
*/
}
}
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Cases does not mean order in your menu, they are like "IF the given variable equals THIS case value"
switch (STRING) {
case STRING_A: do something.. break;
case STRING_B: do something.. break;
}
switch (INTEGER) {
case 1: do something.. break;
case 2: do something.. break;
}
This variable is defined in a try context. It cannot be used outside the try.
String chosenAnswer1 = read.readLine();
You will have to do something like:
String chosenAnswer1 = null;
try {
...
chosenAnswer1 = read.readLine();
The same for all other chosenAnswers and answer1strings
Your try is missing the catch/finally, otherwise why would you use a try?
http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
read.readLine(); These lines need to be wrapped by try catch OR the method should allow the exception throw.
Strings are immutable, therefore stringA==stringB does not evaluate if the strings are the same, it will evaluate if the two strings are the same Object....
String a = "hello";
String b = "hello";
//a==b is false.
//a.equals(b) is true
String a = "hello";
String b = a;
//a==b is true.
//a.equals(b) is true
your use of == for strings incorrect. Strings should be checked for equality using .equals() For example, this line, and all others below it:
if (chosenAnswer1 == answer1string) {
This should be
if (chosenAnswer1.equals(answer1string)) {