java - 在java中找到所有正数的最小值

标签 java algorithm

在寻找给定数字的最小值时,我无法忽略负数。这是我的代码,用于在 java 中打印从用户那里获取 10 个输入的最小数量。 (我是一名新生,也是 java 的新手。如果您发现任何错误,请帮助我解决)

Scanner k = new Scanner (System.in);
int x, y, min;
System.out.println ("enter a number");
x = k.nextInt();
min = x;

for (int count=1; count < 10; count++) {
    System.out.println ("enter a number");
    y = k.nextInt;
    if (y < min) {
        min = y;
    }
}

System.out.println (min);

那是我找到最小数字的代码。但我想找到所有正数中的最小值。如果用户输入负数,那么我想忽略该数字。

帮我编写忽略负数的求最小数的代码。

最佳答案

if(y<min&&y>=0)

你是这个意思吗?

private static Scanner k = new Scanner (System.in);
public static void main(String[] args) {
  int min=getNumber(false);
  for (int count=1; count<10; count++) {
    int y=getNumber(true);
    if(y<min&&y>=0)
      min=y;
  }
  System.out.println(min);
}
private static int getNumber(boolean allowNegative) {
  System.out.println("Please enter an integer:");
  int n=0;
  try {
    n=Integer.parseInt(k.nextLine());
  } catch(NumberFormatException nfe) {
    System.err.println("Input must be an integer...");
    return getNumber(allowNegative);
  }
  if(allowNegative) {
    return n;
  } else {
    if(n<0) {
      System.out.println("You cannot start with a negative number...");
      return getNumber(allowNegative);
    } else {
      return n;
    }
  }
}

关于java - 在java中找到所有正数的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30561275/

相关文章:

algorithm - 如何从购物 list 的多个 bundle 中找到最便宜的产品组合

algorithm - 使用 2^n 步来获得房间中每个可能的人组合

java - 如何设置程序的硬盘位置以供搜索或编辑? ( java )

java - java中的文本转图像

Java OutOfMemory 异常 : mmap error on loading zip file

python - 如何在此类图像中找到最大的空白区域?

python - Python 中的时间复杂度 - 大 O 表示法

java - 使用鼠标单击在 JLabel 中拖动和移动图片

java - 制作一个能够识别参数类型并相应调用其常用方法的方法

c++ - 实现 pow(x, n)