[英]Java: Making a program keep prompting for user input when they enter nothing
[英]Java Program does nothing with input (
对于我的编程课程作业,我有一个程序,该程序需要随机取一个正整数,然后选择第二小的整数。 我相信一切都已正确编码,但是当我执行程序并输入整数时,程序会跳到下一行,并且什么也不做。 我可能会忽略菜鸟的错误吗?
这是代码:
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();
}
}
如果有人可以给我一个小提示或其他东西,那将是很好的。 谢谢!
我认为您可能希望使用使用空格的定界符或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();
}
}
还有一件事是您应该处理用户仅输入一个整数的异常情况。 除此之外,您的代码也可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.