Java程序对输入没有任何作用(

时间:2014-09-11 07:54:31

标签: java input

对于我的编程课程作业,我有这个程序,需要取一个随机数的正整数,然后选择第二个最小的整数。我认为everthing编码正确,但是当我执行程序并输入整数时,程序会跳到下一行并且什么都不做。我可能会忽视一个菜鸟的错误吗?

这是代码:

package SecondSmallest;

import java.io.PrintStream;
import java.util.Scanner;

public class SecondSmallest {

//Name:         Ben den Drijver
//Assignment:   SecondSmallest
//Date: 10      september 2014

PrintStream out;

SecondSmallest(){
    out = new PrintStream(System.out);
}

void start(){
    Scanner in = new Scanner(System.in);

    out.printf("Enter a series of integers: ");
    int smallest = in.nextInt(),
        secondSmallest = in.nextInt();

    while (in.hasNext()){               
        int n = in.nextInt();

        if (n < smallest){
            secondSmallest = smallest;
            smallest = n;
        } else 
            if (n < secondSmallest && n > smallest){
                secondSmallest = n;
            }           
    }
    out.printf("The second smallest number is: %d", secondSmallest);
}
public static void main (String[] argv) {
    new SecondSmallest().start();
}
}

如果有人可以给我一点点暗示,那就太棒了。谢谢!

1 个答案:

答案 0 :(得分:1)

我认为您希望使用 space enter 来使用分隔符。 而且您可能还希望仅扫描数字并将非数字字符检测为限制器

您可以尝试这样的事情:

import java.io.PrintStream;
import java.util.Scanner;

public class SecondSmallest {

//Name:         Ben den Drijver
//Assignment:   SecondSmallest
//Date: 10      september 2014
    PrintStream out;

    SecondSmallest() {
        out = new PrintStream(System.out);
    }

    void start() {
        Scanner in = new Scanner(System.in);
        in.useDelimiter("[ \n]"); // --> your delimiter

        out.printf("Enter a series of integers: ");
        int smallest = in.nextInt();
        int secondSmallest = in.nextInt();

        while (in.hasNext("[0-9]*")) { //--> scan only numeric values for your "SecondSmallest" process
            int n = in.nextInt();

            if (n < smallest) {
                secondSmallest = smallest;
                smallest = n;
            } else if (n < secondSmallest && n > smallest) {
                secondSmallest = n;
            }
        }
        in.close();
        out.printf("The second smallest number is: %d", secondSmallest);
    }

    public static void main(String[] argv) {
        new SecondSmallest().start();
    }
}

还有一件事是你应该处理用户只输入一个整数的异常情况。 除此之外,您的代码工作正常。