2014-02-13 2 views
0

(BlueJ의) : 1. 스캐너 (= 새로운 스캐너 (System.in) 스캐너 스캐너) 2. 사용 방법 scanner.nextLine()질문 우리는이 작업에 대한 몇 가지 지침이

우리 (Mastermind) 단계별로 빌드해야하고 난 항상 (BlueJ) nextInt() 스위치 케이스와 함께 (int가 아닌 물건을 입력)에 대한 오류가있어 btw : 우리는 nextInt 사용해서는 안됩니다 - 우리는 nextLine을 사용해야합니다 -하지만 스위치 케이스로 어떻게 할 수 있습니까? 당신이해야 할 일은

import java.util.Scanner; 
public class Game { 
/** 
* Methods 
*/ 
public void play() { 
    System.out.println("******************* Game **********************"); 
    System.out.println("* (1) CPU vs Human        *"); 
    System.out.println("* (2) CPU vs CPU        *"); 
    System.out.println("* (3) Human vs CPU        *"); 
    System.out.println("* (4) Highscore         *"); 
    System.out.println("* (5) End          *"); 
    System.out.println("-------------------------------------------------"); 
    System.out.println("Your choice:         "); 

    Scanner scanner = new Scanner(System.in); 

    // i used this so far but i get an error for entering a-z or other stuff than numbers 
    int userInput = scanner.nextInt(); 

    //i have to use this but it doesnt work with switchcase - any suggestions? 
    //String userInput = scanner.nextLine(); 

    scanner.close(); 
    switch(userInput) { 
     case 1: // not written yet 
     case 2: // not written yet 
     case 3: // not written yet 
     case 4: // not written yet 
     case 5: System.exit(0); 
     default: System.out.println("Illegal userinput! Only enter numbers between 1 and 5!"); 
    } 
    } 
} 
+0

질문이 명확하지 않습니다. 더 자세히 설명해주세요. – Maroun

+0

뭐가 좋아? 나는 코딩을 위해 BlueJ를 사용한다. 우리는 선생님의 임무를 가지고 있으며 올바르게 해결하는 방법을 모른다. 질문은 코드에 기록됩니다. scanner.nextLine();을 어떻게 사용합니까? 올바른 및 어떻게 errormessage 후 숫자를 다시 입력 할 수 있습니다 "잘못된 userinput! (...)" – JavaBeginner

답변

0

Integer.parseInt(String s) 방법을 사용하여 정수로합니다 (.nextLine() 방법에 의해 산출되는) 문자열을 구문 분석하는 것입니다. 지정된 문자열이 정수가 아닌 경우이 메서드는 NumberFormatException을 던져서 사용자가 잘못된 번호를 입력 한 시점을 파악하여 다시 물어볼 수 있습니다. 그래서 같은

뭔가 : nextLine()이 문자열이 아닌 문자를 반환하기 때문에

public static void main(String[] args) 
{ 
    boolean validInput = false; 
    Scanner scanner = new Scanner(System.in); 
    while (!validInput) 
    { 
     System.out.println("******************* Game **********************"); 
     System.out.println("* (1) CPU vs Human        *"); 
     System.out.println("* (2) CPU vs CPU        *"); 
     System.out.println("* (3) Human vs CPU        *"); 
     System.out.println("* (4) Highscore         *"); 
     System.out.println("* (5) End          *"); 
     System.out.println("-------------------------------------------------"); 
     System.out.println("Your choice:         "); 

     try 
     { 

      // i used this so far but i get an error for entering a-z or other stuff than numbers 
      int userInput = Integer.parseInt(scanner.nextLine().trim()); 
      //If no error took place, then the input is valid. 
      validInput = true; 

      //i have to use this but it doesnt work with switchcase - any suggestions? 
      //String userInput = scanner.nextLine();     
      switch (userInput) 
      { 
       case 1: // not written yet 
       case 2: // not written yet 
       case 3: // not written yet 
       case 4: // not written yet 
       case 5: 
        System.exit(0); 
       default: 
        validInput = false; 
        System.out.println("Illegal userinput! Only enter numbers between 1 and 5!"); 
      } 
     } catch (Exception e) 
     { 
      System.out.println("Invalid Input, please try again"); 
     } 
    } 
    scanner.close(); 
} 
+0

당신이 정확하게 표시/쓸 수 있습니까? 나는 자바 프로가 아니다 :) 단지 그것을 배우기 시작했다. 약간의 코드를 추가하고 catch를 사용하는 방법을 보여줄 수 있습니까? 방법 고마워. – JavaBeginner

+0

@JavaBeginner : 답변을 업데이트했습니다. 나는 이것이 도움이되기를 바랍니다 :) – npinti

+0

제발 좀 – JavaBeginner

0

당신이 직접 스위치의 경우에 대한 nextLine()의 출력을 사용할 수 없습니다. 당신은 단지 하나의 문자에 읽고있는 경우, 당신은 할 수 있습니다 : 다음의 토큰을 int 형으로 구문 분석 할 수없는 경우

String userInput = scanner.nextLine(); 
switch(userInput.charAt(0)) { 

scanner.nextInt()

분명히 예외가 발생합니다. try-catch 블록에이 문장을 래핑하고 숫자가 아닌 숫자가 입력되면 적절한 방법을 사용해야합니다.

+0

나는 이것 같이 그것을 시도하고 달린다. 1을 입력하고 "잘못된 사용자 입력! (...)"을 입력하고 중단합니다. - 다음 질문은 -이 오류 메시지 이후에 - 어떻게 다른 번호를 입력 할 수 있습니까? – JavaBeginner

+0

[Java 7] (http://openjdk.java.net/projects/jdk7/features/)에서 문자열을 바꿀 수 있습니다 (절은''1 '',''2' '가되어야합니다). "등). 'char'를 켜면''1'',''2''' 등이됩니다. – tom

0

nextLine() 당신에게 String을 주며, 정수로 변환하고 (예상 한대로) 후속 논리를 수행해야합니다.

Integer.parseInt() 방법

+0

그 일을했지만 여전히 문제가 있습니다 - 조금 도와 주시겠습니까? – JavaBeginner

+0

문제에 대해 구체적으로 설명하십시오. –

+0

@JavaBeginner 방금 시도해 본 결과 특별한 문제가 없습니다. 당신이 시도한 것과 우리가 겪은 에러를 보여주세요. –