有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java扫描程序没有停止

请看一下下面的代码。我试图按升序管理给定的数字

import java.io.*;
import java.util.*;
import java.util.ArrayList;

public class TurboSort
{
    public static void main(String[]args)
    {

        List<Integer> numbers = new ArrayList();        
        Scanner scan = new Scanner(System.in);

        while(scan.hasNextInt())
        {
            numbers.add(scan.nextInt());
        }


        Collections.sort(numbers);

        System.out.println(numbers);
    }
}

输入为2,1,6,7,3

按回车键

现在,扫描仪没有退出while循环,因为它没有给出任何输出。我做错了什么?即使您成功地获得了它,输出也被诸如“[1][2][3]”之类的括号包围。为什么呢?那是因为我没有叫“整数”。parseInt()'?。请帮我回答这两个问题

谢谢


共 (5) 个答案

  1. # 1 楼答案

    按enter键的结果将是一个行分隔符,其字符被视为分隔符(默认情况下,请参见Character.isWhitespace()),并被跳过。因此Scanner正在等待进一步的输入,该输入永远不会到达,hasNextInt()将被阻塞。输入非整数的内容,例如.,以使循环终止:

    1 2 5 3 7 .

  2. # 2 楼答案

    扫描仪将继续扫描,直到输入结束或无法读取为止(例如,在文本中检测到非整数)

    在按enter键后按ctrl+D键。 您可以在任何空白处分隔数字

  3. # 3 楼答案

    你的代码应该可以工作。您只需要添加一种打破循环的方法。最好将扫描的值保存在局部变量中,以防再次引用

    或许可以加上:

    while(scan.hasNextInt()){
        int i=scan.nextInt();
            if(i==-1)
                break;
    
        numbers.add(i);
    }
    
  4. # 4 楼答案

    如果您只想在像2,1,6,7,3这样的一行上输入,可能更容易使用扫描仪的nextLine()

    Scanner scan = new Scanner(System.in);
    String consoleInput = scan.nextLine();
    

    一旦您点击回车键,这将终止扫描仪。在这一点上,您有一个字符串中的输入,您必须解析该字符串并得到所有的数字

    还要注意,您忘记了参数化ArrayList()

    以下是对源代码的可能修改:

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Scanner;
    
    public class Main {
      public static void main(String[] args) {
    
        Scanner scan = new Scanner(System.in);
    
        String consoleInput = scan.nextLine();
    
        List<Integer> numbers = new ArrayList<Integer>();
    
    
        if (consoleInput.length() > 0 && consoleInput.contains(",")) {
    
          String[] numbersAsStrings = consoleInput.split(",");
    
          for (String tNumberAsString : numbersAsStrings) {
            try {
              int tNumber = Integer.parseInt(tNumberAsString);
    
              numbers.add(tNumber);
    
            } catch (NumberFormatException nfe) {
              System.out.println(tNumberAsString + " is not a number");
            }
          }
    
          Collections.sort(numbers);
    
          System.out.println(numbers);
    
        } else {
          System.out.println("Nothing to sort!");
          System.out.println(numbers);
        }
    
      }
    }
    
  5. # 5 楼答案

    这个循环永远不会退出(只要输入整数),因为没有break条件

    while(scan.hasNextInt()){
      numbers.add(scan.nextInt());
    }
    

    如果希望循环停止,例如只需获取5个整数,则可以执行以下操作:

    while(scan.hasNextInt()){
      numbers.add(scan.nextInt());
      if(numbers.size() == 5) break;
    }