Java Scanner输入多行字符串或者多个int数值

1、确定输入行数

//        示例1:
//        输入:
//        9
//        cap
//        to
//        cat
//        card
//        two
//        too
//        up
//        boat
//        boot
//        输出:
//        boat
//        boot
//        cap
//        card
//        cat
//        to
//        too
//        two
//        up

import java.util.*;

public class Test14 {
    public static void main(String[] args) {
        System.out.println("please input:");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        List stringList = new ArrayList<>();
        for(int i = 0; i<= num; i++){
            stringList.add(in.nextLine());
        }
        stringList.remove(0);
        Collections.sort(stringList);
        for(String s : stringList){
            System.out.println(s);
        }
    }
}

2、不确定输入行数

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        inputStr();
        inputInteger();
        inputIntInLine();

    }
    //每行输入一个数值,输入多个数值
    public static void inputInteger() {
        Scanner scanner = new Scanner(System.in);
        String nextLine = scanner.nextLine();
        int sum = 0;

        while (nextLine != null && !nextLine.equals("")) {
            sum += Integer.parseInt(nextLine);
            System.out.println(sum);
            nextLine = scanner.nextLine();
        }

        System.out.println("end of input integer");
    }
    // 每行输入一个字符串,输入多个字符串
    public static void inputStr() {
        Scanner scanner = new Scanner(System.in);
        String nextLine = scanner.nextLine();
        while (nextLine != null && !nextLine.equals("")) {
            System.out.println(nextLine);
            nextLine = scanner.nextLine();
        }

        System.out.println("end of input string");
    }
    //输入多个数值,用空格隔开
    public static void inputIntInLine() {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        String[] numstr = str.split(" ");
        int[] nums = new int[numstr.length];
        for(int i = 0; i < numstr.length; i ++) {
            nums[i] = Integer.parseInt(numstr[i]);
        }
        for(int n: nums) {
            System.out.println(n);
        }
        System.out.println("end of input int in a line");

    }
}

 

你可能感兴趣的:(javaTips)