Conditional wont be read in do while statement - java

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

Related

Initializing a non-numeric variable in Java [duplicate]

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

Simple switch in "for" loop and toLowerCase() method

I am very much a beginner in Java. I am making a simple switch, in which the user is entering a number in words. For training I added a "for" loop.
package JavaExc;
import java.util.Scanner;
public class JavaStart {
public static void main(String[] args) {
Scanner sck = new Scanner(System.in);
System.out.println("Type loop counter ");
int counter = sck.nextInt();
System.out.println("Counter is: " + counter );
for (int i = 0; i <= counter; i++) {
System.out.println("Type number in words");
String ch = sck.nextLine();
switch (ch.toLowerCase()) {
case "one":
System.out.println("CHOICE 1");
break;
case "Two":
System.out.println("CHOICE 2");
break;
case "THREE":
System.out.println("CHOICE 3");
break;
case "FoUr":
System.out.println("CHOICE 4");
break;
case "fiVE":
System.out.println("CHOICE 5");
break;
default:
System.out.println("Wrong Data");
break;
}
System.out.println("Loops left:\n " + counter--);
}
System.out.println("End of Switch");
}
}
Here is the result:
Type loop counter
5
Counter is: 5
Type number in words
Wrong Data // ??
Loops left:
5
Type number in words
one
CHOICE 1
Loops left:
4
Type number in words
three // Should be ok, so what is wrong here?
Wrong Data
Loops left:
3
End of Switch //To early break loop I think
Process finished with exit code 0
My questions are: Why first loop make default code? Should I make 2 Scanners? One for take value for counter and second for switch?
Why counter and numbers in words do not working properly?
I know I can do it with tables etc. but generally, the purpose of this program is to test the "toLowerCase()" method.
You're checking your string in lower case ("three") against upper case ("THREE"). Make sure they're both identical and it shouldn't fail.
Switch statement
In your switch clause, you are testing a String that has been turned into a lowercase form of itself. Therefore, the only possible case clause that will be matched is "one", as the others all contain uppercase characters.
Change all of the case clauses to lowercase and it will work, as long as you input the data correctly.
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;
Not accepting input
Regarding your problem with the program not accepting input, you have to call sck.nextLine() after calling sck.nextInt(), see here for details on why this is.
Only one scanner is necessary.
The convention of a switch statement is similar to an if-else if-else chain. The value placed between the switch statement's parenthesizes is evaluated against every case present in the switch statement.
A switch statement of:
String condition = "foo";
switch(condition){
case "example":{
}
case "foo":{
}
case "bar":{
}
default:{
}
}
is similar to the expression:
if(condition.equals("example")){
}else if(condition.equals("foo")){
}else if(condition.equals("bar")){
}else{
}
Note that by making your input into the switch statement lowercase, it will never match any case that is uppercase.
e.g:
if("tHREE".toLowerCase().equals("tHREE")){
will never evaluate true, since "tHREE" is first being dropped to all lowercase "three" before performing a case-sensitive comparison to "tHREE".
Why first loop make default code?
As explained in Skipping nextLine() after use next(), nextInt() or other nextFoo() methods, nextInt doesn't consume the newline character. Add a call to sck.nextLine(); after setting counter.
Should I make 2 Scanners? One for take value for counter and second for switch?
No, only one Scanner is necessary.
Why counter and numbers in words do not working properly?
First, your for loop condition is i <= counter, which means that it's set up to run counter + 1 times. Change it to i < counter.
Second, your switch cases except for "one" contain capital letters, so they will never match ch.toLowerCase(). Change your case labels to strings with all lowercase letters.
Third, you decrement counter at the end of the for loop, cutting down on the number of iterations run. Instead, use the expression (counter - i - 1) to output the number of loops left.
retype the cases to:
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;
Ok i added changes and it works fine. Now I will try to make possibilty to input words whatever they are upper or lower cases. Thanks for help! StackOverflow rocks so much!
package JavaExc;
import java.util.Scanner;
public class JavaStart {
public static void main(String[] args) {
Scanner sck = new Scanner(System.in);
System.out.println("Type loop counter ");
int counter = sck.nextInt();
sck.nextLine();
System.out.println("Counter is: " + counter );
int i;
for ( i = 0; i < counter; i++) {
System.out.println("Type number in words");
String ch = sck.nextLine();
switch (ch.toLowerCase()) {
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;
default:
System.out.println("Wrong Data");
break;
}
System.out.println("Loops left:\n " + (counter - i - 1) );
}
System.out.println("End of Switch");
}}

switch loops? while loops? currency converter program java

I am new to switch loops and am having multiple problems with this currency converter program I am trying to create.
First, I would like to loop the case 1 where the user keeps entering values until they type -1 so it stops and moves on. At the moment, it does not do this. Once I've entered the GPR values on switch 1 and then loop back to the menu keeping the original GPR stored values.
Code is here:
import java.util.Scanner;
public class Conversion {
public static void main(String[] args) {
double pound;
double euro;
double dollars;
double yen;
double rupees;
double poundEuro;
double poundDollars;
double poundYen;
double poundRupees;
int Choice;
Scanner input = new Scanner(System.in);
Scanner exchange = new Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros (1GBP = 1.28EUR)");
System.out.println("3. Dollars (1GBP = 1.51USD)");
System.out.println("4. Yen (1GBP = 179.80JPY)");
System.out.println("5. Rupees (1GBP = 95.60INR)");
System.out.println("6. Exit");
Choice = input.nextInt();
switch (Choice) {
case 1:
while (!exchange.equals("-1"));{
pound = exchange.nextDouble();
System.out.print("Please enter your values you would like to exchange (Type '-1' to stop) ");
}
case 2:
pound = exchange.nextDouble();
dollars = 1.51;
poundDollars = pound * dollars;
System.out.println("Your amounts in euros are" + poundDollars);
case 3:
pound = exchange.nextDouble();
yen = 1.28;
poundYen = pound * yen;
System.out.println("Your amounts in euros are" + poundYen);
case 4:
pound = exchange.nextDouble();
rupees = 1.28;
poundRupees = pound * rupees;
System.out.println("Your amounts in euros are" + poundRupees);
case 5:
pound = exchange.nextDouble();
euro = 1.28;
poundEuro = pound * euro;
System.out.println("Your amounts in euros are" + poundEuro);
case 6:
break;
}
input.close();
exchange.close();
}
}
switch is not a loop. It's a branching statement like if. It has break, but that is only present because you can "fall through" to the next case statements. Currently you are falling through on most of them, because you've forgot putting in the break statements between the cases.
A switch statement isn't a loop. Consider it a replacement for a series of else-if statements. Your code actually reads more like this:
if(Choice == 1)
{
}
else if(Choice == 2)
{
}
else if(Choice == 3)
{
}
else if(Choice == 4)
{
}
else if(Choice == 5)
{
}
else if(Choice == 5)
{
}
However, your switch cases should be terminated with break statements. If one is not, unlike the else-ifs above, execution will fall-through to the next case and execute the code in that one too, until it finally reaches a break statement or goes through all the cases.
What you want is for your while-loop to wrap AROUND your switch statement, but you should fix your while-loop first, since you terminated it with a semicolon, it is infinite. While-loops don't need a semicolon at the end, unless you do not have a body for it but you do have some side-effect happening in the conditional check that will eventually cause it to end.
while( blah )
{
switch( blah )
{
case 1:
// Do stuff for this case
break;
case 2:
// Do stuff for this case
break;
default:
// Do stuff when no case is matched
break;
}
}
I think you're a bit confused. As noted by immibis in his comment, switch statements are not loops, so you need to enclose the switch statement inside a loop.
Then, you're missing the break statements at the end of each case. Quoting the Java tutorials:
Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
Your program should be something like this:
public static void main(String[] args) {
// Variable definitions
while(true) { // This is a little trick to force the application to repeat
// a task until you explicitly break the loop
// Code to print your menu
choice = input.nextInt();
if(choice == -1 || choice == 6)
break; // Break the while loop if choice is -1 or 6
switch(choice){
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
If you don't put those break statements at the end of each case block, your program will fall through every option.
Please read:
The Java tutorials: The switch statement
The Java tutorials: The while statement
Another option would be something like this:
public static void main(String[] args) {
// Variable definitions
/*
Now let's use a labeled loop
*/
menu: while(true) {
// Code to print your menu
choice = input.nextInt();
switch(choice){
case -1: // Nothing goes here, so the execution will fall through
// to the next case
case 6:
break menu; // This will break the menu loop.
// Since the previous case simply falls through to
// this one, this will happen if choice is
// either -1 or 6
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
More reading:
The Java tutorials: Branching statements

When I run my program i get the error java.lang.StringIndexOutOfBoundsException: String index out of range: 0

here is my code
import java.io.*;
import java.util.*;
public class weightOnOtherPlanets {
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
System.out.println("choose a planet by entering the corresponging letter\n");
System.out.println("A. Voltar");
System.out.println("B. Krypton");
System.out.println("C. Fertos");
System.out.println("D Servantos");
String choice = kbReader.nextLine( );
char p = choice.charAt(0);
String answerPhrase = "Your weight is " + " " ;
switch(p){
case 'A':
case 'a':
System.out.println(answerPhrase +(.091*weight));
break;
case 'B':
case 'b':
System.out.println(answerPhrase + (.720*weight));
break;
case 'C':
case 'c':
System.out.println(answerPhrase + (.865*weight));
break;
case 'D':
case 'd':
System.out.println(answerPhrase + (4.612*weight));
break;
default:
System.out.println("Please enter either A,B,C,or D");
break;
}
}
}
I have used almost the exact same code for another similar practice project and it worked just fine. When i run the program it goes to the point where it asks for a weight input, then it displays the choice list, but with the error message exception in "main":
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at weightOnOtherPlanets.main(weightOnOtherPlanets.java:14)
I don't know why it gives this error before allowing keyboard input for String choice.
This is because of the way Scanner scans lines.
After you enter a double (the weight), you press Return. This tells System.in to take all the characters you entered and pass them to the scanner. The scanner then reads the part that interests it - the double number - but leaves everything else waiting for the next operation.
This means the Return you pressed - the end-of-line - is still there. Now, the next thing is nextLine(). The scanner sees it, and it reads all the characters it has until it finds an end-of-line. But as we said, the end-of-line is right there. So it reads that, and gives you all the characters it found before it. Which is none at all, because there were no other characters between the double number and the end-of-line.
This means you get an empty string. And an empty string doesn't have a character at position 0, because that would mean it was not empty.
So what you should do is, after receiving the double, you should add a kbReader.nextLine(); - just like that, without putting the value anywhere. This will skip the end-of-line you entered for the double, and then you'll get the next line properly.
When you do your menu reading, though, you should be checking that the string is not empty before you call charAt(0). After all, the user can decide to press Return rather than make a valid choice. So your system should either ignore that or tell him that it's not a legal input, rather than fail with an exception.
You call nextDouble(); and after that you call nextLine() to get your answer phrase. But that call to nextLine(); will only consume the rest of the line on which you entered your double and it will be empty, therefore choice.charAt(0); will throw an exception.
Try doing something like this to consume the rest of the line and then call the nextLine() to get the answer phrase.
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
kbReader.nextLine(); // Consume the rest of the line
// ...
String choice = kbReader.nextLine(); // Get the actual input
char p = choice.charAt(0);
try this:
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
System.out.println("choose a planet by entering the corresponging letter\n");
System.out.println("A. Voltar");
System.out.println("B. Krypton");
System.out.println("C. Fertos");
System.out.println("D Servantos");
String choice = kbReader.nextLine();
if (choice.isEmpty()) {
choice = kbReader.nextLine();
}
char p = choice.charAt(0);
String answerPhrase = "Your weight is " + " ";
switch (p) {
case 'A':
case 'a':
System.out.println(answerPhrase + (.091 * weight));
break;
case 'B':
case 'b':
System.out.println(answerPhrase + (.720 * weight));
break;
case 'C':
case 'c':
System.out.println(answerPhrase + (.865 * weight));
break;
case 'D':
case 'd':
System.out.println(answerPhrase + (4.612 * weight));
break;
default:
System.out.println("Please enter either A,B,C,or D");
break;
}
}
You need to read for input differently. That's why you are throwing an exception.
char p = choice.charAt(0); // why not just do a string comparison instead?
is where the error comes up. This is because choice is null / has no charAt(0).
Irregardless I would use something like this instead
char p = ''
while(in.hasNext()) {
String input = in.nextLine();
if (p.length()>0){
p = choice.charAt(0);
}
//do whatever you wanted to with p
This should give you the behavior you are looking for.
Don't forget to consider changing the double input to work roughly the same though.

Java Switch Statement: creating a calculator error

I was wondering if anyone can see what is wrong with my code. It works except that the program is not acknowledging my switch statement - I searched lots of questions but as I am a novice I am clearly missing something.
import java.util.Scanner;
class Calmlr1 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String anotherOption = "y", operatorOpt= "a";
int no1=0, no2=0;
double result= 0;
System.out.println ("Welcome to the online calculator! Let's begin...");
while (anotherOption.equalsIgnoreCase ("y")) {
System.out.println ("Please enter your 1st number: ");
no1 = input.nextInt();
System.out.println ("Please confirm your operator:\n1 = +\n2 = - \n3 = *\n4 = /");
operatorOpt = input.next ();
System.out.println ("Please enter your 2nd number: ");
no2 = input.nextInt();
switch(no1) {
case 1:
result=no1+no2;
break;
case 2:
result=no1-no2;
break;
case 3:
result=no1*no2;
break;
case 4:
result=no1/no2;
default:
result = 0 ;
break;
}
System.out.println("Your total calculation is: "+result);
System.out.println("Would you like to do another sum? y/n ");
anotherOption=input.next();
}
}
}
You should be using switch(operatorOpt). Right now you are switching on the first number.
You also need to change:
int operatorOpt= 0;
operatorOpt = input.nextInt();
That is, if you want to keep your switch statement the same. Please also see #Daniel Imms answer for an additional bug fix.
Try adding a break at the end of case 4
case 4:
result=no1/no2;
break;
EDIT J L's answer is the main issue, but this is another problem that will break division.
Your switch should be on the operatorOpt and not on no1.
Also, you're missing a break in the case 4. So, if you want to do a division, you'll get 0 as result.
The input from the user for operatorOpt should be done with input.nextLine(). Or, if you want to keep the same switch statement, with input.nextInt().
It should be like this:
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}
Your switch statement should be on "operatorOpt" and not on "no1" as you suppose to check the operator and based on that you want to do the calculation. However, you must use JDK1.7 to use String in Switch statement since previous versions of JDK do not support String Switch.
Also, you should use "break" in case 4.
Your switch should be on the operatorOpt and not on no1.
You can use like this
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}

Categories