2017-09-11 11 views
0

나는 자바에 다소 새로운 멍청하다. 나는 계산기를 만들려고 노력하고, 그것이 작동하는지 모든 것을 테스트하지는 않았지만, 문제가 생겼어요. 한 번의 계산을 수행 한 후에 기본 메뉴로 돌아갈 방법을 알아낼 수 없습니다. 마지막 질문을 추가하여 사용자가 종료하거나 메인 메뉴로 계속 돌아가도록합니다. 나는 무엇을 넣어야할지 모르겠다. (whatnow == Y) {wtf 나는 메인 메뉴로 돌아 가기 위해해야만 하는가 ?? }. 그것이 약간 길거나 무엇인가 인 경우에 유감스럽게 여기십시오, 그러나 그들은 진짜로 모두 동일합니다 그래서 계산 thingy 다만 건너 뜀. 어떤 도움을 주셔서 감사합니다. 나는 정말로 자바에 익숙하지 않고 아마도이 코드를 다시 작성해야 할 것이다.자바 코드의 시작으로 돌아 가기 (계산기의 메인 메뉴)

package practice; 

import java.util.Scanner; 

public static void main(String[] args){ 

    Scanner scan = new Scanner(System.in); 

    int choice; 
    int firstnumber; 
    int secondnumber; 
    int result; 
    char whatnow; 

    System.out.println("Welcome to StemCalc Z Edition(Integers only)!"); 
    System.out.println("Made with love and basic Java"); 
    System.out.println("Which math operation would you like to perform?"); 
    System.out.println(""); 
    System.out.println("WARNING: Enter the integer x, press ENTER, then enter y"); 
    System.out.println(""); 
    System.out.println("[1]-Addition (+)"); 
    System.out.println("[2]-Subtraction (-)"); 
    System.out.println("[3]-Multiplication (x)"); 
    System.out.println("[4]-Division (/)"); 
    System.out.println(""); 
    System.out.println("Enter your choice[1-4 or 99]:"); choice = scan.nextInt(); 

    while ((choice < 1 || choice > 4) && choice != 99) { 
     System.out.println("Please enter 1, 2, 3, 4, or 99: "); 
     choice = scan.nextInt(); 
    } 

    if (choice == 1){ 
     System.out.println("Enter two integer to add(x + y)"); 

     firstnumber = scan.nextInt(); 
     secondnumber = scan.nextInt(); 
     result = firstnumber + secondnumber; 

     System.out.println(firstnumber + " + " + secondnumber + " = " + result); 
    } 

    else if (choice == 2) { 
     System.out.println("Enter two integers to subtract(x - y)"); 

     firstnumber = scan.nextInt(); 
     secondnumber = scan.nextInt(); 
     result = firstnumber - secondnumber; 

     System.out.println(firstnumber + " - " + secondnumber + " = " + result); 
    } 

    else if (choice == 3) { 
     System.out.println("Enter two integers to multiply(x * y)"); 

     firstnumber = scan.nextInt(); 
     secondnumber = scan.nextInt(); 
     result = firstnumber * secondnumber; 

     System.out.println(firstnumber + " * " + secondnumber + " = " + result); 
    } 

    else if (choice == 4) { 
     System.out.println("Enter to integers to divide(x/y)"); 

     firstnumber = scan.nextInt(); 
     secondnumber = scan.nextInt(); 

     while (secondnumber == 0) { 
      System.out.println("ERROR-CANNOT DIVIDE TO ZERO! Type another integer:"); 
      secondnumber = scan.nextInt(); 
     } 

     result = firstnumber/secondnumber; 

     System.out.println(firstnumber + "/" + secondnumber + " = " + result); 
     } 

    else if (choice == 99) { 
     System.exit(0); 

    } 

    while (choice !=99) { 
     System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0); 

     if (whatnow == 'Y' || whatnow == 'y') { 

     } 

     if (whatnow == 'N' || whatnow == 'n') { 
      System.exit(0); 
     } 
    } 
} 

}

PS :

`while (choice !=99) { 
      System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0); 

      while(whatnow != 'Y' || whatnow != 'y' || whatnow !='N' || whatnow !='n') { 
    System.out.println("Enter [Y/N] only:"); whatnow = scan.next().charAt(0); 
      } 

      if (whatnow == 'N' || whatnow == 'n') { 
       System.exit(0);` 
+0

이동 모든 코드, 당신은 시작에 복귀해야 할 때 메소드를 호출 한 후

public static void main(String[] args) { calc(); } 

그리고 calc()라는 방법을 만들 수 있습니다. –

+0

저는 멍청 해요, 내가 아는 유일한 방법은 public static void main (String args [])입니다. 지옥, 방법인지 아닌지조차 모르겠다. P – Ubuntu4EVA

+0

예, 그 방법입니다. 그리고 당신은 그것을 좋아하는 다른 사람을 만들어야합니다. 괜찮은 이름을 짓고'메인 '내부에서 불러오고 돌아올 필요가있을 때마다 호출해야합니다.주변에서 충분한 정보가 있어야 대화에서 키워드 검색을하고 무엇을해야하는지 이해할 수 있습니다. –

답변

1

사용자가 N을 삽입 할 때까지 작성한 모든 것을 반복하면됩니다. 그의 마지막 명령 while(true) 루프 내부 그래서 당신이 원하는 모든 넣어 모든이 될 것입니다 : 사용자가 N 또는 n 외에 아무것도 삽입하는 경우

if (whatnow == 'N' || whatnow = 'n') { 
    System.exit(0); 
} 

