0

我正在尝试创建一个程序,它接受两个数字并输出一个数字中大于另一个数字的最小数字(例如,给定 4687 和 5,程序应该输出 6)。

我遇到的问题是,当我编译程序时,即使我没有收到错误,在输入两个数字后,也没有显示任何输出。光标只是继续在它所在的位置闪烁。这是代码:

    import java.io.*;
    import java.util.*;
    public class Numbers {
      public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    int smallest = 10;
    int num;
    System.out.printf("Enter a value for n: \n");
    int n = in.nextInt();
    System.out.printf("Enter a value for num: \n");
    num = in.nextInt();
    int ch = System.in.read();
    while (ch>n && ch<smallest) {
            smallest=ch;
            ch = System.in.read();
    }
    System.out.printf("Smallest number that is larger is %d", smallest);
}
}
4

1 回答 1

1

我运行你的程序就好了。您遇到的可能只是程序正在等待您不希望输入的输入。

  • 它期待用户的三个输入,你是这样运行它的吗?
  • 输入数字后,您还记得按键盘上的回车键吗?

这是您的程序的示例输出:

Enter a value for n: 
100
Enter a value for num: 
2
0 // <-- This value corresponds to your program prompting for int ch = System.in.read(); 
Smallest number that is larger is 10D

提示:您可能希望将输入的 n 值转换为 a String,然后使用toCharrArray()on 方法,String这样您就可以遍历每个字符,就像您在while循环中所做的那样。

尝试类似:

for(char ch : Integer.toString(n).toCharArray()) { 
// rest of your while loop logic

}
于 2014-03-22T00:59:54.587 回答