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

查看:122
本文介绍了为什么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)依赖于操作系统的行分隔符后的字符.某些操作系统使用\r\n(这些是单个字符,\x只是表示它们的表示法),而其他类似Windows的操作系统则使用\r\n(两个字符)序列作为行分隔符.

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 \r or \n (those are single characters, \x is just notation to represent them) others like Windows use \r\n (two characters) sequence as line separator.

现在,这些额外的字符也会被System.in.read()读取,并且由于它们不等于S,因此System.out.println("wrong.guess again to finish the program");会执行额外的时间.

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天全站免登陆