-1

我希望用户输入以下模式的行数,所以请标记我的错误。由于我是 java 初学者,所以也请给我推荐一些书。必须显示此模式

**********   
*********    
********     
*******      
******       
*****        
****         
***          
**           
* 

这是一个代码:

import java.util.Scanner;
class pattern{
public static void main (String agrs[]){

int n;
Scanner in =new Scanner(System.in);
System.out.println("enter the no. of rows in the pattern");
n= in.nextInt();
{
for(int i=0;i<n;i++)
{   for(int j=0; j<=i;j++)

System.out.print(" * ");
System.out.println(" ");
}}
}}

  ERROR   ...... 
 enter the no. of rows in the pattern
 Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at pattern.main(pattern.java:8)
4

2 回答 2

4

如果您检查oracle 站点上的文档,异常的扩展是:

由 Scanner 抛出以指示检索到的令牌与预期类型的​​模式不匹配,或者令牌超出预期类型的​​范围。

输入非整数输入时抛出此异常。

您需要添加一个 try/catch 来捕捉它,并通知用户输入错误。

例子:

import java.util.Scanner;

public class PatternTest {
    public static void main(String agrs[]) {

        int n = -1;     

        do
        {
            try {
                Scanner in = new Scanner(System.in);    
                System.out.println("enter the no. of rows in the pattern");
                n = in.nextInt();               
            } catch (java.util.InputMismatchException e) {
                System.err.print("Please enter only an integer.");
            }
        }while(n == -1);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i; j++)
            System.out.print(" * ");
            System.out.println(" ");
        }

    }
}

更新

int n = -1;     

do
{
    try {
        Scanner in = new Scanner(System.in);    
        System.out.println("enter the no. of rows in the pattern");
        n = in.nextInt();               
    } catch (java.util.InputMismatchException e) {
        System.err.print("Please enter only an integer.");
    }
}while(n == -1);

for (int rowNumber = n; rowNumber > 0; rowNumber--) {

    for (int columnNumber = 0; columnNumber < rowNumber; columnNumber++)
    System.out.print("*");  

    System.out.println(" ");
}
于 2013-10-02T07:23:42.233 回答
0

尝试查看文档。这里很清楚返回下一个令牌作为长。如果下一个标记不是浮点数或超出范围,则抛出 InputMismatchException。

另请参阅

于 2013-10-02T07:25:04.087 回答