Я внедрил калькулятор, однако я только хочу, чтобы пользователь мог выбрать два варианта и затем закрыть программу. Мой код имеет пользовательский цикл по каждой операции. Я бы хотел, чтобы пользователь выбрал число от 1 до 6 и выполнил выбранную операцию. Также, если кто-то знает, как заставить программу выйти, если он нажмет 0 в меню, это будет фантастически.
import java.util.*;
public class Calculator
{
private int option = -1; // option is initially not 0
to 6
private Scanner scan; // we’ll use scan to read input
// constructor for class
public Calculator()
{
System.out.println ("java Homework1");
System.out.println ("Welcome to Math Calculator!");
System.out.println ("Please choose an option:");
System.out.println (" ");
System.out.println ("1 - add two real numbers");
System.out.println ("2 - subtract two real numbers");
System.out.println ("3 - multiply two real numbers");
System.out.println ("4 - divide two real numbers");
System.out.println ("5 - get the factorial of an
number");
System.out.println ("6 - menu");
System.out.println ("0 - exit");
scan = new Scanner(System.in); // creates scan
}
// entry point for class
public void run()
{
// stick code for calculator in here...may want to
create
// other functions to make code more readable
int selection1;
Scanner first = new Scanner(System.in);
selection1 = first.nextInt();
if (selection1 == 1);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
+ secondnum));
}
if (selection1 == 2);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
- secondnum));
}
if (selection1 == 3);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
* secondnum));
}
if (selection1 == 4);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
/ secondnum));
}
if (selection1 == 5);
System.out.println ("Enter the number you would
like the factorial of: ");
int factorialnum = scan.nextInt();
int i,start = 1;
for (i = 1; i <= factorialnum;i++)
{
start = start*i;
}
System.out.println ("your answer is: " + start);
}
}