Exiting a program with System.exit(0) in java - java

I am a little confused about how to implement System.exit(0); in my program. What I want to have happen is for the user to type the word "exit" and for the program to terminate. I would also like the program to return "0.0" when "clear" is entered, but I think I am having trouble working with my variables because num1 and num2 are doubles but I want "exit" and "clear" to be acceptable inputs, as well.
If anyone has any insight, that would be greatly appreciated. Here is my code:
package projectapcs;
/**
*
* #author Apple
*/
import java.util.Scanner;
public class ProjectAPCS {
public static void exit(int x){
}
public static void clear(int y){
}
public static void main(String[] args) {
double num1;
double num2;
char char1;
String operation;
Scanner input = new Scanner(System.in);
System.out.println
("Enter 'exit' to quit the calculator, 'help' for more options or 'continue' to use the calculator");
System.out.println
("\nEnter the first number:");
num1 = input.nextInt();
System.out.println
("Display:" + num1);
System.out.println("Please enter operation:");
operation = input.next();
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
if ("+".equals(operation)){
System.out.println((num1 + num2));
}
else if ("-".equals(operation)){
System.out.println((num1 - num2));
}
else if ("/".equals(operation)){
System.out.println((num1 / num2));
}
else if ("*".equals(operation)){
System.out.println((num1 * num2));
}
else if ("-x".equals(operation)){
System.out.println (-num1);
}
else if ("x^2".equals(operation)){
System.out.println (num1 * num1);
}
else if ("sqrt".equals(operation)){
System.out.println (Math.sqrt(num1));
}
else if ("H".equals(num1)){
System.out.println("Type + for the addition of values");
System.out.println("Type - for the substraction of values");
System.out.println("Type * for the multiplcation of values");
System.out.println("Type / for the division of values");
System.out.println("Type negate for the negation of values");
System.out.println("Type ^2 for squaring of values");
}
else if("E".equals(num1)){
System.out.println ("Calculator program terminated...");
System.exit(0);
}
}
}

