2015-01-22 3 views
1

내 코드에 대해 질문하고 싶습니다.다중 입력을 요구하는 Java 스캐너

나는 비효율 성과 그것의 난잡함에 대해 사과한다, 나는 여전히 자바를 배우려고 노력하고있다.

System.out.println("Please choose the number corresponding to the operation: "); 
    System.out.println("1 for add,2 for subtract,3 for multiply, 4 for divide, 5 for print, and 6 for exit: "); 

    if (sc.nextInt() == 5) { 
     System.out.println("Your first fraction is: " + num1 + "/" + denom1 + " or in decimal: " + ((float) num1/denom1)); 
     System.out.println("Your second fraction is: " + num2 + "/" + denom2 + " or in decimal: " + ((float) num2/denom2)); 
    } else if (sc.nextInt() == 3) { 
     System.out.println("Multiply: " + (num1 * num2) + "/" + (denom1 * denom2)); 

    } else if (sc.nextInt() == 4) { 
     System.out.println("Divide: " + (num1 * denom2) + "/" + (denom1 * num1)); 

    } else if (sc.nextInt() == 1) { 
     int d = denom1 * denom2; 
     int n1 = num1 * denom2; 
     int n2 = num2 * denom1; 
     System.out.println("Addition: " + (n1 + n2) + "/" + d); 


    } else if (sc.nextInt() == 2) { 
     int d = denom1 * denom2; 
     int n1 = num1 * denom2; 
     int n2 = num2 * denom1; 
     System.out.println("Subtract: " + (n1 - n2) + "/" + d); 
    } 
    else if (sc.nextInt() == 6) { 
     System.exit(0); 
    } 
} 
} 

프로그램을 실행할 때 첫 번째 if 문은 1 번만 입력하면되기 때문에 정상적으로 처리됩니다. 그러나 두 번째 else 문에서 볼 수 있듯이 숫자 3 인 문이 두 개의 입력을 필요로하는 경우 다음 행이 오기 전에 두 번 입력해야합니다. 세 번째 else if 문은 숫자 4이고 다음 행이 표시되기 전에 3 개의 입력이 필요합니다. 내가 이것을 제대로 설명하지 못한다면 미안합니다. 왜 이런 일이 일어나는 지 아는 사람이 있습니까?

int input = sc.nextInt(); 
sc.nextLine(); 
if (input == 5) { 

및 다른 모든 if (sc.nextInt()...) :

답변

2
은 당신의 코드를 변경

.

nextInt은 사용자의 입력을 소비합니다. 따라서 두 번째로 오는 경우 if 입력은 첫 번째 if에 의해 소모됩니다.

은 int 값 다음에 <ENTER>을 사용하는 것이 일반적입니다.

+0

정말 고마워요! 그리고 그래, 나는 다음 번에 환호하는 것을 염두에 두겠다! –

0
  Try to use switch statement. 
    package practice; 
    import java.util.Scanner; 
    public class Stack{ 
    public static void main(String[] args) { 
    Scanner sc=new Scanner(System.in); 
    System.out.println("ENTER THE 2 NUMBERS"); 
    int num1=sc.nextInt(); 
    int num2=sc.nextInt(); 
    System.out.println("ENTER THE CHOICE"); 
    int choice='0'; 
    while(choice!=6) 
    { 
     choice=sc.nextInt(); 
     System.out.println(choice); 
    switch(choice) 
    { 
    case 1: 
     int add=num1+num2; 
     System.out.println("Addition:"+add); 
     break; 
    case 2: 
      System.out.println("Subtract:"); 
     break; 
    case 3: 
      System.out.println("Multiply:"); 
     break; 
    case 4: 
     System.out.println("Divide:"); 
     break; 
    case 5: 
     System.out.println("Your first fraction is:"); 
     System.out.println("Your second fraction is:"); 
     break; 
    case 6: 
     System.exit(0); 
     break; 
    default: 
     System.out.println("LOSER"); 
     break; 
      } 
          }  
    sc.close(); 
       } 
    } 
관련 문제