当调用nextLine() - 方法时,为什么我不能在Scanner(System.in)中输入字符串? [英] Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

查看:702
本文介绍了当调用nextLine() - 方法时,为什么我不能在Scanner(System.in)中输入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个程序实际上是如何工作的??

How does this program actually work...?

import java.util.Scanner;

class string
{
    public static void main(String a[]){
        int a;
        String s;
        Scanner scan = new Scanner(System.in);

        System.out.println("enter a no");
        a = scan.nextInt();
        System.out.println("no is ="+a);

        System.out.println("enter a string");
        s = scan.nextLine();
        System.out.println("string is="+s);
    }
}

输出为:

enter the no
1234
no is 1234
enter a string
string is=         //why is it not allowing me to enter a string here?


推荐答案

.nextInt()获取下一个 int ,但不读取新行字符。这意味着当您要求它读取下一行时,您将从第一次开始读取新行字符的结尾。

.nextInt() gets the next int, but doesn't read the new line character. This means that when you ask it to read the "next line", you read til the end of the new line character from the first time.

在获得 int .nextLine() c $ c>解决这个问题。或者(我更喜欢这种方式),以字符串的形式读取 int ,并将其解析为 int

You can insert another .nextLine() after you get the int to fix this. Or (I prefer this way), read the int in as a string, and parse it to an int.

这篇关于当调用nextLine() - 方法时,为什么我不能在Scanner(System.in)中输入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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