1

大家好,我这里有一点问题,首先我想将来自扫描仪的字符串解析为 int,这样我以后可以使用它的 IF 语句。代码看起来像这样

List<String> list = new ArrayList<String>();
    Scanner numbers = new Scanner(System.in);

    do {
        System.out.println("Current list is " + list);
        System.out.println("Add more? (y/n)");

        if (numbers.next().startsWith("y")) 
        {
            if(Integer.parseInt(numbers)> 0 && Integer.parseInt(numbers) < 101)
            {// i get error on above line, and im kinda lost here


                System.out.println("Enter : ");
                list.add(numbers.next());
            }
        }
        else
        {            
            break;                
        }           
    }while (true);

任何帮助表示赞赏,希望我清楚自己的问题和我的问题

编辑:

        do {

        System.out.println("Current list is " + list);
        System.out.println("Add more? (y/n)");

        if (numbers.next().startsWith("y")) 
        {                               
            System.out.print("Enter: "); 
            System.out.flush();                
            final int n = Integer.parseInt(numbers.next());
            if (n > 0 && n < 101) 
            {
                list.add(n);
                // this is where i get the error.

                //no suitable method found for add(int)
                // method java.util.List.add(int,java.lang.String) is not applicable
                // (actual and formal arguments lists differ in length)
                // method java.util.List.add(java.lang.String) is not applicable
                // (actual argument int cannot be converted to java.lang.String 
                // by method invocation conversion).

                // end of log
            }
            else
            {
                System.out.println("Number you have entered exceeds raange between 0-100");
            } 
        }
        else
        {            
            break;                
        }           
    }while (true);
4

2 回答 2

1

我想你想写

System.out.print("Enter: "); System.out.flush();
final int n = Integer.parseInt(numbers.next());
if (n > 0 && n < 101) list.add(n);

java.util.Scanner还包含该方法nextInt,从而消除了对Integer.parseInt. 你可以说numbers.nextInt()

您还需要将您的列表声明从 更改List<String>List<Integer>

于 2012-07-10T20:53:50.980 回答
0

您正在尝试将非整数(字符串)解析为NumberFormatException在输入为非整数的情况下抛出的整数。

int n=0;

try
{
n = Integer.parseInt(numbers.next());
}catch(Exception e)
{
}

if(n > 0 && n<101)
{
//your logic
}
于 2012-07-10T20:54:32.537 回答