이 방법은 루프는 메인 메뉴 인쇄에 그를 다시 나타납니다 섹션 에서처럼 choice과 같은 방법으로 whatnow 값에 대한 테스트를 추가해야 할 수도 있습니다.

결과는 다음과 같이 될 것입니다 :

public static void main(String[] args){ 
    char whatnow = 'Y'; 
    Scanner scan = new Scanner(System.in); 

    while (whatnow != 'N' && whatnow != 'n') { 
     int choice = printMenuAndAsk(scan); 

     if (choice == 99) 
      break; 
     else performOperation(choice, scan); 

     System.out.println("Do you want to continue calculating? [Y/N]:"); 
     whatnow = scan.next().charAt(0); 

     while(whatnow != 'N' && whatnow != 'Y' && whatnow != 'n' && whatnow != 'y') { 
      System.out.println("Incorrect answer"); 
      whatnow = scan.next().charAt(0); 
     } 
    } 
    scan.close(); 
} 

public static int printMenuAndAsk(Scanner scan) { 
    int choice; 

    System.out.println("Welcome to StemCalc Z Edition(Integers only)!"); 
    ... 
    System.out.println("Enter your choice[1-4 or 99]:"); 
    choice = scan.nextInt(); 

    while ((choice < 1 || choice > 4) && choice != 99) { 
     System.out.println("Please enter 1, 2, 3, 4, or 99: "); 
     choice = scan.nextInt(); 
    } 

    return choice; 
} 

public static void performOperation(int operation, Scanner scan) { 
    System.out.println("Enter first:"); 
    int firstnumber = scan.nextInt(); 
    System.out.println("Enter second:"); 
    int secondnumber = scan.nextInt(); 

    if (choice == 1) 
     System.out.println(firstnumber + " + " + secondnumber + " = " + (firstnumber+secondnumber)); 
    else if (choice == 2) 
     System.out.println(firstnumber + " - " + secondnumber + " = " + (firstnumber-secondnumber)); 
    else if (choice == 3) 
     System.out.println(firstnumber + " * " + secondnumber + " = " + (firstnumber*secondnumber)); 
    else if (choice == 4) { 
     while (secondnumber == 0) { 
      System.out.println("ERROR-CANNOT DIVIDE TO ZERO! Type another integer:"); 
      secondnumber = scan.nextInt(); 
     } 
     System.out.println(firstnumber + "/" + secondnumber + " = " + (firstnumber/secondnumber)); 
    } 
} 
+0

whatnow! = 'Y'work? 루프가 값이 Y 또는 N인지 확인하려면? 그렇다면 Y에 대한 if 문이 필요합니까? – Ubuntu4EVA

+0

내 변경 사항을 검토 할 수 있습니까? 원래 질문을 수정했습니다. – Ubuntu4EVA

+0

'what (whatnow! = 'N'&&nownow! = 'Y') {System.out.println ("Incorrect answer"); whatnow = scan.next(). charAt (0);}'. 이 작업이 끝나면'whatnow'는 'N'(이 경우에는 종료) 또는 'Y'(이 경우에는 루프가 끝났기 때문에 아무 것도 할 필요가 없습니다.) 우리가 끝났기 때문에 –

0

대신에 while 루프를 넣어 노력 : 나는 처음에 동안 (사실)와 같은 것을보고 말을 편집 끝까지 코드 전체를 while(true) 블록에 넣으십시오. 마지막에 if 문을 사용하여 사용자가 계속하지 않을지 여부를 묻습니다. break 키워드를 사용하여 루프를 종료합니다. 다음과 같이 종료하십시오 :

if(input == 'n'){break;} 

이것이하는 일은는 while 루프를 종료한다는 것입니다. while 블록 외부에서 더 많은 명령어를 실행할 수 있습니다.

+0

Java를 처음 사용한다고 명시한 것처럼 함수를 사용하지 말았습니다. –

+0

마지막에 if 문을 예로들 수 있습니까? 나는 다른 사람들이 잠시 (진실한) 것을 두는 것을 보았고 나중에 그것을 거짓으로 만들거나 그런 것을 만들었다. 하지만 내가 의도 한대로 작동합니까? 계산 후 종료하거나 계속할지 여부를 사용자에게 묻습니다. – Ubuntu4EVA

+0

업데이트 된 답변이 도움이됩니까? –

0

당신은 그것을 바꿀 수 :

public static void main(String[] args){ 

    ... 

    while(true){ 
     System.out.println("Welcome to StemCalc Z Edition(Integers only)!"); 

     ... 

     while (choice !=99) { 
      System.out.println("Do you want to continue calculating? [Y/N]:"); whatnow = scan.next().charAt(0); 

      //insert some loop to ensure that the value of whatnow will be either Y or N 

      if (whatnow == 'N' || whatnow == 'n') { 
       System.exit(0); 
      } 
     } 
    } 
} 

편집 여기

것은 내 마지막 코멘트와 함께 예상 무엇의 샘플 코드 다음과 같이하십시오 :

주요 방법 같은 : 다른 방법으로

public static void calc() { 

     Scanner scan = new Scanner(System.in); 

     //the rest of your code 

} else if (choice == 99) { 
      System.exit(0); 

     } 

     calc(); //call the method again at the end of your code 
       //remove your while loop 

    } 
+0

글쎄, 실제로.'calc()'내부에서'calc()'를 호출하면 결국 StackOverflowError가 발생합니다. 루프는 여전히 이것에 대한 멋진 추가 사항입니다. –

+0

예, 결국 OP가 변형 될 수 있습니다. – notyou