2

I am trying to create a program that asks a user for a sentinel value (a value to enter when they want to end the list). It then asks the user to enter numbers until they re-enter the sentinel value. It then figures out the max number in the list. I'm very new to Java, and whenever I run the program is just asks for the sentinel value then does nothing else (never pops up the second input dialog). I'm sure it's something simple that I'm doing wrong, but I can't figure it out. Thanks for any help.

import java.util.*; 

import javax.swing.JOptionPane;
public class HW1 {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);
    int number;
    int max;
    int sentinel;
    int count=0;

    JOptionPane.showInputDialog("Please enter a sentinel value: ");
    sentinel=input.nextInt();

    JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
    number = input.nextInt();
    max = number;
    while (number!=sentinel){
        count +=1;
        if (number>max)
            max=number;
        JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
        number = input.nextInt();
    }
    if (count!=0){
        JOptionPane.showMessageDialog(null, "The max is:" + max);
    }
  }
 }
4

2 回答 2

2

您正在混合将数据输入程序的方式。让我们开始:

Scanner input = new Scanner(System.in);

上面的行允许您从键盘捕获命令行中的数据。

JOptionPane.showInputDialog("Please enter a sentinel value: ");

此选项窗格显示正确,您输入了一个值,然后什么也没有发生。这是因为您的程序正在等待在命令行中输入内容

sentinel=input.nextInt();

当您的程序到达上面的行时,input.nextInt()程序会停止,直到您在命令行中输入一些内容。

正确的方法应该是这样的:

sentinel = Integer.parseInt(JOptionPane.showInputDialog("Please enter a sentinel value: "));
number = Integer.parseInt(JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" value to end."));

并删除:

number = input.nextInt();
sentinel=input.nextInt();
于 2013-09-13T00:35:07.360 回答
2

我认为混乱是这样的:

  • JOptionPane 打开一个输入对话框

  • when the option pane closes, whatever you put there is ignored

  • 然后代码转到这一行 sentinel=input.nextInt();

    等待来自控制台的输入(例如,您需要返回控制台,在此处键入数字并按回车键,然后程序才会前进,它会阻塞直到您这样做)

我会把它改成这样:

  String sentinelInput = JOptionPane.showInputDialog("Please enter a sentinel value: ");
  sentinel= Integer.parseInt(sentinelInput);

(对您期望输入的所有地方重复)

另一种解决方案是

不要使用 JOptionPane,而只是System.out.println打印用户输入请求(而不是弹出对话框)。然后你可以并保留现有的input.nextInt()电话来收集它。

请注意,所有交互都将在控制台中进行,没有任何弹出对话框(在用户体验方面我实际上更喜欢它,而且它将在非 GUI 机器上工作,例如 linux 终端......)

于 2013-09-13T00:27:23.283 回答