2016-03-01 52 views
0

我想提示用户输入两个数字,代表一块板子的大小NxN。如果用户写入少于1个或多于2个数字,程序不允许他这样做,而是由异常来处理。限制提示参数的数量

例如:

public class Tester { 

public static void main(String[] args) { 

    Scanner userInput = new Scanner(System.in); 

    System.out.print("Board size NxN: "); 

    int width = userInput.nextInt(); 
    int height = userInput.nextInt(); 
} 
} 

如何使用try-catch块限制用户仅输入2号实现这一目标?

回答

0

公共类测试仪{

public static void main(String[] args) { 

    Scanner userInput = new Scanner(System.in); 

    System.out.print("Board size NxN: "); 
    try { 
     int width = userInput.nextInt(); 
     int height = userInput.nextInt(); 
     if (userInput.hasNext()) { 
      throw new IllegalArgumentException(); 
     } 
    } catch (IllegalArgumentException e) { 
     System.err.println("Enter just two numbers"); 
    } 
} 

}

+0

当我输入第一个数字,然后是第二个,我按enter键,并继续等待第三号。当第三个数字被放置时,它会抛出异常:板子尺寸NxN:2 3 “只输入两个数字” –

+0

这是合乎逻辑的。您需要向用户提示“Enter 1st”,“Enter 2nd”,“Correct(y/n)?”,并且只接受'YyNn'作为最后一个输入(并且只给第一个数字)。 –