【问题标题】:How to properly scan for user input using java.util.Scanner?如何使用 java.util.Scanner 正确扫描用户输入?
【发布时间】:2016-08-17 02:39:49
【问题描述】:

我已经实现了以下代码来打印小写字符的短语:

import java.util.Scanner;

public class LowerCase{ 
    public static void main (String[] args) {
        String input, output = "", inter;
        Scanner scan, lineScan;
        scan = new Scanner(System.in); // Scan from the keyboard
        System.out.println("Enter a line of text: ");
        input = scan.nextLine(); // Scan the line of text

        lineScan = new Scanner(input);
        while (lineScan.hasNext()) {
            inter = scan.next();
            output += inter.toLowerCase() + " ";
        }
        System.out.println(output);
    }
}

我不知道我的实现有什么问题!它可以正常编译,但是当我运行代码并输入输入短语时,它会冻结。

【问题讨论】:

    标签: java java.util.scanner next lowercase scanline


    【解决方案1】:

    我推荐一种不同的方法:

    import java.util.*;
    public class something
      {
          static Scanner reader=new Scanner(System.in);
          public static void main(String[] args)
          {
              System.out.println("type something (string)");
              String text = reader.next();  // whatever the user typed is stored as a string here
              System.out.println(text);
    
              System.out.println("type something (int)");
              int num = reader.nextInt();  // whatever the user typed is stored as an int here
              System.out.println(num);
    
              System.out.println("type something (double)");
              double doub = reader.nextDouble(); // whatever the user typed is stored as double here
              System.out.println(doub);
            }
        }
    

    这是我如何获取用户输入的一些示例代码。

    【讨论】:

      【解决方案2】:

      您不需要 两个 扫描仪对象来实现输出,这将适合您

      scan= new Scanner(System.in); //scan from the keyboard
      System.out.println("Enter a line of text: ");
      input=scan.nextLine(); //scan the line of text
      
      
      System.out.println(input.toLowerCase());
      scan.close();
      

      【讨论】:

        【解决方案3】:

        您的循环正在等待一个扫描仪的行,但从另一个 Scanner 读取行(因此是一个无限循环)。这个

        while (lineScan.hasNext()) {
            inter= scan.next();
        

        应该是这样的

        while (lineScan.hasNext()) {
            inter= lineScan.next();
        

        【讨论】:

          猜你喜欢
          • 2023-04-07
          • 2023-03-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-30
          • 1970-01-01
          相关资源
          最近更新 更多