【问题标题】:Trouble with "do while"“do while”的问题
【发布时间】:2013-11-14 17:03:36
【问题描述】:

此程序需要用户输入的大写字母。输入保存在 char 变量 c 中,然后转换为 ascii,然后检查它是否真的是大写字母。如果没有,程序应该再次询问。问题是,该命令 System.out.println("Write capital letter: ") 被执行多次,它看起来像这样:

大写字母: 写大写字母: 写大写字母: 写大写字母: 写大写字母:

我希望每次输入错误后屏幕上只有一个“写大写字母:”,并且需要使用 ascii 表完成。

提前致谢。

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

int ascii;
char c;

do { 
  System.out.println("Write capital letter: ");
  c = (char) System.in.read();                                              
  ascii = (int) c;                                                         
} while (ascii < 65 || ascii > 90 );   

【问题讨论】:

  • 你试过调试这个吗?当while 语句发生时,cascii 有什么值?
  • 确实,在ascii = (int) c; 之后添加类似System.out.println( ascii ) 的内容,然后看看你得到了什么值。然后查找哪些字符有这些代码。
  • 导致提示多次显示的原因是,当您读取一个字节(字符)时,它会将您输入的该行上的任何其他内容(包括换行符)留给System.in

标签: java loops while-loop do-while


【解决方案1】:
System.out.println("Write capital letter: ");
do { 
  c = (char) System.in.read();                                              
  // ascii = (int) c;  // not needed if you are using the isUppercase() method          
  if(! Character.isUppercase(c)){
   System.out.println("Write capital letter: ");
  }                                            
} while (! Character.isUppercase(c) );  

只要条件为真,do 块中定义的任何内容都会被执行。因此,将您只想执行一次的语句移出do 块。

【讨论】:

  • 你不需要整个ascii 变量。
  • OP 想要多次提示:“我希望每次输入错误后屏幕上只有一个“写大写字母:”,并且需要使用 ascii 表完成。问题是为什么它出现的频率比 OP 预期的要多。
  • 我试过了,但每次输入错误后我仍然得到多个“写大写字母:”。
  • @user2993023 尝试改用java.util.Scanner
【解决方案2】:

当您设置了BufferedReader 变量集时,为什么还要使用System.in.read()

这将解决您的问题。我正在使用您的 BufferedReader in 变量。

while (true) {
    System.out.println("Write capital letter: ");
    int b = 0
    while ((b = in.read()) != -1){ 
        char c = (char) c;
        if (Character.isUpperCase(c)) break;
    }

    //Carry on...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2014-05-27
    相关资源
    最近更新 更多