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));
}
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 my program figured out so far, it's just that I'm not understanding these instructions I was given (or at least understanding how to do them).
When I type 10, it prints out "10 of", but when I try to type 10S for 10 of Spades, it only prints out "Spades."
Hopefully, someone here can give me either a solution or point me in the right direction on how to solve my problem:
Use a SWITCH statement to assign the result variable an initial value - the value of the card
Use a second SWITCH statement to concatenate to the result variable the card's suit"
here is the code:
import java.util.*;
public class CardConverter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//will hold string that user will input
String card, face, suit, result;
//getting input from user and telling them correct format
System.out.println("Please enter either the number or face value intial of a card followed by the initial of it's suit (ie. QH for Queen of Hearts)");
card = keyboard.nextLine();
//gets first value
face = card.substring(0);
//sets substring for 10 only
//substring for after all single digit/letter card faces
suit = card.substring(1);
//to print face and word of
switch (face)
{
case "10":
System.out.println("10 of ");
break;
case "2":
System.out.println("2 of ");
break;
case "3":
System.out.println("3 of ");
break;
case "4":
System.out.println("4 of ");
break;
case "5":
System.out.println("5 of ");
break;
case "6":
System.out.println("6 of ");
break;
case "7":
System.out.println("7 of ");
break;
case "8":
System.out.println("8 of ");
break;
case "9":
System.out.println("9 of ");
break;
case "J":
System.out.println("Jack of ");
break;
case "Q":
System.out.println("Queen of ");
break;
case "K":
System.out.println("King of ");
break;
case "A":
System.out.println("Ace of ");
break;
}
//to print out card suit
switch (suit)
{
case "H":
System.out.println("Hearts");
break;
case "C":
System.out.println("Clubs");
break;
case "S":
System.out.println("Spades");
break;
case "D":
System.out.println("Diamonds");
break;
}
}
}
Your problem starts at card.substring(0);, which equals card because the substring from the start of the String. Maybe you wanted card.charAt(0);? But that is also wrong because "10S" will have three characters, two for the face value.
You'll need to handle a three-character input specially or be smarter about the substring-ing.
You know the suit will always be the last character, so use the length of the string to charAt for that.
int suitIndex = s.length() - 1;
String suit = ""+s.charAt(suitIndex);
String face = s.substring(0,suitIndex);
You can also simplify the cases
case "J":
System.out.println("Jack of ");
break;
case "Q":
System.out.println("Queen of ");
break;
case "K":
System.out.println("King of ");
break;
case "A":
System.out.println("Ace of ");
break;
default:
System.out.println(face + " of "); // handle all the numbers
break;
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.
This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 7 years ago.
To practice using if else, do while, and switch statements, I was making a small text adventure game where a user would be able to input their name, gain a randomly generated profession, and be assigned a randomly generated quest. however, halfway though the second goal, the java development program I was using continually said that one of my variables "might not have been initialized".
This is what i have for the code so far:
============
import java.util.*;
public class Adventure1
{
public static void main(String[] args)
{
//initialize variables
Scanner keyboard = new Scanner(System.in);
Scanner keyboardYN = new Scanner(System.in);
Scanner keyboard2YN = new Scanner(System.in);
String name = "";
char userInput;
char userYN;
char user2YN;
int dieRoll = (int) (Math.random() * 9);
char outputType;
char Mage;
char Soldier;
char Explorer;
char howTo;
//exeternal documation
System.out.println("The First Adventure by K. Konieczny ");
System.out.println();
//player name
do
{
System.out.println();
System.out.print("What is your name: ");
name = keyboard.nextLine();
//prompt
System.out.print("So your name is " + name + "? Are you sure y/n : ");
userYN = keyboardYN.nextLine().charAt(0);
System.out.println();
if(userYN == 'y')
{
System.out.println();
}
else
{
System.out.println("Type in your real name.");
}
}//end do
while(userYN == 'n');
//narration pt. 1
System.out.println("You, " + name +
" have just been named the greatest, uh, what was it again?");
System.out.println();
//specialization
System.out.print("Roll the dice to decide what your profession is? y/n : ");
user2YN = keyboard2YN.nextLine().charAt(0);
if(user2YN == 'y')
{
switch (dieRoll)
{
case '0':
case '1':
case '2': outputType = Mage;
case '3':
case '4':
case '5': outputType = Soldier;
case '6':
case '7':
case '8': outputType = Explorer;
default : outputType = howTo;
}//end switch
System.out.println("Oh right, you are the greatest " + outputType + " in the town.");
}
else
{
System.out.println("I must be thinking of someone else then.");
}
//get quest
System.out.println();
System.out.println("End of program");
}//end main
}//end class
============
The error message i get reads "variable Mage might not have been initialized."
I don't have much coding experience, and was wondering what I did wrong and how I could fix it in future programs.
You have:
char Mage;
// ...
case '2': outputType = Mage;
What is the value of Mage at that point? The compiler is warning you that the variable has not been initialized.
You might want to initialize Mage to some value such as:
char Mage = '0';
Or most likely you want a String representation of Mage:
String outputType;
String mage = "Mage";
String soldier = "Soldier";
String explorer = "Explorer";
// ...
switch (dieRoll) {
case '0':
case '1':
case '2': outputType = mage;
break;
case '3':
case '4':
case '5': outputType = soldier;
break;
case '6':
case '7':
case '8': outputType = explorer;
break;
default : outputType = "Oops";
}
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)) {