java 如何将扫描仪输入转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42395182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert scanner input into an integer?
提问by O Williams
In Java, how, if possible, can I convert numerical scanner input (such as 2 or 87) into an integer variable? What I'm using now yields the error message:
在 Java 中,如果可能,我如何将数字扫描仪输入(例如 2 或 87)转换为整数变量?我现在使用的会产生错误消息:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at diDecryption.Didecryption.main(Didecryption.java:226)
And this is the code I'm using to do it (pieced together, it's part of a much larger program):
这是我用来做它的代码(拼凑起来,它是一个更大的程序的一部分):
System.out.println("Enter first number");
Scanner sc=new Scanner(System.in);
String name=sc.next();
int result = Integer.valueOf(name);
if (result / 2 == 1){
System.out.println("a");
The purpose of the program is to decode an encrypted message. The input is numerical, and if I remove the string to int converter, the division does not work. How do I fix this?
该程序的目的是解码加密的消息。输入是数字,如果我将字符串删除为 int 转换器,则除法不起作用。我该如何解决?
回答by Alex
System.out.println("Enter first number");
Scanner sc=new Scanner(System.in);
String name=sc.next();
int result = Integer.parseInt(name);
if (result / 2 == 1){
System.out.println("a");
parseint changes it to a primitive int rather than an Integer object
parseint 将其更改为原始 int 而不是 Integer 对象
回答by Antoine Dubuis
If your input is numerical, it is better to use directly the method
如果你的输入是数字,最好直接使用该方法
sc.nextInt();
回答by Sergei Stepanenko
In your stacktrace you have null
as parameter in Integer.valueOf(name)
.
Seems your console produce some invalid input sequence.
Try to check it with sc.hasNext()
condition:
在您的堆栈跟踪中,您null
在Integer.valueOf(name)
. 似乎您的控制台产生了一些无效的输入序列。尝试使用sc.hasNext()
条件检查它:
System.out.println("Enter first number");
Scanner sc = new Scanner(System.in);
if (sc.hasNext()) {
String name = sc.next();
int result = Integer.parseInt(name);
if (result / 2 == 1) {
System.out.println("a");
}
}
回答by FSm
Try
尝试
System.out.println("Enter first number");
Scanner sc=new Scanner(System.in);
int name=sc.nextInt();
if ((name / 2) == 1)
System.out.println("a");
RUN
跑
run:
Enter first number
2
a
回答by Anik Dey
Try this code
试试这个代码
package exmaple;
import java.util.Scanner;
public class Parser {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = in.next();
try{
int result = Integer.parseInt(name);
if(result / 2 == 1) {
System.out.println("a");
}
} catch(Exception exception) {
}
in.close();
}
}