用扫描仪循环

时间:2016-10-12 05:43:10

标签: java java.util.scanner

我正在尝试制作一个三角形数字生成器,询问用户希望它们生成多少个三角形数字。 这些是我的错误:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at TriangularNumbers.main(TriangularNumbers.java:11)


    import java.util.Scanner;

    public class TriangularNumbers {
        public static void main(String args[]) {
            while(true){
                long tnumber = 1L;
                long amount = 2L;
                System.out.println("Welcome to the triangular numbers           calculator!");
                System.out.println("Type in the amount of triangular numbers to be generated!");
                Scanner reps = new Scanner(System.in);
                long repeats = reps.nextInt();
                reps.close();
                long i = 0L;
                while (i < repeats) {
                    i = i + 1;
                    System.out.println(i + ". " + tnumber);
                    tnumber = tnumber + amount;
                    amount = (amount + 1);
                }
                System.out.println("Done generating!");
            }
        }

    }

一切正常,直到达到第二个用户输入的阶段。

2 个答案:

答案 0 :(得分:-1)

为什么你不能这样试试。?

import java.util.Scanner;

public class TriangularNumbers {
    public static void main(String args[]) {
        Scanner reps = new Scanner(System.in);
        while(true){
            long tnumber = 1L;
            long amount = 2L;
            System.out.println("Welcome to the triangular numbers           calculator!");
            System.out.println("Type in the amount of triangular numbers to be generated!");

            long repeats = reps.nextInt();
            if(reps == 0L) break; //Considering reps ==0 as the terminating condition to get out of the loop
            long i = 0L;
            while (i < repeats) {
                i = i + 1;
                System.out.println(i + ". " + tnumber);
                tnumber = tnumber + amount;
                amount = (amount + 1);
            }
            System.out.println("Done generating!");
            reps.nextLine(); // Has to be there in case of run out of tokens
        }
        reps.close();
    }

}

答案 1 :(得分:-2)

请改变这样的代码:

 long tnumber = 1L;
    long amount = 2L;
    System.out.println("Welcome to the triangular numbers           calculator!");
    System.out.println("Type in the amount of triangular numbers to be generated!");
    Scanner reps = new Scanner(System.in);
    long repeats = reps.nextInt();
    reps.close();
    long i = 0L;
    do {
        i = i + 1;
        System.out.println(i + ". " + tnumber);
        tnumber = tnumber + amount;
        amount = (amount + 1);
        System.out.println("Done generating!");
    } while (i < repeats);