2014-10-06 1 views
-1

내 교수는 소수 "소수점"을 쓸 수 있도록 지정했습니다. 숫자가 소수 또는 소수 인 경우 입력 한 숫자가 표시되는 곳에 다음 소수를 표시하십시오. 그는 잘못된 입력이 입력되면 오류 메시지를 표시하기를 원합니다. 음의 정수 부분은 간단하지만 문자 입력을 파악할 수는 없다고 생각했습니다. 또는 문자가 숫자가 아닌 경우. 어떻게 숫자가 아닌 입력을 차단합니까?숫자가 아닌 입력을 거부하는 방법은 무엇입니까?

또한 시스템은 3 개의 연속적인 잘못된 입력을 종료해야합니다. 카운터를 어떻게 재설정합니까? 내가 프로그램을 작성한 방법, 사용자가 두 개의 오류를 만들었지 만 다음 오류가 허용되면 다른 오류가 발생합니다. (따라서 연속적이지 않습니다.) 프로그램이 닫힙니다. 이것은 내가 처음으로 프로그래밍하는 과정이므로 잘 알지 못합니다. 어떤 도움이라도 대단히 감사하겠습니다.

또한 스캐너와 두 가지 방법을 사용해야합니다.

/** 
* 
* @param n 
* @return 
*/ 
public static boolean isPrime(int n) { 

    for (int i = 2; i < n; i++) { 
     if (n % i == 0) { 
      return false; 
     } 
    } 

    return true; 
} 



public static int nextPrime(int n) { 
    n++; 
    isPrime(n); 
    while (isPrime(n) == false) { 
     n++; 
     isPrime(n); 
    } 
    int prime = n; 
    return prime; 
} 


/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    // TODO code application logic here 

    int answer = 2; 
    int counter = 1; 

    boolean playAgain = false; 

    Scanner input = new Scanner(System.in); 

    Scanner reader = new Scanner(System.in); 

    Scanner in = new Scanner(System.in); 

    do { 
     //ask for input 
     System.out.print("\nEnter the integer value-> "); 

     //input answer 
     int n = input.nextInt(); 

     { 
      //decide is negative 
      while (n < 0){ 
       //count counter 
       counter++; 
       //give error message 
       System.out.println("\nInvalid Input! Stike!"); 

       //ask for input 
       System.out.print("\nEnter the integer value-> "); 

       //input answer 
       n = input.nextInt(); 


      //decide is character 
      // if (n != '.'){ 
       //count counter 
       // counter++; 

       //give error message 
       // System.out.println("\nInvalid Input! Strike!"); 
      // } 

      //decide if count three errors 
      if (counter == 3){ 

      //display three errors message 
      System.out.println("Three Strikes! You're Out!"); 
      //close program 
      System.exit(0); 
     } 
      } 

     //decide if prime 
     if (isPrime(n)) { 

      //display prime answer 
      System.out.println(n + " Is Prime"); 

      //decide if even 
     } else { 

      //display even answer 
      System.out.println(n + " Is Even"); 

     } 

     //counter input 
     n++; 

     //while input is false 
     while (isPrime(n) == false) { 
      n++; 
     } 


     //display next prime 
     System.out.println(n + " Next prime"); 

     { 

      //ask if you want to continue 
      System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No "); 
      //input answer 
      answer = in.nextInt(); 


      //if answer is 1)yes 
      if (answer == 1) { 
       playAgain = true; 

       //display play again and next input 
       System.out.println("\nPlay Again!"); 
      } 
      //if answer is no 
      if (answer == 2) { 
       playAgain = false; 
       System.out.println("\nGoodbye!"); 
       //close program 
       System.exit(0); 
      } 


     } 

     } 

    } while (playAgain != false); 
} 

}

+1

나는 동의한다, 간단한 연구는 당신에게이 질문에 대한 답을 주어야한다. – DreadHeadedDeveloper

답변

0
import java.util.Scanner; 

public class SOQ5B 
{ 

    public static boolean isPrime(int n) { 

     for (int i = 2; i < n; i++) { 
     if (n % i == 0) { 
      return false; 
     } 
     } 

     return true; 
    } 


