I was trying to make a simple calculator but I'm kind of stuck. I have the majority of the programming there, but I don't understand why my do/while loop isn't working properly. I would like for the user to input 0 for exit, or 1~4 for the respective calculation.
However, despite my efforts I can't seem to get this working entirely. The problem is that instead of looping until the user inputs something desired, it just terminates entirely.
Any help would be greatly appreciated, thank you!
import java.util.*;
public class Main
{
public static void main(String[] args) {
//variable declare
double number1,number2,answer=0;
int choice;
//scanner to get input from user
Scanner sc = new Scanner(System.in);
do{
//ask user to input number
System.out.println("Welcome user \n---------------------------------");
System.out.println("Enter the first number");
number1 = sc.nextDouble();
System.out.println("Enter the second number");
number2 = sc.nextDouble();
//ask user to enter the choice
System.out.println("What would you like to do? \n1)Addtion\n2)Subtraction\n3)Multiplication\n4)Division\n0)Exit");
choice = sc.nextInt();
//condition to exit the do while loop
if(choice == 0){
break;
}
//switch condition to loop the choice
switch(choice){
case 1 : answer = calcSum(number1,number2);break;
case 2 : answer = calcSub(number1,number2);break;
case 3 : answer = calcMult(number1,number2);break;
case 4 : answer = calcDiv(number1,number2);break;
default : System.out.println("What would you like to do? \n1)Addtion\n2)Subtraction\n3)Multiplication\n4)Division\n0)Exit");break;
}
//print th result after every iteration
displayResult(answer);
}while(choice>0&&choice<5);
}
//calculate sum
static double calcSum(double a, double b){
return a+b;
}
//subtraction
static double calcSub(double a, double b){
return a-b;
}
static double calcMult(double a, double b){
return a*b;
}
//division
static double calcDiv(double a, double b){
return a/b;
}
//print result
static void displayResult(double result){
System.out.println("Result is "+result);
}
}
I would like for the program to validate that the user inputs something desired such as 0, 1, 2, 3 or 4. I'm sorry for the difficulty, I've been learning methods and I'm getting pretty confused.
OK, assuming the problem is that when one enters, e.g., "8" for the value, the program terminates, the issue is in the test.
So, the default in the switch will display the message (and then it will output garbage for the answer), but the check is (choice > 0 && choice < 5); which will fail if one enters "8".
Easy solution is to do change the default to put a value in the range.
Related
I got this question on exam review "Write psuedocode for a program that reads a sequence of integer values and decides whether or not it is a decreasing sequence. The program will first read in the number of values to process, followed by the values themselves. The output will be “Yes” if the sequence is decreasing, and “No” otherwise."
Here is my code, but it sometimes does not stop,(for example, when you input 3 2 1). Can someone help me to figure out where I was wrong? Thank you!
import java.util.Scanner;
public class DecreasingOrNot {
public static void main(String[] args){
int number1, number2;
boolean decrease = true;
Scanner input = new Scanner(System.in);
System.out.println("Enter a sequence of numbers: ");
number2 = input.nextInt();
while (decrease && input.hasNext()){
number1 = number2;
number2 = input.nextInt();
if (number1 < number2){
decrease = false;
}
}
if (decrease){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
Right now, you have no way of breaking out of the loop if the user keeps adding decreasing numbers (which is why it won't break out of the loop if the user enters something like 3 2 1).
I am trying to make a java calculator that works for multiplication, division, subtraction and addition. I am just starting the division part and it is incomplete, however I am getting an error that says "one can not be resolved to a variable". At this certain spot I want to make it so if they type in "one" it will start the division class. Code for main class:
import java.util.Scanner;
class apples {
public static void main(String args[]) {
System.out.println("This is a calculator that can divide, multiply, subtract and add. To divide type in one, to multiply type in two, to subtract type in three and to add type in four");
Scanner input = new Scanner(System.in);
int div, mult, sub, add;
if (input = one) {
division divisionObject = new division();
}
div = input.nextInt();
mult = input.nextInt();
sub = input.nextInt();
add = input.nextInt();
if(div > mult && div > sub && div >add){
}
}
}
Code for division class(I have not touched the other classes yet):
import java.util.Scanner;
public class division {
public static void divide() {
int div1, div2, divanswer;
System.out.println("Enter a number to divide: ");
div1 = input.nextInt();
}
}
P.S Keep in mind I have only been coding in java for like half a week so I am a complete noob.
You should use a String variable to store the choice entered by user like "one".
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
Also, change your if condition to :
if(choice.equalsIgnoreCase("one"))
{
division divisionObject = new division();
}
this will check the choice entered by user.
what is one ?? is it defined anywhere? because if it is a string it has to be quoted like "one" or if it is a variable in which you have stored string then you'll have to use this code:
String stringVal=input.nextLine();// use this for string as an input
//or
int intValue=input.nextLine();// use this for integer as an input
//use any of the below statement based on their declaration.(intValue==1) or (stringVal.equalsIgnoreCase("one"))
if ((intValue==1)||(stringVal.equalsIgnoreCase("one")))
{
division divisionObject = new division();
}
instead of using this :
if (input = one) {
division divisionObject = new division();
}
Happy Coding.. :)
Rectify with this , u will get ur mistake:=
import java.util.*;
public class Algebra {
public static void main(String []args){
int n=0;
float result;
System.out.println("1.Addition");
System.out.println("2.Subtarction");
System.out.println("3.Multiplication");
System.out.println("4.Division");
float a = 0,b = 0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a and b");
a=sc.nextInt();
b=sc.nextInt();
System.out.println("Enter ur choice");
n=sc.nextInt();
switch (n)
{
case 1: result=a+b;
System.out.println("Sum is "+result);
break;
case 2: result=a-b;
System.out.println("Sub is "+result);
break;
case 3: result=a*b;
System.out.println("mult is "+result);
break;
case 4: result=a/b;
System.out.println("div is "+result);
break;
}
}
}
You never declared one as a variable...
If you want to use it try adding in.
int one;
somewhere. I'm not saying anything else is right. but this is why you are getting an error.
read more on your issue. you need to store the user input as one in order to compare. you have a reference to nowhere.
I am fairly new to Java and I am trying to write a small program that asks a user to enter an integer between 0-4. I have written this so far and but it doesn't seem to work! Can anyone tell me where am I wrong?
import java.util.Scanner;
public class GameCharSelect {
public static void main(String[] argh){
int myChar;
Scanner in = new Scanner(System.in);
{
System.out.print("choose a player: ");
myChar = in.nextInt();
}while(myChar>0 && myChar<4);
System.out.println("--------");
System.out.println("you chose "+ myChar);
}
}
Now I want the number to be 1,2 or 3 or else it loop until the user input one of these but the program accept any number at the moment. Where am I wrong?
You are missing a do keyword in your loop. Also your conditional should be reversed:
public static void main(String[] argh) {
int myChar;
Scanner in = new Scanner(System.in);
do {
System.out.print("choose a player: ");
myChar = in.nextInt();
} while (myChar <= 0 || myChar >= 4);
System.out.println("--------");
System.out.println("you chose " + myChar);
}
Your while condition is wrong.
You are checking if the char is larger than 0 AND lower than 4, and if it is, it will do the loop again, while what you are after is the oposite.
Change the statement to check if myChar is smaller than 1 OR higher than 3.
myChar < 1 || myChar > 3
You are also missing a do at the beginning of the do-while.
You haf two problems in your code:
You are putting the while in a wrong way, you should put a do-while statement or put the while before the {...}.
You also want to run the loop when you put a wrong number (<1 or >3), not when you put the correct number(between 1 and 3)... So you also need to change the expression.
My code would be something like this:
import java.util.Scanner;
public class GameCharSelect {
public static void main(String[] argh){
int myChar;
Scanner in = new Scanner(System.in);
do{
System.out.print("choose a player: ");
myChar = in.nextInt();
} while(myChar<1 || myChar>3);
System.out.println("--------");
System.out.println("you chose "+ myChar);
}
}
Your loop should look like
while (true) {
System.out.print("Choose a player: ");
myChar = in.nextInt();
if (myChar > 0 && myChar < 4) {
break; // out of the loop
}
}
That is you only break; out of it if the scanned value is either 1, 2, or 3.
#Ali, while(true) approach is perfectly fine. In fact, it's far more common to see them than a do-while() in actual code running out there. The downvote received is subjective and based on individual coding style preference rather than an indication on the correctness of the answer.
import java.util.Scanner;
public class Dice {
public static void main(String[] args) {
//I used 'print' instead of 'println' just to make it look a little cleaner in the console.
System.out.print("Input your first number: ");
Scanner sc1 = new Scanner(System.in);
double num1 = sc1.nextInt();
//I use doubles for my variables just in case the user wants to divide.
System.out.print("Input your second number: ");
Scanner sc2 = new Scanner(System.in);
double num2 = sc2.nextInt();
/* I used words rather than the actual symbols for my operators just to get practice using scanners for strings.
* Until now I'd solely been using them for int variables. And also due to the small detail that before programming,
* I had no idea what a modulo was and I felt that would be confusing to a random person.
*/
System.out.println("What would you like to do with these numbers?(Add, Subtract, Multiply, Divide, or Check Divisibility): ");
System.out.println("Simply type 'check' to check the divisibility of your two numbers.");
Scanner sc3 = new Scanner(System.in);
String str1 = sc3.nextLine().toUpperCase();
/* toUpperCase to prevent the user from creating an error by typing their in put in a 'unique' way.
*It took me several failures to finally look up toUpperCase.
*/
double num3;
switch(str1) {
case "ADD":
num3 = num1 + num2;
System.out.println("The sum is: " + num3);
break;
case "SUBTRACT":
num3 = num1 + num2;
System.out.println("The difference is: " + num3);
break;
case "MULTIPLY":
num3 = num1 * num2;
System.out.println("The product is: " + num3);
break;
case "DIVIDE":
num3 = num1 / num2;
System.out.println("The quotient is: " + num3);
break;
case "CHECK":
num3 = num1 % num2;
System.out.println("The remainder is: " + num3);
break;
default:
System.out.println("Invalid input. Please ensure that two numbers were entered and that you entered a valid math operation.");
break;
}//switch statement
}//main method
}//class
How would I get my code to run again if I wanted to maybe add another number to my answer? I'm just trying to get some practice in with my Java (I'm extremely green) and I apologize in advance if my question is too broad.
Consider the following small program
boolean quit = false;
while(!quit) {
System.out.print("Enter Something:");
Scanner sc1 = new Scanner(System.in);
String input = sc1.nextLine();
if(input.compareToIgnoreCase("quit") == 0) {
quit = true;
continue;
}
System.out.println("You entered " + input);
}
In this sample we keep asking them to enter something and print it out unless that input is "quit" in that case we use the continue statement to skip the rest of the loop and go back to the top of the while loop and re-evaluate the condition for another iteration. If you entered 'quit' this will evaluate to false and stop the loop and exit the program.
Heres a sample input/output from the program. Notice there is no "You entered quit", this is because the continue statement brought us back to the top of the while loop.
Enter Something:hello
You entered hello
Enter Something:quit
Now how can you adapt this to your program? Heres a small sample of how you can do one of your inputs
double num1 = 0;
String input1 = sc1.nextLine();
if(input1.compareToIgnoreCase("quit") == 0) {
// quit was entered, leave the loop
quit = true;
continue;
}
try {
num1 = Double.parseDouble(input1);
} catch(NumberFormatException e) {
// user entered something that isnt a number, quit the program for now
// you can change this to whatever behavior you like in the future
quit = true;
continue;
}
This will likely leave you with some validation questions like "I want to have my user try again if they input an invalid number" Those are all possible using this method and it leads you in the right direction.
Remember, main() is a callable method. Instead of using a while or for loop, you could just call it again at the end of the main method method.
// Put this at the end of your main method
System.out.print("Do you want to execute again? (yes/no)");
boolean repeat = sc1.nextLine().toUpperCase().equals("YES");
if (repeat) {
main(null); // You're not using any arguments in main()
}
On a separate note, you don't need all three of sc1, sc2, and sc3. They're basically the same. You could probably use sc1 everywhere and remove sc2 and sc3 completely.
// something like this then ask if to do another run if not set flag false
boolean flag = true;
while(flag)
{
System.out.print("Input your first number: ");
Scanner sc1 = new Scanner(System.in);
double num1 = sc1.nextInt();
You should put all your logic around a while loop which will grant to you to repeat your task until a condition is reached.
Maybe you can ask to the user to insert the string "EXIT" when he wants to exit from your program.
In your case I'll do something like this:
boolean exitFlag = false;
do {
// <put your logic here>
String answer = sc3.nextLine().toUpperCase();
if (answer.equals("EXIT")) {
exitFlag = true;
}
} while(!exitFlag);
I can't get this to work properly. It functions as it is supposed to, and does the math, but then it loops once, and ends. I need it to either loop until the users decides to end it, or only run once.
import java.util.Scanner;
public class java {
public static void main(String args[]) {
System.out.println("Welcome to the simple Calculator program");
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
Scanner input = new Scanner(System.in);
int math = input.nextInt();
if (math == 1) {
Scanner a = new Scanner(System.in);
int a1;
int a2;
int asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.print("The sum is: " + asum + "Thank You for using this program");
}
Scanner number = new Scanner(System.in);
int number1;
int number2;
int sum;
System.out.print("Enter first number: ");
number1 = number.nextInt();
System.out.print("Enter Second number: ");
number2 = number.nextInt();
sum = number1 + number2;
System.out.printf("Sum is %d\n", sum);
}
}
Use
do{
// do something.
} while(some condition);
And reapeat the same scanner to get input. You can also add one more option to your menu for repeating and evaluate that with while condition.
It is working as it should.
If you want it to loop as per some user input,you must use any looping construct like while.
Instead of if (math == 1) use
`while (math != exit)`
Make a new entry for exit like 0
Try using while loop. Give the user an option to quit the program.
import java.util.Scanner;
public class java
{
public static void main(String args[])
{
Scanner a = new Scanner(System.in);
System.out.println("Welcome to the simple Calculator program");
while(true)
{
System.out.println("Please type what type of math you would like to do: ");
System.out.println("1=Addition");
System.out.println("2=Subtraction");
System.out.println("3=Multiplication");
System.out.println("4=Division");
System.out.println("5=Sqrt");
System.out.println("6=Quit"); // added an option to quit the program
int math = a.nextInt();
if (math == 1)
{
int a1,a2,asum;
System.out.print("Please enter the first number: ");
a1 = a.nextInt();
System.out.print("Please enter the second number: ");
a2 = a.nextInt();
asum = a2 + a1;
System.out.println("The sum is: " + asum + "Thank You for using this program");
}
// Include actions for math = 2 to 5
if(math == 6)
{
System.out.println("Thank You for using this program");
System.exit(0);
}
}
}
}
The options are displayed again and again after each calculation until the user wants to exit the program by entering 6.
If you want the program to run only once, you should leave out the outer while loop. Everything else remains the same.
PS - You don't need to reopen Scanner again and again (at least not in this problem).
That is because you are only reading the input from the console once..you need to keep the console up with something like while(true) {} or monitor the console for an exit conditon like (" 0 = exit ") .
Also, I don''t think you will need to read two numbers again and again like you are doing right now.
1) You can use a do-while loop with a condition till which you wish to execute.
2) Use a switch case and perform the math operations inside the switch case with different operators. As of now you are trying to perform only addition. So you a switch case where you can perform all the operations.
3) In the switch case have an option which calls the exit(0) method. So that you can run the program until the user wish to exit.
4) By using a switch case you can make the user to choose his own option.
Your entire program is correct dude.
Just add
System.exit(0);
In every if(math==1) ,if(math==2)...before their statement ending.
like if(math==1)
{
...
System.exit(0);
}
You can fix your error...
Like me if your error is fixed. If not tell me the error