有 Java 编程相关的问题?

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

不带数组的java Int序列

嘿,我真的很困惑,我需要在不使用数组的情况下生成一个整数序列,当你给其中一个0的值时,它必须问你要输入多少个数字?我真的是个新手,我一直在努力


共 (2) 个答案

  1. # 1 楼答案

    我对您所问问题的理解是,您希望读取整数(从stdin)直到输入值0,因此,您可以这样做:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.LinkedList;
    
    public class ReadInts {
    
        public static void main(String[] args) throws IOException {
            LinkedList<Integer> list = new LinkedList<>();
    
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String line = br.readLine();
            while (line != null) {
                // without error checking
                int val = Integer.valueOf(line);
                if (val == 0) {
                    br.close();
                    break;
                }
                list.add(val);
                line = br.readLine();
            }
            // print at the end, just to check
            System.out.println(list);
        }
    }
    
  2. # 2 楼答案

    你的问题更让人困惑。。。总之,只需使用List,然后就可以添加任意多的值。如果只需要保留唯一的值,请使用Set

    List integerSequence = new ArrayList();
    integerSequence.add(1);
    ...
    integerSequence.add(n);