-1

我很难为我的学校项目弄清楚这部分。所以寻求一点澄清。通常,用户必须输入一个数字(列)来插入一个游戏块。但是,如果用户输入“q”,程序将关闭。

我们被指出使用“parseInt”的方向,但是我正在寻找一些关于它是如何工作的澄清?

while(response.equalsIgnoreCase("q"));
        {
            System.out.println("Do you want to play again?");
            response = scan.next();

        }
        System.out.println("Do you want to play again?");
        response = scan.next(); // this revisits the while loop that
                                // prompted the player to play.
4

2 回答 2

0

请参阅http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)

public static int parseInt(String s)
       throws NumberFormatException

您想在Integer.parseInt(userInput)调用周围应用 try-catch 块以捕获 NumberFormatException

在 catch 正文中,您可以设置输入无效的标志。根据布尔值 isInputIsValid 将整个事情放在一个 while 循环中。

    boolean isValidNumber = false, wantsToQuit = false;
    while (!isValidNumber) {
        // Ask user for a value any way you want and save it to userInput
        String userInput = "";

        try {
            Integer.parseInt(userInput);
            isValidNumber = true;
        } catch (NumberFormatException e) {
            isValidNumber = false;
            if (userInput.equals("q")) {
                wantsToQuit = true;
                break;
            }
        }
    }

wantToQuit 不是必须的变量,只是说明该部分的目的是什么

于 2013-10-01T03:02:49.193 回答
0
import java.util.Scanner;
 public class ScanInteger {
    public static void main(String...args)throws Throwable {
        int num = 0; String s= null;
        System.out.print("Please enter a number : ");
        Scanner sc = new Scanner(System.in);
        do{
        try{    
                s = sc.next();
                num= Integer.parseInt(s);
                System.out.println("You have entered:  "+num+" enter again : ");
        }catch(NumberFormatException e){
            if(!s.equalsIgnoreCase("q"))
                System.out.println("Please enter q to quit else try again ==> ");
            }
        }while(!s.equalsIgnoreCase("q"));
    sc.close();
    }
}
于 2013-10-01T03:10:24.633 回答