Java output error - java

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

Related

Trying to stop a Do-While Loop for an application

I'm creating an application for a homework, the problem is that I am trying to create a do-while loop to exit the application (Using the question "Do you want to exit (Y/N)"). To work with the do-while loop, I created a method to store the app and then called the method in the do-while loop, so that when I try to stop the loop, the method loops once more. I want when I type "Y" to the console the whole program stops and doesn't loop one more time.
I created a simple example to explain my problem.
Here's the method:
public static void App(){
Scanner sc = new Scanner(System.in);
System.out.print("Write a number: ");
int num1 = sc.nextInt();
System.out.print("Write another number: ");
int num2 = sc.nextInt();
System.out.println("\nResult: "+(num1+num2));
}
And here I'm trying to create the loop in the main method:
public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);
App();
String answer;
do {
System.out.println("Do you want to exit (Y/N)?");
answer = sc2.next();
App();
} while (answer.equalsIgnoreCase("N")) ;
}
the problem is that I am trying to create a do-while loop to exit the application
You already have that in your program.
so that when I try to stop the loop, the method loops once more...
That doesn't fit the goal of your program.
I want when I type "Y" to the console the whole program stops and doesn't loop one more time
A lot of context that doesn't fit right in.
But anyway, you just have to reorganize your program.
In other words, just move your App() method.
public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);
String answer;
do {
App();
System.out.println("Do you want to exit (Y/N)?");
answer = sc2.next();
} while (answer.equalsIgnoreCase("N")) ;
}
Also, I spotted a lot of bad practices, so I kind of fixed them:
public static void main(String[] args) throws Exception {
try(Scanner sc2 = new Scanner(System.in)){
String answer;
do {
App();
System.out.print("Do you want to exit (Y/N)?");
answer = sc2.nextLine();
} while (answer.equalsIgnoreCase("N")) ;
}
}
Lastly, maybe (just maybe) try to solve your problem first before seeking help for your homework.
The reason why your program is running again after you type n is because the App() method is ran after the question is asked within the do part of the loop.
This code below is the simplest fix I could think of.
public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);
// I removed the line 'App();' as the App method will always run at least one time. Therefore putting that method within the 'do' part of the loop allows us to ask the user if they wish to exit or not after they have received their answer.
String answer;
do {
App();
System.out.print("Do you want to exit (Y/N)?"); //I changed the 'println' to 'print' here
answer = sc2.next();
} while (answer.equalsIgnoreCase("N")) ;
}
As a side note, methods in java should be lower-case when following typical Java naming conventions. While this will not affect how your code runs, I would suggest renaming the method from App() to app().
Everything looks good in your code, Just change the execution logic as shown in code blocks.
public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);
App(); //remove this line from here
String answer;
do {
App(); //call App function here so that it got executed at least one time
System.out.println("Do you want to exit (Y/N)?");
answer = sc2.next();
App(); //remove this as well
} while (answer.equalsIgnoreCase("N")) ;
}
Here is yet another approach except it uses a while loops instead of do/while loops. Two different approaches are provided and both provide User entry validation:
Approach #1:
public static void appMethod() {
Scanner sc = new Scanner(System.in);
int num1 = Integer.MIN_VALUE; // Initialize with some obscure value.
int num2 = Integer.MIN_VALUE; // Initialize with some obscure value.
while (num1 == Integer.MIN_VALUE) {
System.out.print("Write a number: ");
try {
num1 = sc.nextInt();
} catch ( java.util.InputMismatchException ex) {
System.out.println("Invalid Entry! Try again..."
+ System.lineSeparator());
sc.nextLine(); // consume the ENTER key hit otherwise this error will keep cycling.
num1 = Integer.MIN_VALUE;
}
}
while (num2 == Integer.MIN_VALUE) {
System.out.print("Now, write yet another number: ");
try {
num2 = sc.nextInt();
} catch ( java.util.InputMismatchException ex) {
System.out.println("Invalid Entry! Try again..."
+ System.lineSeparator());
sc.nextLine(); // consume the ENTER key hit otherwise this error will keep cycling.
num2 = Integer.MIN_VALUE;
}
}
System.out.println("\nResult: " + num1 +" + " + num2 + " = " + (num1 + num2));
}
Approach #2:
This next approach makes use of the Scanner#nextLine() method. The thing to remember about nextLine() is that, if you use it in your console application then basically recommend you use it for everything (all prompts). A 'quit' mechanism is also available in this version. Read the comments in code:
public static void appMethod() {
Scanner sc = new Scanner(System.in);
// Retrieve first number...
String num1 = "";
while (num1.isEmpty()) {
System.out.print("Write a number (q to quit): ");
// Making use of the Scanner#nextLine() method
num1 = sc.nextLine();
// Has 'q' been supplied to Quit?
if (num1.equalsIgnoreCase("q")) {
return;
}
/* Validate the fact that a signed or unsigned Integer or
Floating Point value has been entered. If not show Msg. */
if (!num1.matches("-?\\d+(\\.\\d+)?")) {
System.out.println("Invalid Entry! (" + num1 + ") Try again..."
+ System.lineSeparator());
num1 = ""; // empty num1 so as to re-loop.
}
}
// Retrieve second number...
String num2 = "";
while (num2.isEmpty()) {
System.out.print("Now, write yet another number (q to quit): ");
num2 = sc.nextLine();
if (num2.equalsIgnoreCase("q")) {
return;
}
if (!num2.matches("-?\\d+(\\.\\d+)?")) {
System.out.println("Invalid Entry! (" + num2 + ") Try again..."
+ System.lineSeparator());
num2 = "";
}
}
// Convert the numerical strings to double data type values.
double number1 = Double.parseDouble(num1);
double number2 = Double.parseDouble(num2);
// Display the result.
System.out.println("\nResult: " + num1 +" + " + num2 + " = " + (number1 + number2));
}

