IDEA 中使用 while(scanner.hasnext()) 如何结束输入,tracktest 代码测验

按 ctrl + d 即可。不用写回车结束输入什么的

ctrl + d 结束输入

import java.util.ArrayList;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        String[] lines = getStdin();
        for (int i = 0, l = lines.length; i < l; i++) {
            String output = String.format("Hello %s!", lines[i]);
            System.out.println(output);
        }
    }

    private static String[] getStdin() {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> lines = new ArrayList<>();
        while (scanner.hasNext()) {
            lines.add(scanner.nextLine());
        }

        String[] strings = lines.toArray(new String[lines.size()]);
        System.out.println("strings = " + strings);
        return strings;
    }
}


在这里插入图片描述

回车结束输入

import java.util.ArrayList;
import java.util.Scanner;

public class T11 {
    public static void main(String[] args) {
        String[] lines = getStdin();
        for (int i = 0; i < lines.length; i++) {
            String output = String.format("Hello %s !",  lines[i]);
            System.out.println(output);
        }
    }

    private static String[] getStdin() {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> lines = new ArrayList<>();
        while (true) {
            String line = scanner.nextLine();
            if (line.isEmpty()) {
                break; // 终止循环,输入结束
            }
            lines.add(line);
        }
        scanner.close();
        return lines.toArray(new String[0]);
    }
}



track test

分蛋糕问题
6个人分4个蛋糕最小三等分,
输入
1
6 4
输入出
3

import java.util.Scanner;
import java.util.ArrayList;

public class App {

    public static void main(String[] args) {
        String[] lines = getStdin();
        for (int i = 1, l = lines.length; i < l; i++) {
          //int num = Integer.parseInt(lines[0]);
            //获取字符串6 4的数字6和4
            String[] numbersArray = lines[i].split("\\s+");
            int peoples = Integer.parseInt(numbersArray[0]);
            int cakes = Integer.parseInt(numbersArray[1]);
            int minDivision = 1;

            // 从1开始尝试等分数,找到满足每人分到整数个蛋糕的最小等分数
            while (true) {
                int totalCakes = minDivision * cakes;
                if (totalCakes >= cakes && totalCakes % peoples == 0) {
                    break;
                }
                minDivision++;
            }
            System.out.println(minDivision);
        }
    }

    private static String[] getStdin() {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> lines = new ArrayList<>();
        while (scanner.hasNext()) {
            lines.add(scanner.nextLine());
        }
        return lines.toArray(new String[lines.size()]);
    }
}

在这里插入图片描述