저는 마침내 (거의) 제가 작업해온 작은 계산기 프로젝트로 끝났습니다. 현재는 복식의 더하기, 빼기, 곱하기, 나누기, 수정, 제곱 및 부정으로 작동하고 "종료", "지우기"및 "도움말"과 같은 일부 문자열에 응답합니다.try & catch 블록 구현
사용자가 콘솔에 "첫 번째 숫자 입력"또는 "두 번째 입력"이라고 표시된 후 숫자가 아닌 것을 입력 할 때마다 "잘못된 입력"과 같은 콘솔에서 메시지를 반환하는 데 try and catch 블록을 구현하는 데 도움이 필요합니다. 번호".
나는 몇 가지 다른 방법으로 엉망으로 만들었지 만 아무 것도 작동하지 않는 것 같습니다. 조언 크게 감사하겠습니다. 코드 :
import java.util.Scanner;
public class exit {
static double num1;
static double num2;
static String operation;
public static void main(String[] args) {
boolean run = true;
while (run) {
System.out.println(" Enter: \n \b help for all usable operations \n continue to use the calculator");
Scanner input = new Scanner(System.in);
String str1 = input.next();
if (str1.equals("exit")) {
System.exit(0);
} else if (str1.equals("clear")) {
System.out.println("0.0");
} else if (str1.equals("help")) {
System.out.println("please enter:\n + for addition \n - for subtraction \n * for multiplication \n/for division \n -x for negation \n x^2 for squaring\n % for mod \n remember to only input integer or double values\n");
} else if (str1.equals("continue")) {
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));
}
}
}
}
}
왜 그런 시도가 필요합니까? 당신은'if'에서만 숫자를 확인하거나 입력 문자를 정수로 설정할 수 있습니다 – user2377971
http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner –