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

查看:21
本文介绍了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天全站免登陆