here's some code I wrote in java SE to get use to if statements and scanning. just looking for suggestions that will improve this program or/and teach me techniques that I should get use to using.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.print("Enter the first value ");
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
System.out.print("Enter the next value ");
int y = scan.nextInt();
System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");
int z = scan.nextInt();
if (z == 1) {
int a = x * y;
System.out.println("Result: " + a);
}//end of if multiply
else if (z == 2) {
int a = x / y;
System.out.println("Result: " + a);
}//end of if divide
else if (z == 3) {
int a = x + y;
System.out.println("Result: " + a);
}// end of if add
else {
int a = x-y;
System.out.println("Result: " + a);
} //end of is subtract
}// End of main
}// End of public class
here's my new program, still not perfect but the class i'm taken hasn't even gone over data types and classes yet so i'm already ahead lol Thank you every one for your help!
import java.util.Scanner;
public class Calculatortwo {
public static void main(String[] args) {
//get imput values from user
System.out.print("Enter the first value ");
Scanner scan = new Scanner(System.in);
double x = scan.nextDouble();
System.out.print("Enter the next value ");
double y = scan.nextDouble();
System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");
int operation = scan.nextInt();
//calculator logic
double result = 0;
switch (operation) {
case 1:
result = x * y;
break;
case 2:
if(y != 0) {
result = x / y;
}
else {
System.out.println("Error: Divide by 0");
}
break;
case 3:
result = x + y;
break;
case 4:
result = x - y;
break;
default:
System.out.println("Error: operation not found");
}
System.out.println("Result: " + result);
}
}
if
statements, and if you scroll to the end of the code block, you may notice that in contrast to, say, SO, CR "closing code fences" still need a newline to follow it. \$\endgroup\$ – greybeard Jan 20 at 6:58