使用Scanner类输入 [英] Inputing using Scanner class

查看:85
本文介绍了使用Scanner类输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从过去的经验中理解的是 nextInt() nextDouble()会一直搜索到整数或双数位于相同或下一行无关紧要,而读取字符串作为输入通过扫描程序类 next()在空格之前考虑这些字符串并将光标保持在同一行,其中 nextLine()将考虑剩余的 next() if在代码中的 nextLine()之前使用,有人可以帮助我更详细地理解这一点,特别是关于 nextLine()它开始的地方和光标结束的地方?另外,请告诉我,我认为是否有任何错误。

What I understood from my past experiences is nextInt() or nextDouble() would keep on searching until the integer or the double is found in the same or the next line it doesn't matter,while to read a string as input through scanner class next() considers those strings before space and keeps the cursor in the same line, where as nextLine() would consider the leftovers by the next() if used before the nextLine() in code,could someone help me understand this in more detail,especially about nextLine() where it starts and where the cursor ends? Also, please tell me if any mistakes I thought are correct.

推荐答案

您的第一个理解是错误的。

Your first understanding is wrong.


我从过去的经验中理解的是.nextInt()或
.nextDouble()将继续搜索直到整数或双
在相同或下一行中找不到它

what i understood from my past experiences is .nextInt() or .nextDouble() would keep on searching until the integer or the double is found in the same or the next line it doesn't matter

nextInt() nextDouble()分别等待整数和双精度。如果它得到字符串而不是它的期望,它会抛出 InputMismatchException

nextInt() and nextDouble() waits for the integer and double respectively. If it gets string instead of it's expectation, it throws InputMismatchException.

您可以运行此代码并亲眼看看。

You can run this code and see for yourself.

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        s.nextInt();
    }
}

根据你的报价:


.nextInt()或.nextDouble()将继续搜索,直到整数
或double在相同或下一行中找到它无所谓

.nextInt() or .nextDouble() would keep on searching until the integer or the double is found in the same or the next line it doesn't matter

提供输入: Abcdf234gd 。你不会得到 234 。你得到 InputMismatchException

Give input: Abcdf234gd. You won't get 234. You get InputMismatchException.

对于 .next() .nextLine()

.next():只读取并返回字符串,直到遇到空格或 EOF

.next() : Only reads and returns a string till it encounters a space or EOF.

.nextLine():返回字符串直到遇到 \ n \ r EOF 。意味着,它返回整行。

.nextLine() : Returns string till it encounters \n or \r or EOF. Means, it returns whole line.

光标位置

next()

next():

考虑字符串:

ABC DEF GHI JKL MNO PQR STU VWX YZ

初始位置:

->ABC DEF GHI JKL MNO PQR STU VWX YZ

当您拨打 next()时,光标移动到:

When you call next(), the cursor moves to:

ABC ->DEF GHI JKL MNO PQR STU VWX YZ

并返回 ABC

nextLine()

nextLine():

考虑字符串:

ABC DEF GHI JKL 
MNO PQR STU VWX
YZ

初始头寸:

->ABC DEF GHI JKL
MNO PQR STU VWX 
YZ

当您调用 nextLine()时,光标转到下一行:

When you call nextLine(), the cursor moves to next line:

ABC DEF GHI JKL
->MNO PQR STU VWX
YZ

并返回 ABC DEF GHI JKL

我希望它有所帮助。

这篇关于使用Scanner类输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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