This is a simple calculator that I need to get functioning with basic commands. The goal of this project is to program exceptions (very easy) but, I for the life of me, can not figure this out. I have looked everywhere.
Whether it's an if/else statement or a Switch/Case statement, the thrid statement always get skipped. When a user inputs "m" it is supposed to save the value of the calculation to a placeholder variable to be able to be recalled (Again, super simple). I added a default case statement to the addition section and added my save method to the default statement and it works perfectly. Every other command (r for recall, c for clear, and e for exit) also work great. m for save does not at all.....
import java.util.Scanner;
public class Calculator {
public static Scanner input = new Scanner(System.in);
public static double placeHolder;
public static void clear() {
System.out.println("Save has been deleted, Screen has been cleared.");
}
public static void end() {
System.out.println("Program ended..");
input.close();
System.exit(0);
}
public static void save(double initValue) {
System.out.println("Number saved!");
placeHolder = initValue;
}
public static void recall() {
if (placeHolder != 0){
System.out.println("Memory Place Holder Set To: " + placeHolder);
}
else {
System.out.println("There is no data saved.");
}
}
public static void commands() {
System.out.println("e = end | c = clear | m = save | r = recall | o = continue");
String command = input.nextLine();
if (command.equals("e")){
end();
}
else if (command.equals("c")){
clear();
}
else if (command.equals("r")){
recall();
}
}
public static void main(String[] args) {
boolean loop = true;
while (loop == true){
commands();
System.out.println("Please enter what you would like to do: (+,-,*,/,%)");
String function = input.nextLine();
System.out.println("Enter the first number to be calucalted (If dividing, this is the numerator):");
double n1 = input.nextDouble();
System.out.println("Enter the second number to be calucalted (If dividing, this is the denominator):");
double n2 = input.nextDouble();
//=======================
// Addition
//=======================
if (function.equals("+")){
double sum = n1+n2;
System.out.println(n1+"+"+ n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
default:
System.out.println("Default");
save(sum);
break;
}
}
//=======================
// Subtraction
//=======================
else if (function.equals("-")){
double sum = n1-n2;
System.out.println(n1 + "-" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Multiplication
//=======================
else if (function.equals("*")){
double sum = n1*n2;
System.out.println(n1 + "*" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Division
//=======================
else if (function.equals("/")){
double sum = n1/n2;
System.out.println(n1 + "/" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Mod
//=======================
else if (function.equals("%")){
double sum = n1%n2;
System.out.println(n1 + "%" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
}
//=======================
// Dictate loop duration:
//=======================
System.out.println("Would you like to continue? (Y|N): ");
String ans = input.nextLine();
if (ans.equals("N") || ans.equals("n")){
System.out.println("Closing Program");
loop = false;
end();
}
}
}
The main code in question is this: I know the rest don't have a default or break statement. This one does and I am debugging and trying to figure out why the m fails. Right now if you him m, it just goes to the default case statement which, does not solve the issue.
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
default:
System.out.println("Default");
save(sum);
break;
=========================================================================
Here is the Fix for anyone looking at this post after the fact:
public static void main(String[] args) {
boolean loop = true;
while (loop == true){
commands();
System.out.println("Please enter what you would like to do: (+,-,*,/,%)");
String function = input.nextLine();
System.out.println("Enter the first number to be calucalted (If dividing, this is the numerator):");
double n1 = input.nextDouble();
input.nextLine();
System.out.println("Enter the second number to be calucalted (If dividing, this is the denominator):");
double n2 = input.nextDouble();
input.nextLine();
//=======================
// Addition
//=======================
if (function.equals("+")){
double sum = n1+n2;
System.out.println(n1+"+"+ n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
}
}
after every input.nextDouble(); you need to call input.nextLine(); to consume the new line, see Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
remove the unnecessary input.nextLine(); after every String command = input.nextLine();
The nextDouble() does not consume the new line. You can fix this by parsing the full line and then use Double.parseDouble() to get the double value from the line like this
....
System.out.println("Enter the first number to be"+
"calculated (If dividing, this is the numerator):");
double n1 = Double.parseDouble(input.nextLine());
System.out.println("Enter the second number to be" +
"calculated (If dividing, this is the denominator):");
double n2 = Double.parseDouble(input.nextLine());
if (function.equals("+")) {
double sum = n1 + n2;
System.out.println(n1 + "+" + n2 + " = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
switch (command) {
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
}
....
Note
You do not have to check while(loop == true) with boolean variables you can just do check by doing while(loop).
Check this Complete code link
There are few things you need to take care of.
Have a good exception handling.
Validate the user inputs
Changes I made to your code-
clear the placeHolder value in clear() method
using input.next() inplace of input.nextLine() and removing extra input.newLine() methods
added break statements to all switch statements
You need to modularize a lot of things in your code. Have a look at Best Coding practice
input.nextDouble() reads the numbers, but does nothing with the end-of-line. So when you do this later in the code:
String command = input.nextLine();
it handles the left-over end of line, not the "m" you type next.
To fix, do something to handle the end of line on your input, such as adding input.nextLine() after calling nextDouble():
double n1 = input.nextDouble();
input.nextLine();
double n2 = input.nextDouble();
input.nextLine();
Related
I created simple calculator using switch case. When I enter the invalid operators, but it takes that value .And at last it gives the default switch case .How can I restrict it.
package calculator;
import java.util.*;
public class Calculator {
public static void main(String[] args) {
char operator;
Double num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.println("Enter the operator: +,-,*,/,% ");
operator = input.next().charAt(0);
//user input
System.out.println("Enter the First Number:");
num1 = input.nextDouble();
System.out.println("Enter the Second Number:");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1+num2;
System.out.println(num1+" + "+num1+" = " + result);
break;
case '-':
result = num1-num2;
System.out.println(num1+" - "+num1+" = " + result);
break;
case '*':
result = num1*num2;
System.out.println(num1+" * "+num1+" = " + result);
break;
case '/':
result = num1/num2;
System.out.println(num1+" / "+num1+" = " + result);
break;
case '%':
result = num1%num2;
System.out.println(num1+" % "+num1+" = " + result);
break;
default:
System.out.println("Invalid operator");
break;
}
input.close();
}
}
console output
Enter the operator: +,-,*,/,%
7
Enter the First Number:
5
Enter the Second Number:
5
Invalid operator
if(Character.isDigit(c)){
// what you want for true
}
else{
// what you want for false
}
This may help you.
Java or any other programming languages run code sequentially.
Here once the operator is entered you can check to proceed further for other statements.
The logic of code how you write, that way it is executed.
So in this case, once you take value for operator check whether that operator is allowed in your case or not.
If allowed then run the further code else not run that.
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'm trying to error proof my program that basically works as a mini calculator. But I have no idea how to write a "Catch" statement that would detect when the user enters a case number that doesn't exist, in my case anything that is negative or > 4
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
}
}
catch(Exception e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
} ```
Why do you want to throw an Exception unnecessarily? I suggest you just put a default case in your switch with the required error message. Also, move the input part inside the loop, so that it continues to take input.
I also suggest you use nextLine() instead of nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = 0, n = 1;
boolean valid;
do {
do {
valid = true;
try {
operacija = Integer.parseInt(operacijai.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter an integer only.");
valid = false;
}
} while (!valid);
switch (operacija) {
case 1:
System.out.println("addingMethod()");
n = 2;
break;
case 2:
System.out.println("subtractingMethod()");
n = 2;
break;
case 3:
System.out.println("multiplyingMethod()");
n = 2;
break;
case 4:
System.out.println("dividingMethod()");
n = 2;
break;
default:
System.out.println("Invalid input");
}
} while (n == 1);
}
}
A sample run:
Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
5
Invalid input
Another sample run:
Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()
You can also handle the use case in default
It is totally upto your use-case how you are handling the exception, you can also create your custom exception and throw from default
something like:
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
default:
System.out.print("Enter a correct number!")
throw new CustomException();
}
}
catch(CustomException e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
}
Figured out a clean way of doing this with default case.
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija;
do {
operacija = operacijai.nextInt();
switch (operacija) {
case 1:
addingMethod();
break;
case 2:
subtractingMethod();
break;
case 3:
multiplyingMethod();
break;
case 4:
dividingMethod();
break;
default:
System.out.print("Enter a correct number!");
}
} while(operacija < 1 || operacija > 4);
operacijai.close();
}
I've spent hours on this program trying to figure out how to repeat the main menu to show until the user write 3 (to quit the program).
The program asks the user to enter 2 integer numbers, then Main menu shows to choose from 3 options.
I chose the do while loop to force it show at least once, but i don't know what's my mistake?
package javaapplication33;
import static java.lang.System.exit;
import java.util.Scanner;
public class JavaApplication33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers: ");
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn = showMenu();
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
}
public static int showMenu() {
int optionn = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("--------------");
System.out.println("1.Add the numbers");
System.out.println("2.Multiply the numbers");
System.out.println("3.Quit");
System.out.println("--------------");
System.out.println("Enter your choice:");
optionn = keyboard.nextInt();
return optionn;
}
You could consider just a while loop, instead of a do-while.
int optionn = 0;
while (optionn != 3)
{
optionn = showMenu();
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}
}
Additionally, there's no reason to clear out your optionn variable in your showMenu method.
try this
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
int optionn = showMenu();//SHOWS THE MENU AGAIN
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
Your showmenu() method isnt in your while that why i dosent repeat
The two lines of code that needed fixing - have comments, see below:
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}// End of switch statement
optionn = showMenu(); // <--- changed
} while (optionn != 3); // <--- changed
A couple of mistakes.
First you should be getting the user input inside the do/while loop. Just move your optionn=showMenu() inside the do (That way you can show the options again and allow the user to choose again).
Second you want to keep on looping while optionn!=3 instead of optionn==3 (You want to continue looping if the user doesn't want to exit).
I would also not use exit(0) and also move your exit print statement to inside the loop (So you print it before you exit your function). Something like this:
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn;
do {
optionn = showMenu(); //Allow user to select from menu every iteration
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
System.out.println("Thank you. Good Bye."); //Moved from the bottom
return; //I would use return instead of the exit(0) here.
//exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn != 3); //Make sure this is != not ==
Hope this helps!
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";
}