为什么input.nextint方法有一个\ n剩余呢?

编程入门 行业动态 更新时间:2024-10-21 05:45:24
本文介绍了为什么input.nextint方法有一个\ n剩余呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在回答这个问题时,我不明白为什么input.nextInt的剩余字符是换行符.

In the answer to this question I don't understand why the input.nextInt has a newline character as a leftover.

扫描仪在使用next(),nextInt()或其他nextFoo()吗?

推荐答案

答案很简单:

Scanner#nextInt()读取下一个整数,但不读取用户按下以提交整数的换行符(ENTER).

Scanner#nextInt() reads the next integer but not the newline (ENTER) the user presses to submit the integer.

要了解这一点,您必须知道您键入的所有内容都会写入一个缓冲区,Scanner方法会尝试从该缓冲区中读取.

To understand this you must know that everything you type will be written to a buffer, from which the Scanner methods try to read from.

关于以下示例:

System.out.println("Enter a number: "); int i = scanner.nextInt(); System.out.println("Enter a line: "); String l = scanner.nextLine();

会发生什么:

  • 用户看到Enter a number:,然后按17和ENTER.
  • 扫描仪将读取17,但保留ENTER的换行符.
  • 程序将写入Enter a line:,但是扫描程序将读取ENTER的换行符,而不是等待输入.
  • The user sees Enter a number: and will press 17 and ENTER.
  • The scanner will read the 17 but leave the newline of the ENTER.
  • The program will write Enter a line: but the scanner will read the newline of the ENTER instead of waiting for input.

更多推荐

为什么input.nextint方法有一个\ n剩余呢?

本文发布于:2023-10-31 06:09:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有一个   剩余   方法   input   nextint

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!