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)) {
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.
Okay, so I'm clearly not asking the question properly for this question. The idea is to ask a user for a number (indicating what flavor ice cream they want) associated with the flavor. Everytime I enter any number, it spits out the default. One of the issues (at least I think it is...) is the input = keyboard.nextInt();.
System.out.println(" ");
System.out.println(" What flavor of ice cream would you like? ");
System.out.println("(1) Vanilla (2) Peanut Butter (3) Chocolate (4)Chocolate Chip (5) Mint Chocolate Chip " +
" (6) Cookie Dough (7) Mint Mouse tracks (8) Coconut (9) Pinapple (10) Cotton Candy" +
"(11) Mouse Tracks (12) Oreo Cookies and Cream");
input = keyboard.nextInt();
flavorType = input.charAt(0);
switch(flavorType)
{
case 1:
order.setFlavor ("Vanilla");
break;
case 2:
order.setFlavor("Peanut-Butter");
break;
case 3:
order.setFlavor ("Chocolate");
break;
case 4:
order.setFlavor ("Chocolate Chip");
break;
case 5:
order.setFlavor ("Mint Chocolate Chip");
break;
case 6:
order.setFlavor ("Choclate Chip Cookie Dough");
break;
case 7:
order.setFlavor ("Mint Mouse Tracks");
break;
case 8:
order.setFlavor ("Coconut");
break;
case 9:
order.setFlavor ("Pinapple");
break;
case 10:
order.setFlavor ("Cotton Candy");
break;
case 11:
order.setFlavor ("Mouse Tracks");
break;
case 12:
order.setFlavor ("Oreo Cookies and Cream");
break;
default:
System.out.println(" ");
System.out.println(" Im sorry, that was not one of the choices, you will get two scoops " +
" of vanilla with whipped cream,hot fudge, rainbow sprinkles, and a cherry");
order.setFlavor ("Vanilla");
}
Now, I also have the variables declared on top as such
String customerName;
double cost;
double toppingCost = 1.25;
int numberOfScoops;
int numberOfDeluxe = 0;
int numberOfToppings = 0;
//String flavor;
String toppingList;
final double TAX_RATE = .08625;
double tax;
char choice;
char flavorType;
String input;
String toppings = " Whipped cream, syrup, and sprinkles ( Chocolate or rainbow)";
int toppingChoice;
I also have in the driver program...
public void setFlavor (String type)
{
flavor = type;
}
This is only part of the assignment. The rest of it involves scoops, toppings, etc etc. This part however is the issue, unable to get the switch statement right.
Assuming you declared:
Scanner keyboard = new Scanner(System.in);
and order is defined properly as well. As I wrote in the comments - you read input as int but you treat it as String when you try calling: input.charAt.
Further, you can simplify the code by using a Map both to figure out the choice (instead of case-switch) as well as displaying the options.
The following code will work with Java 9:
Map<Integer, String> dict = new TreeMap(Map.of(1, "Vanilla",
2, "Peanut-Butter",
3, "Chocolate",
4, "Chocolate Chip",
5, "Mint Chocolate Chip",
6, "Choclate Chip Cookie Dough",
7, "Mint Mouse Tracks",
8, "Coconut",
9, "Pinapple",
10, "Cotton Candy"));
// Map.of API allows up to 10 items - so we'll need to add the other two manually.
// That's also the reason that we're copying the Map.of by doing:
// new TreeMap(Map.of(...)) - since `Map.of` returns an immutable Map which we cannot modify
dict.put(11, "Mouse Tracks");
dict.put(12, "Oreo Cookies and Cream");
System.out.println("\n What flavor of ice cream would you like? ");
dict.forEach((k, v) -> System.out.println(String.format("(%d) %s", k, v)));
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
if (null == dict.get(input)) {
System.out.println(" Im sorry, that was not one of the choices, you will get two scoops " +
" of vanilla with whipped cream,hot fudge, rainbow sprinkles, and a cherry");
order.setFlavor ("Vanilla");
} else {
order.setFlavor (dict.get(input));
}
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 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();
}
So here is a link to another persons question and its my exact assignment.
https://stackoverflow.com/questions/39834840/concatenating-switch-statements-for-playing-cards-assignment
How can I get my result string to display the valueofCard then the suitofCard in this format "value of suit"
Also, how can I shorten up the 2-10 value range within a switch case?
I am aware I have " of " and a couple other lines that make no sense, I just figured I am missing something big anyways.
Thanks for any help, have lots of catching up to do.
System.out.print("Please enter a letter/integer of a playing card (A, J, Q, K, or 2 - 10),\nfollowed by card type (D, H, S, C):");
Scanner kbd = new Scanner(System.in);
String userInput = kbd.nextLine();
String valueofCard = userInput.substring(0, userInput.length() / 2); // gives first half of string
String suitofCard = userInput.substring(userInput.length() / 2); //give last half of string with + 1 if odd
StringBuilder result = new StringBuilder();
switch (valueofCard) {
case "A":
result.append("Ace of ");
break;
case "J":
result.append("Jack of ");
break;
case "Q":
result.append("Queen of ");
break;
case "K":
result.append("King of ");
break;
case "2":
result.append("2 of ");
case "3":
result.append("3 of ");
case "4":
result.append("4 of ");
case "5":
result.append("5 of ");
case "6":
result.append("6 of ");
case "7":
result.append("7 of ");
case "8":
result.append("8 of ");
case "9":
result.append("9 of ");
case "10":
result.append("10 of ");
break;
}
switch (suitofCard) {
case "D":
result.append("Diamonds");
break;
case "H":
result.append("Hearts");
break;
case "S":
result.append("Spades");
break;
case "C":
result.append("Clubs");
break;
}
System.out.println(result.toString());
kbd.close();
}
}
Option 1 - You could use a Stringbuilder to do this.
StringBuilder cardAndSuit = new StringBuilder();
switch (valueofCard) {
case "A":
cardAndSuit.append("Ace of");
.....
switch (suitofCard) {
case "D":
cardAndSuit.append("Diamonds");
break;
...
// Print the final string
System.out.println(cardAndSuit.toString()); // Ace of Diamonds
Option 2 - You could also just create a regular String and append to it.
String cardAndSuit = '';
cardAndSuit += "Ace of";
cardAndSuit += " Diamonds";
System.out.println(cardAndSuit); // Ace of Diamonds
2 is probably easier and more terse. Option 2 will actually be turned into option 1 by the compiler behind the scenes.