为什么 println 方法中的字符串显示两次? [英] Why does the string inside println method show twice?

查看:22
本文介绍了为什么 println 方法中的字符串显示两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,为什么 println 方法中的字符串显示两次.我应该怎么做才能每次迭代显示一次消息

In the following code why does the string inside println method shows twice.What should I do to show the message once per iteration

package practicejava;

public class Query {

    public static void main(String[] args) throws java.io.IOException {
        System.out.println("Guess a capital letter Character");
        while ((char) System.in.read() != 'S') {
            System.out.println("wrong.guess again to finish the program");
        }

    }
}

推荐答案

当用户输入控制台字符时,为了确认他的输入已准备好传递给应用程序,他按下 enter 键.但是控制台不仅仅传递提供的字符,它还添加到输入流 (System.in) 依赖于操作系统的 行分隔符 后面的字符.一些操作系统使用 (那些是单个字符,x 只是表示它们的符号)其他像 Windows 使用 (两个字符)序列作为行分隔符.

When a user writes in console characters, to confirm fact that his input is ready to be passed to application he presses enter key. But console doesn't pass only provided characters, it also adds to input stream (System.in) OS dependent line separator character(s) after it. Some OS use or (those are single characters, x is just notation to represent them) others like Windows use (two characters) sequence as line separator.

现在这些额外的字符也被 System.in.read() 读取,因为它们不等于 S System.out.println("错误.再次猜测以完成程序"); 被执行额外的时间.

Now those additional characters are also read by System.in.read() and since they are not equal to S System.out.println("wrong.guess again to finish the program"); is executed additional time.

为了避免此类问题而不是通过 System.in.read() 处理原始数据,请考虑使用旨在使我们的生活更轻松的类,例如 java.util.Scanner

To avoid such problems instead of working with raw data via System.in.read() consider using classes meant to make our life easier like java.util.Scanner

Scanner sc = new Scanner(System.in);
System.out.println("Guess a capital letter Character");
String response = sc.nextLine();
while(!response.equals("S")){
     System.out.print("incorrect data, please try again: ");
     response = sc.nextLine();
}

这篇关于为什么 println 方法中的字符串显示两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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