2012-07-27 3 views
0

저는 초보자이며 while 회 돌이에서 if 문을 중첩 시키려고 실험하고있었습니다. 이 방법으로 기본 계산기를 만들었지 만 약간의 문제가 있습니다. 나는 먼저 코드를 공유하고 나서 내 문제를 제기 할 것이다. 여기 자바 "if 문"에 문제가 있습니다.

코드입니다 : 당신이 마지막에 입력 fnumsnum

을 처리 할 변수 method을 요청 것을 볼 수

import java.util.Scanner; 
class whileloop{ 
    public static void main(String args[]){ 
     Scanner scan = new Scanner(System.in); 
    System.out.println("This is a basic calculator."); 
    System.out.println("To exit, input exit when asked to input the method."); 
    System.out.println("----------------------------------------------"); 
    while (true){ 
     System.out.println("to add, input '+', to subtract, input '-', to divide, input '/', to multiply, input '*' and to exit, input 'exit.'"); 
     System.out.println("----------------------------------------------------"); 
     System.out.print("Please enter a method here:"); 
     String method = scan.nextLine(); 
     if (method.equals("exit")){ 
      System.out.println("You chose to exit."); 
      break; 
     } 
     else if (method.equals("+")){ 
      System.out.println("You chose to add."); 
      System.out.print("Please enter first number here:"); 
      double fnum = scan.nextInt(); 
      System.out.print("Please enter second number here:"); 
      double snum = scan.nextInt(); 
      double ans = fnum + snum; 
      System.out.print("The answer is"); 
      System.out.println(ans); 
     } 
     else if(method.equals("-")){ 
      System.out.println("You chose to subtract."); 
      System.out.print("Please enter first number here:"); 
      double fnum = scan.nextInt(); 
      System.out.print("Please enter second number here:"); 
      double snum = scan.nextInt(); 
      double ans = fnum - snum; 
      System.out.print("The answer is"); 
      System.out.println(ans); 
     } 
     else if(method.equals("*")){ 
      System.out.println("You chose to multiply."); 
      System.out.print("Please enter first number here:"); 
      double fnum = scan.nextInt(); 
      System.out.print("Please enter second number here:"); 
      double snum = scan.nextInt(); 
      double ans = fnum * snum; 
      System.out.print("The answer is"); 
      System.out.println(ans); 
     } 
     else if(method.equals("/")){ 
      System.out.println("You chose to divide."); 
      System.out.print("Please enter first number here:"); 
      double fnum = scan.nextInt(); 
      System.out.print("Please enter second number here:"); 
      double snum = scan.nextInt(); 
      double ans = fnum/snum; 
      System.out.print("The answer is"); 
      System.out.println(ans); 
     } 
     else{ 
      System.out.println("Invalid input. please select a valid input from the list of operators given."); 
     } 
    } 
} 
} 

, 내가 else 문을 추가했다. 작동을 위해 유효한 method을 입력하지 않을 때이를 사용자에게 알려야합니다.

문제 나 사정이 코드를 실행할 때마다 내가 입력 method대로 제 완벽 작동 후 fnumsnum 후 출력 응답하지만 요청할 무엇이다, 또한 코드의 블록을 실행 else 문에서.

어떻게 방지합니까? 도와주세요! (. 난 그냥 조금 더 조직 보이게하기 위해 코드 블록에 넣어) 우리가 숫자를 입력 할 때마다

to add, input '+', to subtract, input '-', to divide, input '/', to multiply, input '*'   and to exit, input 'exit.' 
---------------------------------------------------- 
Please enter a method here:+ 
You chose to add. 
Please enter first number here:10 
Please enter second number here:10 
The answer is20.0 
to add, input '+', to subtract, input '-', to divide, input '/', to multiply, input '*'  and to exit, input 'exit.' 
---------------------------------------------------- 
Please enter a method here:Invalid input. please select a valid input from the list of  operators given. 
to add, input '+', to subtract, input '-', to divide, input '/', to multiply, input '*' and to exit, input 'exit.' 
---------------------------------------------------- 
Please enter a method here: 
+3