If you want to allow arbitrary inputs, read input as a String, then convert to double as needed:
String input = scanner.next();
if (input.equals("exit")) {
exit();
else if (input.equals("clear")) {
clear();
} else {
try {
double number = Double.parseDouble(input);
/* do something with `number` */
} catch (NumberFormatException e) {
System.err.println("Not a double.");
}
}

Related

Illegal start of expression on my function public static void

My code is about looping and method, A program that will let user either compute an area or use the 4 basic math operations. the (Triangle, Square,Rectangle) with their choice of process: Addition, Subtraction, Multiplication and Division.
I think i properly closed the addition function there and i already check the closing every functions they seem work well other than the addtion function since thats the only error i got.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//WHILE LOOP FOR CHOICES
while(true){//CHOICES LOOP
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("1 - Addition process");
System.out.println("2 - Subtraction process");
System.out.println("3 - Multiplication process");
System.out.println("4 - Division process");
System.out.println("5 - Compute process");
System.out.println("Your choice: ");
int option = scan.nextInt();
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if(option == 1){
Add();
}
else if(option == 2){
Sub();
}
else if(option == 3){
Mul();
}
else if(option == 4){
Div();
}
else if(option == 5){
Com();
}
else if((option>=6)&&(option<=100)){//INVALID
System.out.println("Invalid Input, Please Input Choice Again.");
}
else{//- if user input other number, the program will break and stop from looping
break;
}
Here Im getting a error here im not sure what is it
public static void Add(){
System.out.println("ADDITION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int add1=scan.nextInt();
System.out.println("2nd number: ");
int add2=scan.nextInt();
int addtotal=add1+add2;
if(addtotal>100){// In addition, if the sum is higher than 100, print the answer the word high. if equal and below 100, print low
System.out.println("Total is "+addtotal+" High");
}
else if(addtotal<100){
System.out.println("Total is "+addtotal+" Low");
}
}
public static void Sub(){//SUBTRACTION
System.out.println("SUBTRACTION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int sub1=scan.nextInt();
System.out.println("2nd number: ");
int sub2=scan.nextInt();
int subtotal=sub1-sub2;
if(subtotal<0){// In subtraction, if the difference is negative, print invalid. If 0 or above, print the difference and the word valid.
System.out.println("Invalid ");
}
else if(subtotal>0){
System.out.println("Total is "+subtotal+" Valid");
}
}
public static void Mul(){//MULTIPLICATION
System.out.println("MULTIPLICATION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
double multi1=scan.nextDouble();//In multiplication, make it accepts decimal value
System.out.println("2nd number: ");
double multi2=scan.nextDouble();
double multitotal=multi1*multi2;
System.out.println("Total is "+multitotal);
}
public static void Div(){
System.out.println("DIVISION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int div1=scan.nextInt();
System.out.println("2nd number: ");
int div2=scan.nextInt();
int divtotal= div1 / div2;
int divremainder= div1 % div2;//In division, if it has remainder, print the answer and the remainder.
System.out.println("Total is "+divtotal);
System.out.println("Remainder is "+divremainder);
}
public static void Com(){// If user choose 5, the user needs to choose again on a ,b or c. If other letter, print invalid and then go pack on choosing of process.
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("a - Rectangle");
System.out.println("b - Square");
System.out.println("c - Triangle");
System.out.println("Your choice: ");
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
char choice = Keyboard.nextLine().charAt(0);
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if (choice == 'A' || choice == 'a')//rectangle
{
System.out.println("Enter length of rectangle's base: ");
double base = input.nextDouble();
System.out.println("Enter length of rectangle's height: ");
double height = input.nextDouble();
double rArea = base * height;
System.out.println("The area of a rectangle with a base length of " + base + " and a height of " + height + " is " + rArea + ".");
}
else if (choice == 'B' || choice == 'b') //square
{
System.out.println("Enter length of square's sides: ");
double sSide = input.nextDouble();
double sArea = sSide * sSide;
System.out.println("The area of a square with a side length of " + sSide + " is " + sArea + ".");
}
else if (choice == 'C' || choice == 'c') //traingle
{
System.out.println("Enter traingle's side length: ");
double tSide = input.nextDouble();
double tArea = tSide * tSide * tSide;
System.out.println("The area of a triangle with a side length of " + tSide + " is " + tArea + ".");
}
else //invalid
{
System.out.println("You've entered an invalid character.");
}
}
}
You haven't got a closing brace for your main method

Java try-catch inside of a do-while loop

In my Java code shown below, I'm accepting user input of two doubles, and wrapping those values in a try-catch that handles an InputMismatchException. I've also wrapped a do-while loop around this try-catch block. I'm trying to craft the code in a way that handles the case where if a user inputs the wrong type for "number2", then the loop doesn't start over and ask the user to input "number1" all over again. I've been scratching my head on the best way to implement this and am open to any feedback or suggestions.
So the test case would be; the user inputs the right type for number1, but the wrong type for number2, in which case, how can I implement the code so that it only asks for re-entry of number2 instead of re-starting the entire loop. I've tried nested try-catch, nested do-whiles, etc. Any thoughts?
import java.util.InputMismatchException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter your first number: ");
double number1 = input.nextDouble();
System.out.print("Enter your second number: ");
double number2 = input.nextDouble();
System.out.println("You've entered the numbers " + number1 + " " + number2);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
} while (continueInput);
}
}
You can extract method which takes Supplier
private <T> T executeWithRetry(String initialText, String retryText, Supplier<T> supplier) {
System.out.println(initialText);
while (true) {
try {
return supplier.get();
} catch (InputMismatchException ex) {
System.out.println(retryText);
}
};
}
And use it like
double number1 = executeWithRetry(
"Enter your first number: ",
"Try again, a double is required.",
() -> input.nextDouble()
)
Just split the process of reading the 2 values apart. This way you can individually check if an InputMismatchException occurs and handle it individually for each variable.
continueInput = false;
do {
try {
System.out.print("Enter your first number: ");
double number1 = input.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
continueInput = true;
}
} while (continueInput);
continueInput = false;
do {
try {
System.out.print("Enter your second number: ");
double number2 = input.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
continueInput = true;
}
} while (continueInput);
try this,
Scanner input = new Scanner(System.in);
boolean continueInput = true;
double number1 = 0;
while (continueInput) {
try {
System.out.print("Enter your first number: ");
number1 = input.nextDouble();
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
}
continueInput = true;
double number2 = 0;
while (continueInput) {
try {
System.out.print("Enter your second number: ");
number2 = input.nextDouble();
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
}
System.out.println("You've entered the numbers " + number1 + " " + number2);

A simple console calculator

I have designed a simple console calculator as follows but i need to create a loop where I can re run the program:
So that I won't need to run the program again and again and it can take the input from the user and run by itself.
private static Scanner op;
private static Scanner input;
private static Scanner cont;
public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;
input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1= input.nextDouble();
System.out.println("Please input the second numer:");
num2= input.nextDouble();
op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();
if (operation.equals("+")){
System.out.println("Your Result is :" + (num1+num2));
}
if (operation.equals("-")){
System.out.println("Your Result is:" + (num1-num2));
}
if (operation.equals("/")){
if (num2 == 0){
System.out.println("Your Input is Invalid");}
else {
System.out.println("Your result is :" + (num1/num2));
}
}
if (operation.equals("*")){
System.out.println("Your result is:" + (num1*num2));
}
if (operation.equals("%")){
System.out.println("Your result is:" + (num1*100/num2));
}
if (operation.equals("^")){
ans= Math.pow(num1, num2);
System.out.println("Your result is:"+ans);
}
if (operation.equals("log")){
l1=Math.log(num1);
l2=Math.log(num2);
System.out.println("Your result is:"+l1/l2);
}
operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
if (operation.equals("Yes")){
else{
System.out.println("Thank You");
}
}
}
you can create a function and call it with a loop like this:
private static void myfunction(){
//put your code here
}
public static void main(String[] args) {
//call your function until your condition is false
while(myconditionistrue){
myfunction();
}
}
if you want to ask your user if continue or not use this way:
private static void myfunction() {
//put your code here
}
public static void main(String[] args) {
String exit;
Scanner scan = new Scanner(System.in);
do {
//call your function or you can put all your code here
myfunction();
System.out.println("You want to continue? y : n :");
exit = scan.next();
} while (exit.equals("y"));
}
You can use a while(true) and then just exit at command:
import java.util.Scanner;
class Main {
private static Scanner op;
private static Scanner input;
private static Scanner cont;
public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;
while (true) {
input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1 = input.nextDouble();
System.out.println("Please input the second numer:");
num2 = input.nextDouble();
op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();
if (operation.equals("+")) {
System.out.println("Your Result is :" + (num1 + num2));
}
if (operation.equals("-")) {
System.out.println("Your Result is:" + (num1 - num2));
}
if (operation.equals("/")) {
if (num2 == 0) {
System.out.println("Your Input is Invalid");
} else {
System.out.println("Your result is :" + (num1 / num2));
}
;
}
if (operation.equals("*")) {
System.out.println("Your result is:" + (num1 * num2));
}
if (operation.equals("%")) {
System.out.println("Your result is:" + (num1 * 100 / num2));
}
if (operation.equals("^")) {
ans = Math.pow(num1, num2);
System.out.println("Your result is:" + ans);
}
if (operation.equals("log")) {
l1 = Math.log(num1);
l2 = Math.log(num2);
System.out.println("Your result is:" + l1 / l2);
}
//cont = new Scanner(System.in);
//operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
cont = new Scanner(System.in);
operation = cont.next();
if (operation.equals("Yes")) {
} else {
System.out.println("Thank You");
System.exit(0);
}
}
}
}
Test
Please input your first number:
5
Please input the second numer:
5
Select your operation:
*
Your result is:25.0
Do you wish to perform any other operation?
Yes
Please input your first number:
20
Please input the second numer:
10
Select your operation:
+
Your Result is :30.0
Do you wish to perform any other operation?
No
Thank You
As RealSkeptic stated in his comment, what you need is a loop. You can learn about loops, for example, here. The best choice for this situation is do-while loop.
I have a few more advices to your code:
You don't need to create many scanners to get more inputs than just one. One instance suffices.
When you use many if statements whose conditions are disjoint (by that I mean that if a single condition is true then the rest of the conditions is false), use else-if statements. It is more efficient. See this for more information.
Don't use empty branches in if statement. In this particular example, you can use if (!operation.equals("Yes")). The exclamation mark means negation. So if operation equals "Yes", the whole condition is evaluated as false.
Learn how to divide a complex code into functions (or methods). Generally, one function should provide one simple functionality.

try catch placement issue within program design?

I've put in the try catch as shown now the program still skips to the 2nd & 3rd input question without printing the error exception after ("Enter your operation: add, subtract, divide, multiply, or exit"). Also if "exit" is inputed for first question the the 2nd & 3rd input requirements still loop before program finishes, is there any way to exit immediately as prompted with the other inputs being required?
Any suggestions welcome
import java.util.Scanner;
import java.io.*;
class Monday {
public static void main(String[] args) {
double n1,n2;
boolean check = true;
while(check) {
System.out.println("Enter your operation: add, subtract, divide, multiply, or exit");
Scanner myScan = new Scanner(System.in);
String op = myScan.next();
try {
System.out.println("Enter your 1st number");
try {
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();
} catch (Exception e) {
System.out.println("This is my error");
return;
}
/* System.out.println("Enter your 1st number");
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();*/
switch (op) {
case"add":
System.out.println("Your answer is "+ (n1 + n2));
break;
case"subtract":
System.out.println("Your answer is "+ (n1 - n2));
break;
case"divide":
System.out.println("Your answer is "+ (n1 / n2));
break;
case"multiply":
System.out.println("Your answer is "+ (n1 * n2)) ;
break;
case"exit":
System.out.println("Goodbye!");
break;
}
if ("exit".equals(op))
check = false;
} catch (Exception e) {
System.out.println("This is my error");
System.exit(1);
}
}
}
}
You don't even need try/catch.
double n1, n2;
System.out.println("Enter your 1st number");
if (myScan.hasNextDouble()) n1 = myScan.nextDouble();
else return;
System.out.println("Enter your 2nd number");
if (myScan.hasNextDouble()) n2 = myScan.nextDouble();
else return;
But if you want to use it:
double n1, n2;
System.out.println("Enter your 1st number");
try {
n1 = myScan.nextDouble();
System.out.println("Enter your 2nd number");
n2 = myScan.nextDouble();
} catch (Exception e) {
System.out.println("This is my error");
return;
}

Basic Java Calcualtor: Only addition working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to build a simple calculator that operates on Double values and performs:
+
-
*
/
negation
^2
for some reason, whichever operation i specify when running the program executes the addition function. So when I try to do
5
7
*
I get 12.0 and not 35.
Any suggestions?
I would also really like some help implementing a way to quit this program when the word "exit" is entered. I was thinking something like System.exit(0);
but Im not sure how to implement. this is my code so far:
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation == "+");
{
System.out.println((num1 + num2));
}
if (operation == "-"){
{
System.out.println((num1 - num2));
}
if (operation == "/"){
{
System.out.println((num1 / num2));
}
if (operation == "*"){
{
System.out.println((num1 * num2));
}
}
}
there is a semicolon at if (operation.equals("+"));
so, System.out.println((num1 + num2)); will always work
And also replace, == with .equals("+")
as == checks for reference, while equals checks for the value of the variable.
please change operation == to operation.equals("your value")
There are at least three main issues with your code...
Firstly, String comparison in Java is done using .equals not ==
Secondly...
if (operation == "+");
Has a semi-colon at the end, which basically means that even if the condition is meet, it will not run anything, but will skip to the next execution block, which is ...
{
System.out.println((num1 + num2));
}
Thirdly, you have an extra open brace ({) here...
if (operation == "-"){
{
Here...
if (operation == "/"){
{
And here...
if (operation == "*"){
{
Which is going to completely screw up your logic
You should also make use of else-if blocks as well...
Instead, try something like...
if ("+".equals(operation))//;
{
System.out.println((num1 + num2));
}
else if ("-".equals(operation)) //{
{
System.out.println((num1 - num2));
}
else if ("/".equals(operation)) //{
{
System.out.println((num1 / num2));
}
else if ("*".equals(operation)) //{
{
System.out.println((num1 * num2));
}
I've commented out the problem areas so you can see where they exists before hand
try this way
Instead of using == use .equals()
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation.equals("+"))
{
System.out.println((num1 + num2));
}
if (operation.equals("-"))
{
System.out.println((num1 - num2));
}
if (operation.equals("/")){
{
System.out.println((num1 / num2));
}
if (operation.equals( "*")){
{
System.out.println((num1 * num2));
}
}
}

Categories