【问题标题】:print out each character in an input打印出输入中的每个字符
【发布时间】:2016-06-19 15:36:30
【问题描述】:

我一直在以http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html 作为参考自学Java。他们有一个名为 algs4 的库,它有几个类,包括 StdIn,我正在尝试在下面实现。

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class Tired
{  
    public static void main(String[] args)
    {
        //I thought this while statement will ask for an input 
        //and if an input is provided, it would spell out each character
        while (!StdIn.hasNextChar()) {

             StdOut.print(1);  //seeing if it gets past the while conditional
            char c = StdIn.readChar();
            StdOut.print(c);
        }       
    }    
}


//This is from StdIn class. It has a method called hasNextChar() as shown below.  
/*
     public static boolean hasNextChar() {
        scanner.useDelimiter(EMPTY_PATTERN);
        boolean result = scanner.hasNext();
        scanner.useDelimiter(WHITESPACE_PATTERN);
        return result;
    }
 */

如果我运行代码,它确实会要求输入,但无论我输入什么,都不会发生任何事情,也不会打印出任何内容。

我看到即使StdOut.print(1); 也没有打印出来,所以由于某种原因,它只是卡在while

【问题讨论】:

    标签: java class input while-loop


    【解决方案1】:

    看起来问题出在您的 while 循环的条件上:

    !StdIn.hasNextChar()
    

    这表示只要没有下一个字符就继续。但是你想在有一个的时候继续,所以摆脱那个!,你应该会很好。

    【讨论】:

      【解决方案2】:

      这里有一些类似的替代代码。不是最好的编码,但很有效。

      import java.util.Scanner;
      
      public class test{
      
          static Scanner StdIn = new Scanner(System.in);
          static String input;
      
          public static void main(String[] args){
      
              while(true){
                  if(input.charAt(0) == '!'){ // use ! to break the loop
                      break;
                  }else{
                      input = StdIn.next();  // store your input
                      System.out.println(input); // look at your input
                  }
              }
          }   
      }
      

      【讨论】:

        猜你喜欢
        • 2013-06-16
        • 1970-01-01
        • 2015-07-30
        • 1970-01-01
        • 2015-07-28
        • 2023-01-22
        • 1970-01-01
        • 2023-03-26
        • 2017-02-05
        相关资源
        最近更新 更多