如何在java中为该程序获取不等数?

如何在java中为该程序获取不等数?,java,Java,我已经编写了这段代码,但我想知道,当用户输入的数字不相等时,我如何使用这个程序来实现这一点?您所拥有的非常接近,但为了确保您获得3个唯一的数字,并准确返回中间的数字,我建议使用以下方法 //to display second smallest number out of three import java.util.*; public class Prog { public static void main(String[] args) { Scanner in = new

我已经编写了这段代码,但我想知道,当用户输入的数字不相等时,我如何使用这个程序来实现这一点?

您所拥有的非常接近,但为了确保您获得3个唯一的数字,并准确返回中间的数字,我建议使用以下方法

//to display second smallest number out of three  
import java.util.*;
public class Prog
{
  public static void main(String[] args)
  {
    Scanner in = new Scanner (System.in);
    int a,b,c,d,e;
    System.out.println("Enter three numbers");
    a = in.nextInt();
    b = in.nextInt();   
    c = in.nextInt();
    d = Math.min(a, b);
    e = Math.max(d,c);
    System.out.println(+e);
  }
}
publicstaticvoidmain(字符串[]args){
列出enteredValues=getEnteredValues();
如果(enteredValues.size()!=3){
//出了点大问题,但为了安全起见
}否则{
int a=输入的值。获取(0);
int b=输入的值。获取(1);
int c=输入的值。get(2);
int min=Math.min(a,Math.min(b,c));
int max=Math.max(a,Math.max(b,c));
如果(a>min&&amin&&b
这样做的目的是首先从用户那里获取3个数字。如果集合是唯一的,则只需将其输入添加到集合中,即可强制用户输入3个唯一的数字

从用户那里获取数字后,它将使用Math.min和Math.max来获取所有3个数字之间的最小值和最大值。然后,它只是一个简单的if/else树,以确定哪一个位于计算的最小值/最大值之间


我希望这有帮助!

这是根据您的问题和问题中的评论,您将只有3个输入,您希望找到第二个最小值,并且您只能使用最小值和最大值。 如果不是这样,请更新问题,以获得您想要的问题的正确答案

public static void main(String[] args) {
    List<Integer> enteredValues = getEnteredValues();
    if (enteredValues.size() != 3) {
        // something went terribly wrong, but just to be safe
    } else {
        int a = enteredValues.get(0);
        int b = enteredValues.get(1);
        int c = enteredValues.get(2);
        int min = Math.min(a, Math.min(b, c));
        int max = Math.max(a, Math.max(b, c));
        if (a > min && a < max) {
            // a is mid
        } else if (b > min && b < max) {
            // b is mid
        } else {
            // c is mid
        }
}

private static List<Integer> getEnteredValues() {
    Scanner in = new Scanner(System.in);
    List<Integer> enteredValues = new LinkedList<>();
    System.out.println("Enter 3 unique numbers");
    while (enteredValues.size() < 3) {
        Integer enteredValue = in.nextInt();
        if (enteredValues.contains(enteredValue)) {
          // probably prompt them to enter another number
        } else {
            enteredValues.add(enteredValue);
        }
    }
    return enteredValues;
}

你的意思是强迫用户输入不相等的数字?或者我不能正确理解你的问题?在问题中,它说接受三个数字,并使用math.max和math.min显示第二个最小的数字,那么有没有办法得到三个“不相等的数字”或者这是正确的方法。是的,例如:示例输入:31,82,61。示例输出:61将您的号码存储在一个集合中,例如,检查集合中是否已包含用户提交的号码。如果该集合中包含“不接受号码”,只需打印smth,如“号码应唯一,请输入另一个号码”,然后等待下一个号码出现bmitted from userUse collections。许多人在评论中也提出了同样的建议。使用任何Java集合进行排序,您的答案将是最后一个中间数字/最后一个但只有一个数字(从最小的一侧)这就是为什么我在回答中提到这将解决3个数字的原因。这显示了正确的结果,但带有相反的符号,我如何更正它?最小值和最大值将为任何值提供正确的输出。我是说,如果答案为4,结果显示“-4”,但我通过更改来更正:
System.out.println(d-(e+f))是的!我修改了
  int d=a+b+c;
  int e=Math.max(a,Math.max(b,c));
  int f=Math.min(a,Math.min(b,c));
  System.out.println(d-(e+f));