사용자가 입력 한 내용에 + 기호가 있으면이 프로그램이 두 피연산자를 올바르게 실행할 수 있도록 만들고 싶습니다. 또한 사용자가 종료 할 때마다 프로그램을 종료 할 수 있도록하고 싶지만 첫 번째 줄에서 끝나면 작동합니다. 초보자 프로그래밍, 그래서 nooby 실수에 미리 사과.내 Java 콘솔 계산기에서 추가 기능이 작동하지 않는 이유는 무엇입니까? 그리고 어떻게 프로그램을 종료 할 때 "quit"명령을 항상 작동하게 할 수 있습니까?
package javaapplication59;
import java.util.Scanner;
public class JavaApplication59 {
public static void main(String[] args) {
System.out.println("This is a calculator of singular expressions.");
calculator();
}
public static void calculator() {
System.out.println("Enter an expression, or type \"quit\" to exit.\n");
Scanner kbd;
kbd = new Scanner(System.in);
System.out.println();
String text = kbd.nextLine();
while (!text.equalsIgnoreCase("quit")) {
Scanner tokens = new Scanner(text);
if (tokens.hasNextInt()) {
twoOperand(tokens);
} else {
oneOperand();
}
}
System.out.println("Farewell");
System.exit(0);
}
public static void twoOperand(Scanner tokens) {
int firstNum = tokens.nextInt();
String operator = tokens.next();
int secondNum = 0;
if (tokens.hasNextInt()) {
secondNum = tokens.nextInt();
} else {
System.out.println("Error, not valid expression");
calculator();
}
while (tokens.next().contains("+")) {
addition();
}
while (tokens.next().contains("-")) {
subtraction();
}
while (tokens.next().contains("*")) {
multiplication();
}
while (tokens.next().contains("/")) {
division();
}
while (tokens.next().contains("%")) {
modulus();
}
while (tokens.next().contains("^")) {
exponentiation();
}
}
public static void oneOperand() {
}
public static void addition() {
Scanner tokens;
tokens = new Scanner(System.in);
String name = tokens.next();
int sum = 0;
while (tokens.hasNextInt()) {
int num = tokens.nextInt();
sum += num;
System.out.println(sum);
calculator();
}
}
}
당신은 아마 당신의 첨가 방법은 값을 반환합니다. 또한 추가 반복자 내부에서 계산기를 호출하고 while 루프에서 피연산자 함수를 호출합니다. 왜? 이 코드의 80 %는 복잡하지 않아도됩니다. 이것은 생각보다 훨씬 간단합니다. – G2M
첫 번째 숫자, 연산자 및 두 번째 숫자를 변수에 넣으면 ... 이미 호출 한 연산자를 얻기 위해'next'를 다시 호출하면 NoSuchElementException이 발생합니다. –