    public static int nextPrime(int n) { 
     n++; 
     isPrime(n); 
     while (isPrime(n) == false) { 
     n++; 
     isPrime(n); 
     } 
     int prime = n; 
     return prime; 
    } 


/** 
* @param args the command line arguments 
*/ 
    public static void main(String[] args) { 
    // TODO code application logic here 

     int answer; 
     int counter = 0; 
     int n; 

     boolean playAgain = true; 
     boolean isNum; 
     boolean isNum2; 
     boolean continuePermitted = true; 

     Scanner input = new Scanner(System.in); 

     String s; 

     do { 
     //ask for input 
     System.out.print("\nEnter the integer value-> "); 

     s = input.nextLine(); 


     isNum = true; 

     for(int i = 0; i < s.length(); i++) 
     { 

      if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9')) 
      { 

       isNum = false; 

      } 

     } 

     if(isNum) 
     { 

      counter = 0; 

      n = Integer.parseInt(s); 

     //decide if prime 
      if (isPrime(n)) { 

      //display prime answer 
       System.out.println(n + " Is Prime"); 

      //decide if even 
      } 
      else { 

      //display even answer 
       System.out.println(n + " Is Even"); 

      } 

     //counter input 
      n++; 

     //while input is false 
      while (isPrime(n) == false) { 
       n++; 
      } 


     //display next prime 
      System.out.println(n + " Next prime"); 


      do 
      { 

       continuePermitted = true; 

      //ask if you want to continue 
       System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No "); 
      //input answer 

       s = input.nextLine(); 

       isNum2 = true; 

       for(int i = 0; i < s.length(); i++) 
       { 

        if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9')) 
        { 

        isNum2 = false; 

        } 

       } 


       if(isNum2) 
       { 

        answer = Integer.parseInt(s); 

       //if answer is 1)yes 
        if (answer == 1) { 
        playAgain = true; 

        //display play again and next input 
        System.out.println("\nPlay Again!"); 
        } 
       //if answer is no 
        if (answer == 2) { 
        playAgain = false; 
        System.out.println("\nGoodbye!"); 
        //close program 
        System.exit(0); 
        } 

       } 

       else 
       { 

        System.out.println("Incorrect response."); 
        continuePermitted = false; 

        //if answering the yes or no question incorrectly is part of the 3 strikes 
        //then uncomment the following lines of code 

        /* 
        counter++; 
        } 

        if(counter >= 3) 
        { 

        System.out.println("3 strikes you out"); 
        System.exit(0); 
        */ 

       } 
      }while(!continuePermitted); 


     } 

     else 
     { 

      System.out.print("\nIncorrect input. Number must be a positive integer.\n"); 
      counter++; 

     } 

     if(counter>=3) 
     { 

      System.out.println("3 strikes and you're out!"); 
      System.exit(0); 

     } 




     } while (playAgain != false); 
    } 
} 

미래에는 여기에서 질문을하기 전에 인터넷에서 질문을 연구하는 것이 좋습니다. 귀하의 질문에 쉽게 대답 할 수있는 여러 곳이있었습니다.

이제 실제 질문에 대해 s = input.nextLine()이라는 줄에서 코드를 어떻게 변경했는지 확인하십시오. 내가 뭘했는지는 문자열의 각 숫자가 0-9 사이의 숫자인지 확인하기 위해 검사되었습니다. 나는 그들이 모두 숫자인지를 확인할 수 있었을뿐만 아니라 네거티브가되도록하기 위해서도 네가 모두 긍정적인지를 알 수 있었다. 이와 함께 입력 값이 양수 일 때만 작동하는 부울도 있습니다. 그렇지 않으면 3 번 확인하여 프로그램이 엉망이되지 않도록하십시오. 게다가, 나는 3 개의 스트라이크를 허용하는 또 다른 섹션을 주석 처리했는데, 네 아니오 질문에 답하면 스트라이크로 간주됩니다. 다른 질문이 있으면 그냥 묻고 대답을 편집합니다.

+1

양해 해 주셔서 감사합니다. 나는 온라인 검색에 몇 시간을 보냈다. 나는 틀린 것을 발견했다. 비록 당신이 나와 같은 초보자를위한 단계를 설명했지만. – Nikron69

0

당신은 당신이 여기에 당신이 java.util.InputMismatchException

을 얻을 것이다 번호 대신 문자를 입력하면

int n = input.nextInt(); 

와 스캐너 클래스를 사용하여 입력을하려고

당신이 할 수있는 일은

입니다.
try { 
    int n = input.nextInt();  
} catch (InputMismatchException e) { 
    //handle the error scenario where the input is a character 
    System.out.println("Enter Valid Input"); 
} 
관련 문제