이 질문은 여러 번 묻습니다. nextInt 다음에 nextLine을 사용할 때 ['스캐너 문제] (http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextint)를보십시오. –

답변

2
use scan.nextLine() immediately after scan.nextInt(). 

:

또한,이 출력의 종류 내가 얻을입니다 Enter 키를 누르면 scan.nextInt()는 "end of line"이 아닌 숫자 만 읽습니다. 우리가 scan.nextLine()을 할 때; 첫 번째 입력에서 여전히 버퍼에있는 "end of line (\ n)"을 읽습니다. 계산 후

import java.util.Scanner; 
class whileloop{ 
    public static void main(String args[]){ 
     Scanner scan = new Scanner(System.in); 
    System.out.println("This is a basic calculator."); 
    System.out.println("To exit, input exit when asked to input the method."); 
    System.out.println("----------------------------------------------"); 
    while (true){ 
     System.out.println("to add, input '+', to subtract, input '-', to divide, input '/', to multiply, input '*' and to exit, input 'exit.'"); 
     System.out.println("----------------------------------------------------"); 
     System.out.print("Please enter a method here:"); 
     String method = scan.nextLine(); 
     if (method.equals("exit")){ 
      System.out.println("You chose to exit."); 
      break; 
     } 
     else if (method.equals("+")){ 
      System.out.println("You chose to add."); 
      System.out.print("Please enter first number here:"); 
      double fnum = scan.nextInt(); 
     scan.nextLine(); 
      System.out.print("Please enter second number here:"); 
      double snum = scan.nextInt(); 
     scan.nextLine(); 
      double ans = fnum + snum; 
      System.out.print("The answer is"); 
      System.out.println(ans); 
     } 
     else if(method.equals("-")){ 
      System.out.println("You chose to subtract."); 
      System.out.print("Please enter first number here:"); 
      double fnum = scan.nextInt(); 
     scan.nextLine(); 
      System.out.print("Please enter second number here:"); 
      double snum = scan.nextInt(); 
     scan.nextLine(); 
      double ans = fnum - snum; 
      System.out.print("The answer is"); 
      System.out.println(ans); 
     } 
     else if(method.equals("*")){ 
      System.out.println("You chose to multiply."); 
      System.out.print("Please enter first number here:"); 
      double fnum = scan.nextInt(); 
     scan.nextLine(); 
      System.out.print("Please enter second number here:"); 
      double snum = scan.nextInt(); 
     scan.nextLine(); 
      double ans = fnum * snum; 
      System.out.print("The answer is"); 
      System.out.println(ans); 
     } 
     else if(method.equals("/")){ 
      System.out.println("You chose to divide."); 
      System.out.print("Please enter first number here:"); 
      double fnum = scan.nextInt(); 
     scan.nextLine(); 
      System.out.print("Please enter second number here:"); 
      double snum = scan.nextInt(); 
     scan.nextLine(); 
      double ans = fnum/snum; 
      System.out.print("The answer is"); 
      System.out.println(ans); 
     } 
     else{ 
      System.out.println("Invalid input. please select a valid input from the list of operators given."); 
     } 
    } 
} 
} 
+0

감사합니다. 왜 이런 일이 일어 났는지 말해 주실 래요? 나는 그 원인을 안다면 쉽게 암기 할 수 있습니다. –

+1

@user 숫자를 입력하고 Enter 키를 누를 때마다 scan.nextInt()는 "end of line"이 아닌 숫자 만 읽습니다. 우리가 scan.nextLine()을 할 때; 첫 번째 입력에서 여전히 버퍼에있는 "end of line (\ n)"을 읽습니다. –

+0

오케이! 엄청 고마워! 이 문제는 문자 그대로 내 뇌를 먹고있었습니다. –

1

String method = scan.nextLine(); 반환 "". 빈 문자열이 if 문 중 어느 것과도 일치하지 않으므로 else이 계산됩니다.

+0

하지만 왜 이런 일이 발생합니까? 변수에 값을 저장하지 않았습니까? 다음 루프에서 수정할 때까지 비워 두어서는 안됩니다. –

0

이는 scan.nextLine()이 계산 후 ""을 반환하기 때문입니다. 그래서이 줄을 추가하면됩니다.

 System.out.println("to add, input '+', to subtract, input '-', to divide, input '/', to multiply, input '*' and to exit, input 'exit.'"); 
    System.out.println("----------------------------------------------------"); 
    System.out.print("Please enter a method here:");   
    String method = scan.nextLine(); 
    // add this line 
    if (method.equals("")) 
    { 
     continue; // no "" will be there 
    }