[英]Integers.parseint( on scanner input ), also i want to make limits so user can only input number in range from 0 to 100
Hello guys im having little problem here, Firstly i want to parse string which comes from scanner into int, so i can later use it IF statement. 大家好,我在这里没有什么问题,首先,我想将来自扫描程序的字符串解析为int,以便以后可以在IF语句中使用它。 Code looks like this
代码看起来像这样
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);
Any help appreciated, hopefully i made my self clear and my problem too 任何帮助表示赞赏,希望我能阐明自己的意思,也可以解决我的问题
Edit: 编辑:
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);
I presume you wanted to write 我想你想写
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
also contains the method nextInt
, which obviates the need for Integer.parseInt
. java.util.Scanner
还包含nextInt
方法,从而消除了对Integer.parseInt
的需求。 You can just say numbers.nextInt()
. 您可以只说
numbers.nextInt()
。
You also need to change your list declaration from List<String>
to List<Integer>
. 您还需要将列表声明从
List<String>
更改为List<Integer>
。
You are trying to parse non-integer (String) to integer which throws NumberFormatException
in cases where input is non-integer. 您试图将非整数(字符串)解析为整数,如果输入为非整数,则抛出
NumberFormatException
。
int n=0;
try
{
n = Integer.parseInt(numbers.next());
}catch(Exception e)
{
}
if(n > 0 && n<101)
{
//your logic
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.