Issue with do/while looping

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.

Really confused on where to begin, multiple choice operations?

I have a prompt to "Write a program that performs the following operations: +, -, *, /, % (as defined by Java). Your program should first read the first number, then the operation, and then the second number. Both numbers are integers. If, for the operation, the user entered one of the symbols shown above, your program should perform the corresponding operation and compute the result. After that it should print the operation and the result. If the operation is not recognized, the program should display a message about it. You do not need to do any input validation for the integers."
An example output I'm given is:
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
How can I get started on this? I'm super confused and really new to java! Any help is greatly appreciated.
You generally first want to start reading input from STDIN:
Scanner in = new Scanner(System.in);
Then, I would read all parameters and afterwards perform the computation:
System.out.print("Enter the first number: ");
int left = Integer.parseInt(in.nextLine());
System.out.print("Enter the operation: ");
String operation = in.nextLine();
System.out.print("Enter the second number: ");
int right = Integer.parseInt(in.nextLine());
Now that all input is collected, you can start acting.
int result;
switch(operation)
{
case "+": result = left + right; break;
case "-": result = left - right; break;
case "*": result = left * right; break;
case "/": result = left / right; break;
case "%": result = left % right; break;
default: throw new IllegalArgumentException("unsupported operation " + operation);
}
System.out.println(left + " " + operation + " " + right + " = " + result);
Sounds like we are doing your homework! :) Make sure you learn these things or else it will eventually bite you. You can only delay the inevitable. With that "fatherly advice", here ya go.
First, you need to be able to read input from the console so that you can get the input numbers and operation. Of course, there are whole answers on this already. One link:
Java: How to get input from System.console()
Once you have the input, then you can work with it.
You will need to look at the items entered. They say you don't need to validate the numbers but you need to validate the operation. So look at the operation String variable after you got it from the console and see if it is "equalsIgnoreCase" (or just equals since these symbols don't have uppercase) to each one of the accepted operations. If it isn't equal to any of them then you should print out a message as it says. (Again with System.out.println).
You can then go into some if conditions and actually do the math if the operation equals one of the items. For example:
if(inputOperation.equalsIgnoreCase("+")){
double solution = inputInt1 + inputInt2;
//Need to do for all other operations. I didn't do the WHOLE thing for you.
}else if(NEED_TO_FILL_IN_THIS){
//Need to fill in the operation.
//You will need to have more else if conditions below for every operation
}else{
System.out.println("Your operation of '"+inputOperation+"' did not match any accepted inputs. Accepted input operations are '+','-','%','/' and '*'. Please try again.");
}
System.out.println("Your answer to the equation '"+inputInt1+" "+inputOperation+" "+inputInt2+"' is the following:"+solution);
That should get you started. Let me know if you still need further direction.
I hope that helps!
And to end with some fatherly advice: Again, it sounds like you are doing homework. This is all pretty well documented if you just know how to google. "Java get input from console". Or "Java check if String is equal to another string". Learning how to fish is so much more important than getting the fish. I suggest you do some catchup because if this is your homework and you are unsure then it seems like you are a bit behind. I don't mean to be rude. I am just trying to help you longer term.
Enter the first number: 6
Enter the operation: +
Enter the second number: 10
6 + 10 = 16
Scanner f=new Scanner(System.in)
System.out.print("Enter the first number: ")
int firstNum=f.nextInt();
System.out.println();
System.out.print("Enter the operation: ")
String Op=f.nextLine();
System.out.println();
System.out.print("Enter the Second number: ")
int secNum=f.nextInt();
System.out.println();
int answ=0;
if(Op.equals("+"){
answ=firstNum+secNum;
}else if(.......){
}
hope it helps :)
To read the integers, use a Scanner
public static void main(String [] args)
{
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the first number: ");
int firstNum = stdin.nextInt(); //first number
System.out.println("Enter the operation: ");
String operation = stdin.next(); //operation
System.out.println("Enter the second number: ");
int secondNum = stdin.nextInt(); //second number
doOperation(firstNum, secondNum, operation);
}
public static void doOperation(int firstNum, int secondNum, String operation)
{
if(operation.equals("+")
{
int result = firstNum + secondNum;
}
else if(...)
{
//etc
}
System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result);
}
Here is My Solution
package com.company;
import com.sun.org.apache.regexp.internal.RE;
import java.util.Scanner;
public class Main {
private static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
// write your code here
int First,Second,Resualt;
char operation;
System.out.println("Enter the first number: ");
First=scanner.nextInt();
System.out.println("Enter the operation:");
operation=scanner.next().charAt(0);
System.out.println("Enter the second number :");
Second=scanner.nextInt();
if (operation=='+'){
Resualt=First+Second;
System.out.println(First+" "+"+ "+Second+" = "+Resualt);
}
else if (operation=='-'){
Resualt=First-Second;
System.out.println(First+" "+"- "+Second+" = "+Resualt);
}
else if (operation=='*'){
Resualt=First*Second;
System.out.println(First+" "+"* "+Second+" = "+Resualt);
}
else if (operation=='%'){
Resualt=First%Second;
System.out.println(First+" "+"% "+Second+" = "+Resualt);
}
else {
System.out.println("Error");
}
}
}
Good Luck!!

