2014-10-09 2 views
1

Я совершенно не знаком с Java, и я застрял. Я должен создать игру «угадай номер». Я могу сделать большинство частей, но теперь я не знаю, как обращаться с пользовательским вводом, если это строка. Я хочу сказать Пользователю, что вход был неправильным, если он входит в строку и повторно запрашивает ввод. Было бы здорово, если бы кто-то может помочь мне здесь :)
Вот мой код: Java - Обработка ввода исключений строк

import java.util.Scanner; 
import java.util.Random; 

public class SWENGB_HW_2 { 

public static void main(String[] args) { 

    System.out.println("Welcome to the guess the number game!\n"); 
    System.out.println("Please specify the configuration of the game:\n"); 

    Scanner input = new Scanner(System.in); 

    System.out.println("Range start number (inclusively):"); 
    int startRange; 
    startRange = input.nextInt(); 

    System.out.println("Range end (inclusively):"); 
    int endRange; 
    endRange = input.nextInt(); 

    System.out.println("Maximum number of attemps:"); 
    int maxAttemp; 
    maxAttemp = input.nextInt(); 

    System.out.println("Your Task is to guess the random number between " 
      + startRange + " and " + endRange); 

    Random randGenerator = new Random(); 
    int randNumber = randGenerator.nextInt((endRange - startRange) + 1) 
      + startRange; 
    int numberOfTries = 0; 

    System.out 
      .println("You may exit the game by typing; exit - you may now start to guess:"); 
    String exit; 
    exit = input.nextLine(); 


    for (numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++) { 

     int guess; 
     guess = input.nextInt(); 



     if (guess == randNumber) { 
      System.out.println("Congratz - you have made it!!"); 
      System.out.println("Goodbye"); 
     } else if (guess > randNumber) { 
      System.out.println("The number is smaller"); 
     } else if (guess < randNumber) { 
      System.out.println("The number is higher"); 
     } 

    } 
    if (numberOfTries >= maxAttemp) { 
     System.out.println("You reached the max Number of attempts :-/"); 
    } 

} 
} 
+0

возможно дубликат [Понимание попытки и улова и обработки ошибок] (http://stackoverflow.com/questions/25940276/understanding-try-catch-and-error -handling) – StackFlowed

+0

Возможно, вы захотите добавить 'break;' после печати 'Goodbye', чтобы выйти из цикла for и завершить работу программы. – aioobe

ответ

3

Вы можете создать метод полезности который выглядит следующим образом:

public static int nextValidInt(Scanner s) { 
    while (!s.hasNextInt()) 
     System.out.println(s.next() + " is not a valid number. Try again:"); 
    return s.nextInt(); 
} 

, а затем, вместо того,

startRange = input.nextInt() 

вы

startRange = nextValidInt(input); 

Если вы хотите иметь дело с "exit" альтернативы, я бы рекомендовал что-то вроде этого:

public static int getInt(Scanner s) throws EOFException { 
    while (true) { 
     if (s.hasNextInt()) 
      return s.nextInt(); 
     String next = s.next(); 
     if (next.equals("exit")) 
      throw new EOFException(); 
     System.out.println(next + " is not a valid number. Try again:"); 
    } 
} 

, а затем обернуть всю программу в

try { 
     ... 
     ... 
     ... 
    } catch (EOFException e) { 
     // User typed "exit" 
     System.out.println("Bye!"); 
    } 
} // End of main. 

Btw, остальные вашего кода выглядит великолепно. Я пробовал это и работает как шарм :-)

+0

Thx thats приятно слышать :) – chritschl

+0

У меня есть еще один вопрос. Что вы имеете в виду с «деформацией всей программы в ней»? Какие части кода? – chritschl

+1

Положите 'try {' как самое первое после 'main (String [] args) {' и '} catch (EOFException e) {System.out.println (« Bye »); } 'перед закрытием'} '' main'. Бросив «EOFException» в любом месте, вы попадете в «catch'-block, а затем прекратите работу напрямую. – aioobe

1

Вы можете проверить, что сканер имеет int, прежде чем пытаться его прочитать. Вы можете сделать это по телефону hasNextInt() с чем-то вроде

while (input.hasNext() && !input.hasNextInt()) { 
    System.out.printf("Please enter an int, %s is not an int%n", input.next()); 
} 
int startRange = input.nextInt(); 
Смежные вопросы