如果使用Scanner类从键盘读取一系列整数(数目不定),最后以“#”字符结束输入

如果使用Scanner类从键盘读取一系列整数(数目不定),最后以“#”字符结束输入,如何循环读取

用字符串接收,判断字符是否为#

import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        String num=in.next();
        char[] chars = num.toCharArray();
        for (int i=0;i<chars.length;i++){
            if (chars[i]=='#'){
                break;
            }else {
                System.out.print((chars[i]-'0')+" ");
            }
        }
    }
}

img


Scannner input = new Scanner(System.in);
String str = input.next();
while(!str.equals("#")){
  int n = Integer.parseInt(str);
  str = input.next();
.....
}
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<Integer> inputs = new ArrayList<>();
        while (true) {
            String next = sc.next();
            if ("#".equals(next)) {
                break;
            }
            try {
                inputs.add(Integer.parseInt(next));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(inputs);
    }