Scanner和nextInt丢弃整数 [英] Scanner and nextInt discard integer

查看:110
本文介绍了Scanner和nextInt丢弃整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Scanner在java中获取用户输入。当我使用nextInt()并且用户输入2 5时,则分配值2并丢弃5。如果我想显示这样的输入是错误怎么办?
我想到的一个解决方案是我可以使用nextString()而不是nextInt()然后解决问题。但是有人可以建议一个更好的解决方案吗?

I am using Scanner for taking user input in java. when i use nextInt() and the user inputs "2 5", then the value "2" is assigned and 5 is thrown away. What if I want to display that such an input is an error? One solution that comes to my mind is that i can use nextString() instead of nextInt() and then work my way out. But can anybody suggest a better solution?

我意识到它并没有抛弃空格后的整数,而是将它用于下一个输入。

i realized that it is not throwing away the integer after space, instead it is using it for the next input.

import java.util.Scanner;
class Test{
static Scanner in=new Scanner(System.in);
static void trial(){
    int k=in.nextInt();
    System.out.println(k);
    System.out.println(k);
}

public static void main(String[] args){     
    int k=in.nextInt();
    System.out.println(k);
    System.out.println(k);
    trial();        
}
}


推荐答案

1。首先使用 nextLine() 读取整行。

2. 使用 Integer.parseInt()方法验证整数输入

例如:

Scanner scan = new Scanner(System.in);
String s = scan.nextLine();

try{
    Integer.parseInt(s);
}
catch(NumberFormatException ex){
    System.out.println("Its not a valid Integer");
}

这篇关于Scanner和nextInt丢弃整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