This question already has answers here:
Java: Unresolved compilation problem
(10 answers)
Closed 3 years ago.
This is the error I am getting and I cant seem to figure out how to fix it.
I was trying to make it so that once you have finished your calculations, the program asks you if you want to perform them again.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
retry cannot be resolved
yes cannot be resolved to a variable
My code(don't judge, this is my first program in java):
package calculatorpls;
import java.util.Scanner;
public class calc {
public static void main(String[]Args)
{
do {
Scanner num = new Scanner(System.in);
System.out.println("Please enter the first number."+"\n");
int no1 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no1+"."+"\n"+"\n"+"Please enter the second number now."+"\n");
int no2 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no2+"."+"\n"+"\n"+"Please choose what you would like to do from the following options:"+"\n"+
"1)Addition"+"\n"+"2}Subtraction(1st Number-2nd Number)"+"\n"+"3)Subtraction(2nd Number-1st Number)"+"\n"+"4)Multiplication"+"\n"+"5)Division(1st Number divided by 2nd Number)"+"\n"+"6)Division(2nd Number divided by 1st Number)"
+ ""+"\n"+"7)Multiply by an exponent(1st Number)"+"\n"+"8)Multiply by an exponent(2nd Number)"+"\n"+"\n"+"Type any number from 1-8 to select your option."+"\n");
//String Addition;
//String Subtraction(1st Number-2nd Number);
//String Subtraction(2nd Number-1st Number);
//String Multiplication;
//String Division(1st Number divided by 2nd Number);
//String Division(2nd Number divided by 1st Number);
//String Multiply by an exponent(1st Number);
//String Multiply by an exponent(2nd Number);
int choice = num.nextInt();
System.out.println("\n"+"You have chosen "+choice +"\n");
switch (choice)
{
case 1:
float addition = no1+no2;
System.out.println("\n"+ addition);
break;
case 2:
float subtraction1 = no1-no2;
System.out.println("\n"+ subtraction1);
break;
case 3:
float subtraction2 = no2-no1;
System.out.println("\n"+ subtraction2);
break;
case 4:
float multiplication = no1*no2;
System.out.println("\n"+ multiplication);
break;
case 5:
double division1 = no1/no2;
System.out.println("\n"+ division1);
break;
case 6:
double division2 = no2/no1;
System.out.println("\n"+ division2);
break;
case 7:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponent = num.nextInt();
double exponent1 = (int) Math.pow(no1, exponent);
System.out.println("\n"+ exponent1);
break;
case 8:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponenttwo = num.nextInt();
double exponent2 = (int) Math.pow(no2, exponenttwo);
System.out.println("\n"+ exponent2);
break;
default:
System.out.println("\n"+ "There isnt any such option matching your entry!"+"\n");
break;
}
System.out.println("\n"+ "Would you like to perform more calculations? Respond with yes or no."+"\n");
String retry = num.nextLine();
String again = "yes";
}while(retry.equalsIgnoreCase(again));
}
}
I fixed it for you.
String retry;
String again;
do {
Scanner num = new Scanner(System.in);
System.out.println("Please enter the first number."+"\n");
int no1 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no1+"."+"\n"+"\n"+"Please enter the second number now."+"\n");
int no2 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no2+"."+"\n"+"\n"+"Please choose what you would like to do from the following options:"+"\n"+
"1)Addition"+"\n"+"2}Subtraction(1st Number-2nd Number)"+"\n"+"3)Subtraction(2nd Number-1st Number)"+"\n"+"4)Multiplication"+"\n"+"5)Division(1st Number divided by 2nd Number)"+"\n"+"6)Division(2nd Number divided by 1st Number)"
+ ""+"\n"+"7)Multiply by an exponent(1st Number)"+"\n"+"8)Multiply by an exponent(2nd Number)"+"\n"+"\n"+"Type any number from 1-8 to select your option."+"\n");
//String Addition;
//String Subtraction(1st Number-2nd Number);
//String Subtraction(2nd Number-1st Number);
//String Multiplication;
//String Division(1st Number divided by 2nd Number);
//String Division(2nd Number divided by 1st Number);
//String Multiply by an exponent(1st Number);
//String Multiply by an exponent(2nd Number);
int choice = num.nextInt();
System.out.println("\n"+"You have chosen "+choice +"\n");
switch (choice)
{
case 1:
float addition = no1+no2;
System.out.println("\n"+ addition);
break;
case 2:
float subtraction1 = no1-no2;
System.out.println("\n"+ subtraction1);
break;
case 3:
float subtraction2 = no2-no1;
System.out.println("\n"+ subtraction2);
break;
case 4:
float multiplication = no1*no2;
System.out.println("\n"+ multiplication);
break;
case 5:
double division1 = no1/no2;
System.out.println("\n"+ division1);
break;
case 6:
double division2 = no2/no1;
System.out.println("\n"+ division2);
break;
case 7:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponent = num.nextInt();
double exponent1 = (int) Math.pow(no1, exponent);
System.out.println("\n"+ exponent1);
break;
case 8:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponenttwo = num.nextInt();
double exponent2 = (int) Math.pow(no2, exponenttwo);
System.out.println("\n"+ exponent2);
break;
default:
System.out.println("\n"+ "There isnt any such option matching your entry!"+"\n");
break;
}
System.out.println("\n"+ "Would you like to perform more calculations? Respond with yes or no."+"\n");
retry = num.next();
again = "yes";
}while(retry.equalsIgnoreCase(again));
I'm answering just to expand on nusaK's answer.
You should declare utilities like Scanner which may be used multiple times outside of for loops.
When you put the Scanner num = new Scanner(System.in); inside a loop, a new Scanner Object will be created every time the loop runs. Since we're always scanning from System.in, we can use the same object to scan for all iterations.
Since Java manages memory by itself, it isn't much of a problem but it might be in other languages.
Scanner num = new Scanner(System.in);
String again = "yes"; // you can initialize again here
String retry=""; // always initialize in languages like Java to avoid errors.
do {
...
}
while((retry=num.next()).equalsIgnoreCase(again));
// u can also use this, i.e. assign and evaluate at the same time but it's harder to read.
Related
I'm doing a java number converter and whenever I try my hexadecimal to decimal converter it always gives me a java.lang.NumberFormatException for whatever I type that I want to convert. The console displays this error whenever I type in a string value for example ABC. How would I go about fixing this error? The error occurs at this line: int intNum = Integer.valueOf(numHexadecimal); in the code.
public static void hexToDecimal() {
System.out.println("Enter your hexadecimal number");
numHexadecimal = input.next();
hexArray = numHexadecimal.toCharArray();
int intNum = Integer.valueOf(numHexadecimal);
int counter = 0;
String hexVal = "";
int digit;
digit = intNum % 16;
switch (digit) {
case 1:
hexVal+="F"; break;
case 2:
hexVal+="E"; break;
case 3:
hexVal+="D"; break;
case 4:
hexVal+="C"; break;
case 5:
hexVal+="B"; break;
case 6:
hexVal+="A"; break;
default:
hexVal+=Integer.toString(digit);
}
intNum = intNum/16;
for (counter = hexVal.length()-1; counter >= 0; counter--)
System.out.print(hexVal.charAt(counter));
}
}
If you want to parse hexadecimal numbers you have to use the two-parameters version of valueOf, specifying the radix (16 for hexadecimal) as the second parameter
int intNum = Integer.valueOf(numHexadecimal, 16);
This question already has answers here:
How to loop user input until an integer is inputted?
(5 answers)
Closed 4 years ago.
I'm learning to program in Java and I'm working on a pizza-ordering console program.
I've gotten the entire program to work, but I want to fool-proof it. Three places I ask for an int input, but when I type a char or a string, the program crashes.
What I hoped to achieve:
When the user enters a valid number, the program continues - Done
When the user enters a char or a string they get an error message and the loop starts over.
Here's an example from my code:
do {
correctInput = true;
System.out.println("Step 1: Look through the menu below and type in the NUMBER of the pizza you want.\n");
pizzaMenu();
System.out.print("\nType in your pizza number here: ");
pizzaNumber = pizza.nextInt();
pizza.nextLine();
switch (pizzaNumber) {
case 1:
pizzaChoice = "Napoli";
pizzaPrice = 50;
break;
case 2:
pizzaChoice = "Hawaii";
pizzaPrice = 50;
break;
case 3:
pizzaChoice = "Quattro Stagioni";
pizzaPrice = 60;
break;
case 4:
pizzaChoice = "Sicillia";
pizzaPrice = 75;
break;
case 5:
pizzaChoice = "Turbo";
pizzaPrice = 60;
break;
case 6:
pizzaChoice = "Jamaica";
pizzaPrice = 75;
break;
case 7:
pizzaChoice = "Romano";
pizzaPrice = 60;
break;
case 8:
pizzaChoice = "Vulcano";
pizzaPrice = 75;
break;
case 9:
pizzaChoice = "Vegetariana";
pizzaPrice = 60;
break;
case 10:
pizzaChoice = "Salame";
pizzaPrice = 60;
break;
default:
System.out.println("You've entered a wrong number. Try again");
correctInput = false;
break;
}
} while (!correctInput);
Could you please help pointing me towards a possible solution?
You can read a string from the scanner and then manually try to convert it to required number (either Integer or Double):
String str = scan.next();
if (isNumeric(str))
System.out.println("Numeric value: " + Double.parseDouble(str));
else
System.out.println("Not a numeric");
And method that checks if given string a numeric or not:
private static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e) {
return false;
}
}
My program is designed to assign an integer value based on a class size that the user inputs (S, M, L, X). Then, in a later method, I use this value to calculate the remaining seats available in the class. This issue that I'm having is that, in spite of the program running, the value returned is always zero, no matter what class size the user inputs or the number of students entered as being registered already.
The program includes a few other unrelated steps, so I've isolated the aforementioned methods for ease of reference but I can post my complete code if this is easier.
My code to assign the integer value:
public static int courseSize() {
System.out.print("Please enter the course size (possible values are:
S, M, L, or X):");
size = console.next().charAt(0);
switch(size) {
case 'S': totalSeats = 25;
break;
case 'M': totalSeats = 32;
break;
case 'L': totalSeats = 50;
break;
case 'X': totalSeats = 70;
break;
default: System.out.println("Please enter S, M, L, or X");
}//Close switch statement
console.nextLine();
return totalSeats;
}//Close courseSize
This is the code for obtaining the number of students registered and calculating the number of seats available:
public static void numStudents() {
System.out.print("How many students are currently registered for this course? ");
studentsReg = console.nextInt();
}//Close numStudents method
//This method returns the number of open seats remaining
public static int calcAvail () {
openSeats = (totalSeats - seatsTaken);
return openSeats;
} //Close calcAvail method
This is the output for collecting the user input. You can see the user entered L (50 seats) and 13 students are registered.
However, you can see in the below output that it states there are 0 remaining seats.
All of the variables in this code are declared under my class as public, static variables.
Any thoughts as to why my calculation isn't working? I'm leaning toward the issue being my switch statement because it uses a char as input and then stores it as an integer; however, the output is still printing out the correct number to the screen.
move this console.nextLine(); in numStudents()
default is missing break
default: System.out.println("Please enter S, M, L, or X");
break;
}
return totalSeats;
}
You can do
default: System.out.println("Incorrect entry");
courseSize();
break;
}
and
openSeats = (totalSeats - seatsTaken); should be
openSeats = (totalSeats - studentsReg );
I would clear the EOL character left by your call to nextInt() in your numStudents() with the following code
public static void numStudents() {
System.out.print("How many students are currently registered for this course? ");
//code A
studentsReg = console.nextInt();
console.nextLine();
//or
//code B
studentsReg = Integer.parseInt(console.nextLine());
}//Close numStudents method
Then I would wrap a while() around your switch to make sure your user has to input a valid selection or retry, and use nextLine() instead of next() which also leaves behind an EOL character ('\n').
public static int courseSize() {
boolean validInput = false;
while(!validInput)
{
validInput = true;
System.out.print("Please enter the course size (possible values are: S, M, L, or X):");
size = console.nextLine().charAt(0);
switch(size) {
case 'S': totalSeats = 25;
break;
case 'M': totalSeats = 32;
break;
case 'L': totalSeats = 50;
break;
case 'X': totalSeats = 70;
break;
default: System.out.println("Incorrect Value Entered, Please enter S, M, L, or X");
validInput = false;
break;
}//Close switch statement
}
return totalSeats;
}//Close courseSize
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";
}
I need to write an application which lets the user put in two values and an operator and then calculate it. If the operator is different form +,-,/ or * the application should prompt "Wrong operator input". When it's compiled it should run something like this:
Give me number 1: 5
Give me number 2: 2
Give me an operator: +
Result: 7
The text in bold is userinput.
So far... I've got nothing. I mean I have this:
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n1;
int n2;
String o;
System.out.print("Give me number 1: ");
n1 = input.nextInt();
System.out.print("Give me number 2: ");
n2 = input.nextInt();
System.out.print("Give me an operator: ");
o = input.nextLine();
}
}
But that's about it. I have no idea how to proceed. The biggest question I have is: How do I get the users operator to be an actual operator?
Possibly something like the below would suit your needs:
Scanner input = new Scanner(System.in);
System.out.print("Give me number 1: ");
int n1 = input.nextInt();
System.out.print("Give me number 2: ");
int n2 = input.nextInt();
System.out.print("Give me an operator: ");
String o = input.next();
switch (o) {
case "+":
System.out.println(n1 + n2);
break;
case "-":
System.out.println(n1 - n2);
break;
case "*":
System.out.println(n1 * n2);
break;
case "/":
System.out.println(n1 / n2);
break;
default:
System.out.println("Error, invalid operand.");