How to make a program run a second time?

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

Having Problems With do...while Loop

I have a little problem with this do while loop; when I run the program it is working, at least partially, what I mean is first you need to make a choice for convertion from C to F or from F to C and after you enter the values the program stops what I want to do is to keep asking for values until you enter 3. I tried to do it with a do while loop but it is not working so if someone has any ideas I would be grateful. Here is the code:
import java.util.Scanner;
public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}
Like in your other question, here you're scanning for input before prompting the user for input.
You need to remove the second line below:
System.out.println("Conversion table: ");
int choice = input.nextInt();
do
With your code as is, it outputs
Conversion table:
and then blocks waiting for input. Whereas you want it instead to continue into the while loop and output
1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:
Make a choice between 1 - 3
before blocking to scan for input.
As is, if you enter any number at the first block, your program enters the loop and behaves as you wanted. So you're nearly there!
The code does work. the problem is most likely the
int choice = input.nextInt();
before the do
Remove this, and change
choice = input.nextInt();
to
int choice = input.nextInt();
Besides the fact that you have: int choice = input.nextInt(); outside of the loop which is unnecessarily getting input before showing the menu, it seems to all work relatively fine. You can just declare int choice inside the loop where you have choice = input.nextInt(); (ie. just change that to intchoice = input.nextInt();).
I tested your code, and it works fine if you change the line int choice = input.nextInt(); (just before your do{} while() block) into int choice;.
As others have already mentioned, you should not read input before your do{} while() block, since the question has not been asked yet.
you forgot the break; after your default case

Categories

Resources