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";
}
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.
For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated.
import java.io.*;
import java.util.*;
public class Prog213c
{
public static void main(String[] args) {
Scanner kbReader=new Scanner(System.in);
do{
System.out.println( "Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits)
{
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default: System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
String answer = kbReader.next();
} while (answer == 'y'); // error received here
You have a few problems here:
String answer = kbReader.next();
} while (answer == 'y'); // error received here
Technically, answer is out of scope when you try to use - you can only use answer inside the loop itself. You should declare answer prior to starting your while loop so that it's in scope. Also, answer is a string and you're trying to "directly" compare it to a char.
This is also performing a case-sensitive comparison; while this isn't technically incorrect, it would be more user-friendly to accept accept either "Y" or "y".
Also, your switch statement won't work correctly. For example, case 30 will only be called if credits is exactly 30, which I assume isn't what you want.
You could do something like:
case 30:
case 31:
case 32: // ...
but that seems like a thoroughly painful way to do that. See also this question for more details.
This answer is particularly interesting and could be useful for your purposes. This is the code from that answer:
switch ((int) num/10) {
case 1:
System.out.println("10-19");
break;
case 2:
System.out.println("20-29");
break;
case 3:
System.out.println("30-39");
break;
case 4:
System.out.println("40-49");
break;
default:
break;
}
(Again, just to give credit where credit's due the above isn't my code, it was from the linked answer).
Also:
int studentNumber = kbReader.nextInt();
You never actually do anything with studentNumber, just prompt the user for it. Did you mean to do this?
Single quotes are character literals in Java. So you can't compare a
String with a char directly.
Your answer variable has to be declared before the do-while loop.
you have to use the equals method to compare strings.
answer.equals("y")
Problem 1:
since answer is a string object, this is not working (answer == 'y');
you can do "y".equals(answer) is you get the nextLine from the scanner
or if you need to work with chars
char x = kbReader.next().charAt(0);
while (x == 'y');
Problem 2:
answer must be declared before the do-while loop...
your final code can look like
Scanner kbReader = new Scanner(System.in);
char answer = 'y';
do {
System.out.println("Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits) {
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default:
System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
answer = kbReader.next().charAt(0);
} while (answer == 'y');
Change your while condition to:
while ("y".equals(kbReader.next()));
when i try to print out the result with switch i can't get any result
so i thought to convert char to integer so the switch statement gona work but isn't so any ideas about how to find solution
echar guestGuess = input.next().charAt(0);
int x = (int)guestGuess;
switch(x){
case '1':
System.out.println(answer.isfirstGuessRight(guestGuess) + "\n");
break;
case '2:
'System.out.println("We are kontrol your answer" + answer.issecandGuessRight(guestGuess));
There's not problem in Java to use char for switch.
You don't have to cast to int for that.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter something, and I'll take the first char only");
char c = scan.next().trim().charAt(0);
switch (c) {
case '1':
System.out.println("1 for sure");
break;
case '2':
System.out.println("I think it's 2");
break;
default:
System.out.println("I don't know");
}
}
I am experiencing some problems with the output of my program. I am certain the error is logical but i just cant fix it. error should be somewhere around here
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
/*This is my utility scanner,
* I created char grade to get the user input.
*/
java.util.Scanner input=new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
I don't know how to fix it. At the moment if i insert A+ to the program it would give me the result for A-. Heres my full code.
public class SwitchCase {
public static void main(String[] args) {
System.out.println("Please enter your grade (ex.A+) to get the mark range");
/*This block of codes converts from string to
* char and it gets the plus or minus sign
*/
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
/*This is my utility scanner,
* I created char grade to get the user input.
*/
java.util.Scanner input=new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
/*This set of code contains the nested switch statements
* that i will use to output the correct mark range
* to the user. It also contains a try statement to find runtime
* errors in the program.
*/
try{
switch(grade)
{
case 'A':
switch(modifier)
{
case '+': System.out.println("Your grade is 90-99.99%"); break;
case '-': System.out.println("Your grade is 80-84.99%"); break;
default: System.out.println("Your grade is 85-89.99%"); break;
}
break;
case 'B':
switch(modifier)
{
case'+': System.out.println("Your grade is 77.00 - 79.99%"); break;
case'-': System.out.println("Your grade is 70.00 - 72.99%"); break;
default: System.out.println("Your grade is 73.00 - 76.99%"); break;
}
break;
case 'C':
switch(modifier)
{
case'+': System.out.println("Your grade range is 67.00 - 69.99%"); break;
case'-': System.out.println("Your grade range is 60.00 - 62.99%"); break;
default: System.out.println("Your grade range is 63.00 - 66.99%"); break;
}
break;
case 'D':
switch(modifier)
{
case'+': System.out.println("Your grade range is 55.00 - 59.99%"); break;
case'-': System.out.println("-"); break;
default: System.out.println("Your grade range is 50.00 - 54.99%"); break;
}
break;
case 'F':
switch(modifier)
{
default: System.out.println("Your grade range is 0.00-49.99%"); break;
}
break;
}
}
catch (java.util.InputMismatchException e) { //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid grade!");
}
input.close(); //ends the user input
}
}
After
char grade = userInputString.charAt(0);
add
char modifier = ' ';
if( userInputString.length() > 1 ){
modifier = userInputString.charAt(1);
}
and remove the code dealing with plusorminus.
You should also add some code to avoid hiccups after reading the input line.
userInputString = userInputString.trim(); // maybe user hits space?
if( ! userInputString.matches( "^[A-F][-+]?$" ) ){
// error message...
}
Not sure whether there is E, and F+ or F-?? We have different grades. Perhaps the regex should be
"^[A-E][-+]?|F$"
You might be inserting
A+
but you're only consuming the A.
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
The modifier is assigned, deterministically, here
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
The length of plusorminus will always be 2 which means that modifier will always be plusorminus.charAt(1), ie. -. You want to assign the second character of your input string as the modifier.
New to Java and I'm having troubles with my code, it's a switch statement within a while loop. I like to use letters or "char" instead of numbered cases "int" and I have 'q' to quit. Thanks for your input. This is the main code.
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
case 'f':
nastybat.feed();
break;
case 'p':
nastybat.play();
break;
case 'r':
nastybat.read();
break;
case 't':
nastybat.train();
break;
case 'q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
choice = sChoice.next().charAt(0);
}
}
}
When I enter corresponding letter the loop doesn't show Input method or repeat and 'q' does nothing. Default displays "invalid entry" before input.
Code edited and still have problems.
The input is taken only once, the first time! Therefore the loop always returns the same result. You should duplicate the getting input code inside the loop!
Scanner sChoice = new Scanner(System.in);
char choice = '';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
.
.
.
.
.
choice = sChoice.next().charAt(0);
The first line gets input for the first switch run, and the one inside the loop gets the rest.
UPDATE:
The choice = sChoice.next().charAt(0); should be place at the final of the loop, if not, as #proskor says, when user hits 'q' the program will return an 'invalid entry'.
I finished the code and it seems to work. Testing out the methods the object can use now.
Final
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c': case 'C':
nastybat.checkStats();
break;
case 'f': case 'F':
nastybat.feed();
break;
case 'p': case 'P':
nastybat.play();
break;
case 'r': case 'R':
nastybat.read();
break;
case 't': case 'T':
nastybat.train();
break;
case 'q': case 'Q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
choice = sChoice.next().charAt(0);
}
}
}