//Loop that isn't working. I keep pressing a number that is 1,2,3,4, or 5 but it won't exit the loop. The operator seems to be assigned the value that I input but it still will not exit the while loop. I'm trying to write a basic calculator with simple math operations but this turned into a very annoying problem.
import java.util.Scanner;
public class BasicCalculatorTwo {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int operator;
double fnum, snum, answer;
operator = 0;
System.out.println("Enter first number : ");
fnum = scanner.nextDouble();
System.out.println("Enter second number : ");
snum = scanner.nextDouble();
while(operator != 1 || operator != 2 || operator != 3 || operator != 4 || operator != 5 ){
System.out.println();
System.out.println(fnum + " ? " + snum + " = ");
System.out.println("1 : Add");
System.out.println("2 : Subtract");
System.out.println("3 : Multiply");
System.out.println("4 : Divide");
System.out.println("5 : Modularize");
operator = scanner.nextInt();
}
switch(operator){
case 1:
answer = fnum + snum;
break;
case 2:
answer = fnum - snum;
break;
case 3:
answer = fnum * snum;
break;
case 4:
answer = fnum / snum;
break;
case 5:
answer = fnum % snum;
break;
default:
break;
System.out.println(fnum + " ? " + snum + " = " + answer);
scanner.close();
}
}
}
You loop conditional is the problem.
while (operator != 1 || operator != 2 || operator != 3 || operator != 4 || operator != 5)
It should be
while (operator != 1 && operator != 2 && operator != 3 && operator != 4 && operator != 5)
Basically, you're saying that if the operator is != 1, then do the loop. Likewise each of the others. If you were to utilize && operators instead of || it would work much better.
Really, what you want to say is that operator is > 1 && < 5, then loop, otherwise break.
while(operator < 1 || operator > 5)
{
DoPrintStuffHere();
}
Think about it logically, you want any number less than 1 OR greater than 5 to loop again.
Related
In this calculator program when I type in any other incorrect answer for the operator such as a number or a letter instead of +, -, *, / it shows the "wrong only operators" message but even when I put in the correct operator the same message still shows up.
How can the program not show the wrong message when I type in the correct symbol.
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner (System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
do
{
operator = scan.next().charAt(0);
System.out.println("Wrong only operators. ");
scan.nextLine();
}
while(operator != '+' && operator != '-' && operator != '*' && operator != '/');
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}
In your case it is better to use a while loop instead of a do while.
Since you are using a do while loop : that statement is being executed at least once, not matter whether the operator is correct or not.
You can add a condition there to stop it from executing but a better way is to use while loop
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner(System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
operator = scan.next().charAt(0);
while(operator != '+' && operator != '-' && operator != '*' && operator != '/')
{
System.out.println("Wrong only operators. ");
operator = scan.next().charAt(0);
scan.nextLine();
}
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}
I have a do-while loop within a do-while loop and switch cases for each of them.
I want the main menu to be looping forever and want the main menu cases to go back to the main menu after some condition.
For example:
//main menu
do {
case 1:
do {
case 1:
case 2:
} while(something);
//go back to main menu
case 2:
case 3:
case 4:
} while(true);
How may I achieve this in Java code?
Below is my code for your reference (should you need it) :)
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("[1] Priority Queue");
System.out.println("[2] 2D Array");
System.out.print("Please choose a data structure: ");
int num = scanner.nextInt();
switch (num) {
// ==================== PriorityQueue ====================
case 1:
System.out.println("\n=== Priority Queue Test ===\n");
System.out.print("Enter size of priority queue: ");
PriorityQueue pq = new PriorityQueue(scanner.nextInt());
char a;
/* Perform Priority Queue operations */
do {
System.out.println("\nPriority Queue Operations\n");
System.out.println("1. insert");
System.out.println("2. remove");
System.out.println("3. check empty");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter job name and priority: ");
pq.insert(scanner.next(), scanner.nextInt());
break;
case 2:
System.out.println("\nJob removed \n\n" + pq.remove());
break;
case 3:
System.out.println("\nEmpty Status: " + pq.isEmpty());
break;
default:
System.out.println("Wrong Entry \n ");
break;
}
System.out.println("\nDo you want to continue? (y or n) \n");
a = scanner.next().charAt(0);
} while (a == 'Y' || a == 'y' || a != 'N' || a != 'n');
break;
// ==================== 2D Array ====================
case 2:
TwoDimensionalArray array = new TwoDimensionalArray();
System.out.println("\n=== 2D Array Test ===\n");
System.out.println("Enter size of 2D Array: ");
int DIM = scanner.nextInt();
int[][] table = new int[DIM][DIM];
char b;
do {
System.out.println("1. insert [x][y] coordinate");
System.out.println("2. remove [x][y] coordinate");
System.out.println("3. empty");
System.out.println("4. print");
int choice = scanner.nextInt();
switch (choice) {
case 1:
array.insert(table, scanner);
break;
case 2:
array.remove(table, scanner);
break;
case 3:
array.empty(DIM);
break;
case 4:
array.print(DIM, table);
break;
}
System.out.println("\nDo you want to continue? (y or n) \n");
b = scanner.next().charAt(0);
} while (b == 'Y' || b == 'y' || b != 'N' || b != 'n');
break;
default:
System.out.println("Please choose a number on the list!\n");
}
while (num == 1 || num == 2 || num == 3 || num == 4 || num == 5 || num == 6 || num == 7 || num == 8 || num == 9
|| num == 10 || num == 11 || num == 12 || num == 13 || num == 14 || num == 15 || num == 16 || num == 17)
;
} while (true);
}
}
Take a look at your while conditions.
while (a == 'Y' || a == 'y' || a != 'N' || a != 'n');
This always evaluates to true and so you never the leave the inner loop.
You need to change it to
while ((a == 'Y' || a == 'y') && (a != 'N' || a != 'n'));
This part doesn't seem necessary
while (num == 1 || num == 2 || num == 3 || num == 4 || num == 5 || num == 6 || num == 7 || num == 8 || num == 9
|| num == 10 || num == 11 || num == 12 || num == 13 || num == 14 || num == 15 || num == 16 || num == 17)
;
If you remove it and change the while conditions accordingly it should work.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
The "switch case" witch I have write for sin,cos,tan,cot doesn't work when I enter them in operator and it goes to entering second number.
Where is my fault?
Here is my code:
import java.util.Scanner;
public class MainClass {
public static void main(String args[]){
Scanner NumInput = new Scanner(System.in);
double firstNum = 0;
double secondNum = 0;
double result = 0;
System.out.println("Enter first number: ");
firstNum = NumInput.nextDouble() ;
System.out.println("Enter operator: ");
String amalgar = NumInput.next();
if (amalgar == "sin" || amalgar == "cos" || amalgar == "tan" || amalgar == "cot"){
switch(amalgar){
case "sin":
result = Math.toRadians(Math.sin(firstNum));
break;
case "cos":
result = Math.toRadians(Math.cos(firstNum));
break;
case "tan":
result = Math.toRadians(Math.tan(firstNum));
break;
case "cot":
result = (Math.toRadians(Math.cos(firstNum))/Math.toRadians(Math.sin(firstNum)));
break;
default :
break;
}
System.out.println(Math.toRadians(result));
}
else
System.out.println("Enter second number: ");
secondNum = NumInput.nextDouble();
switch (amalgar){
case "+":
result = firstNum + secondNum;
break;
case "-":
result = firstNum - secondNum;
break;
case "*":
result = firstNum * secondNum;
break;
case "/":
result = firstNum / secondNum;
break;
default:
System.out.println("nemifahmam chi neveeshti");
}
System.out.println(result);
}
}
The problem lies with this if condition:
if (amalgar == "sin" || amalgar == "cos" || amalgar == "tan" || amalgar == "cot"){
Using == only evaluates to true if you have the same object (i.e. two identical references) but "sin"(or "cos",etc) and amalgar are always two different objects. You should use equals() instead to compare the value. (see How do I compare strings in Java?)
Better yet, don't use the if-else block at all. Use switch, because if you don't match one of those four you won't evaluate anything but your default case, which is empty.
I'd like to ask a question about my code.
I apologize for the inefficiency and the messiness of it, I am still trying to learn java.
System.out.println("Please choose the number corresponding to the operation: ");
System.out.println("1 for add,2 for subtract,3 for multiply, 4 for divide, 5 for print, and 6 for exit: ");
if (sc.nextInt() == 5) {
System.out.println("Your first fraction is: " + num1 + "/" + denom1 + " or in decimal: " + ((float) num1 / denom1));
System.out.println("Your second fraction is: " + num2 + "/" + denom2 + " or in decimal: " + ((float) num2 / denom2));
} else if (sc.nextInt() == 3) {
System.out.println("Multiply: " + (num1 * num2) + "/" + (denom1 * denom2));
} else if (sc.nextInt() == 4) {
System.out.println("Divide: " + (num1 * denom2) + "/" + (denom1 * num1));
} else if (sc.nextInt() == 1) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Addition: " + (n1 + n2) + "/" + d);
} else if (sc.nextInt() == 2) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Subtract: " + (n1 - n2) + "/" + d);
}
else if (sc.nextInt() == 6 ) {
System.exit(0);
}
}
}
When I run the program, the first if statement gets by fine, as I only have to input the number 5 one time. However as you can see from the second else if statement which is the number 3 requires two inputs, I have to enter it two times before the next line comes up. The third else if statement which is the number 4 requires 3 inputs before the next line shows up, and so on with each successive else if statement. I'm sorry if I am not explaining this properly, Does anyone have any idea why this is happening?
Change your code to:
int input = sc.nextInt();
sc.nextLine();
if (input == 5) {
and all other if (sc.nextInt()...)also.
nextInt will consume your input. So if you come to the second if the input is alredy consumed by the first if .
nextLine is nessesary to consume the <ENTER> after the int value.
Try to use switch statement.
package practice;
import java.util.Scanner;
public class Stack{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE 2 NUMBERS");
int num1=sc.nextInt();
int num2=sc.nextInt();
System.out.println("ENTER THE CHOICE");
int choice='0';
while(choice!=6)
{
choice=sc.nextInt();
System.out.println(choice);
switch(choice)
{
case 1:
int add=num1+num2;
System.out.println("Addition:"+add);
break;
case 2:
System.out.println("Subtract:");
break;
case 3:
System.out.println("Multiply:");
break;
case 4:
System.out.println("Divide:");
break;
case 5:
System.out.println("Your first fraction is:");
System.out.println("Your second fraction is:");
break;
case 6:
System.exit(0);
break;
default:
System.out.println("LOSER");
break;
}
}
sc.close();
}
}
When the following Java program is compiled, the following error occurs:
method exit in class System cannot be applied to given types;
I have 2 classes, MainClass and MathQuiz.
MainClass:
class MainClass {
public static void main(String args[]) {
MathQuiz mq = new MathQuiz(); //whenever "mq" is written, this refers to class "MathQuiz"
mq.initialiseVars(); //initialise variables (from MathQuiz)
byte exitChoice = 0;
//ask user for choice
mq.showOprMenu(); //show operation menu (from MathQuiz)
byte oprChoice = Keyboard.readByte(); //ask for user input
//if input is out of range (smaller than 0 or greater than 4), ask again
while(oprChoice < 0 || oprChoice > 4) {
System.out.print("Invalid choice! Enter your choice again (1, 2, 3, 4 or 0): ");
oprChoice = Keyboard.readByte();
}//while
mq.showDiffMenu(); //show difficulty menu (from MathQuiz)
byte diffChoice = Keyboard.readByte(); //ask for user input
//if input is out of range (smaller than 0 or greater than 3), ask again
while(diffChoice < 0 || diffChoice > 3) {
System.out.print("Invalid choice! Enter your choice again (1, 2, 3 or 0): ");
diffChoice = Keyboard.readByte(); //ask for user input
}//while
mq.generateRandNums(); //generate random numbers (from MathQuiz)
switch (exitChoice) {
case 0: {
while (exitChoice != 1 || exitChoice != 2); {
System.out.print("Are you sure you want to exit? (1 = Yes, 2 = No) ");
exitChoice = Keyboard.readByte(); //ask for user input
if (exitChoice == 1) {
System.out.println("Exiting program.");
**System.exit(); //quit program**
}//if exitChoice is 1
else if (exitChoice == 2) {
System.out.println("Returning to menu.");
mq.showOprMenu();
}//if exitChoice is 2
}//while exitChoice is neither 1 nor 2
}//case 0 ("Exit" chosen)
case 1: {
System.out.println("You will be tested on addition.");
mq.showAddQuestion(); //show addition question (from MathQuiz)
mq.checkAns(); //check answer (from MathQuiz)
break;
}//case 1 ("Addition" chosen)
case 2: {
System.out.println("You will be tested on subtraction.");
mq.showSubQuestion(); //show subtraction question (from MathQuiz)
mq.checkAns(); //check answer (from MathQuiz)
break;
}//case 2 ("Subtraction" chosen)
case 3: {
System.out.println("You will be tested on multiplication.");
mq.showMultQuestion(); //show multiplication question (from MathQuiz)
mq.checkAns(); //check answer (from MathQuiz)
break;
}//case 3 ("Multiplication" chosen)
case 4: {
System.out.println("You will be tested on division.");
mq.showDivQuestion(); //show division question (from MathQuiz)
mq.checkDivAns(); //check answer and remainder (from MathQuiz)
break;
}//case 4 ("Division" chosen)
}//switch (exitChoice)
}//main
}//class
MathQuiz:
class MathQuiz {
//properties
byte diffChoice, oprChoice, exitChoice;
int num1, num2, userAns, correctAns, userRem, correctRem, score, numOfQuestions;
//methods
public void showOprMenu() {
System.out.println("-------------------");
System.out.println("Mathematical Quiz");
System.out.println(); //skip a line
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("0. Exit");
System.out.println("-------------------");
System.out.print("Enter your choice (1, 2, 3, 4 or 0): ");
}//show operation menu
public void showDiffMenu() {
System.out.println("-------------------");
System.out.println("Difficulty Settings");
System.out.println();
System.out.println("1. Easy");
System.out.println("2. Medium");
System.out.println("3. Hard");
System.out.println("0. Go back to Operation Menu");
System.out.println("-------------------");
System.out.print("Enter your choice (1, 2, 3 or 0): ");
}//showDiffMenu();
//initialise variables
public void initialiseVars() {
userAns = 0;
correctAns = 0;
userRem = 0;
correctRem = 0;
score = 0;
numOfQuestions = 0;
diffChoice = 0;
exitChoice = 0;
oprChoice = 0;
}//initialiseVars();
//generate random values for num1 and num2
public void generateRandNums() {
switch (diffChoice) {
case 0: showOprMenu(); break; //case 0 (back to operation menu)
case 1: {
//generate random values for num1 and num2 (between 1 and 10)
num1 = (int) (Math.random() * (10));
num2 = (int) (Math.random() * (10));
break;
}//case 1 (easy)
case 2: {
//generate random values for num1 and num2 (between 1 and 100)
num1 = (int) (Math.random() * (100));
num2 = (int) (Math.random() * (100));
break;
}//case 2 (medium)
case 3: {
//generate random values for num1 and num2 (between 1 and 1000)
num1 = (int) (Math.random() * (1000));
num2 = (int) (Math.random() * (1000));
break;
}//case 3 (hard)
}//switch (diffChoice)
}//generateRandNums();
//show addition question
public void showAddQuestion() {
System.out.print(num1 + " + " + num2 + " = ");
userAns = Keyboard.readInt();
correctAns = num1 + num2;
}//showAddQuestion();
//show subtraction question
public void showSubQuestion() {
System.out.print(num1 + " - " + num2 + " = ");
userAns = Keyboard.readInt();
correctAns = num1 - num2;
}//showSubQuestion();
//show multiplication question
public void showMultQuestion() {
System.out.print(num1 + " * " + num2 + " = ");
userAns = Keyboard.readInt();
correctAns = num1 * num2;
}//showMultQuestion();
//show division question
public void showDivQuestion() {
System.out.print(num1 + " / " + num2 + " = ");
userAns = Keyboard.readInt();
correctAns = num1 / num2;
System.out.print("Remainder: ");
userRem = Keyboard.readInt();
correctRem = num1 % num2;
}//showDivQuestion();
//check if inputted answer is correct (addition/subtraction/multiplication)
public void checkAns() {
if(userAns == correctAns) {
System.out.println("Correct!");
score++;
}//if answer is correct
else System.out.println("Incorrect."); //if answer is incorrect
numOfQuestions++; //increases the question "counter" by 1 (both if correct or incorrect)
}//checkAns();
//check if inputted answer and remainder is correct (division)
public void checkDivAns() {
if(userAns == correctAns) System.out.println("Correct!"); //if answer is correct
else System.out.println("Incorrect."); //if answer is incorrect
if(userRem == correctRem) System.out.println("Correct!"); //if remainder is correct
else System.out.println("Incorrect."); //if remainder is incorrect
if((userAns == correctAns) && (userRem == correctRem)) score++; //if both answer and remainder are correct
numOfQuestions++; //increases the question "counter" by 1 (both if correct or incorrect)
}//checkDivAns();
}//class
System.exit takes one argument and you should pass an exit status to it, e.g:
System.exit(0); // zero exit status usually means that program did its job without errors.
Or you can simply do:
return; // in the main method return basically has the same effect as System.exit(0)
System.exit(int status), has an int parameter.
Instead use:.
System.exit(0);