2017-02-19 47 views
2

如何确保0不作为最小值?我已经确定答案不是一个负数,但现在我不知道如何排除0作为输入,当它被按下以便找到最小值时。Java程序接受int值直到用户输入一个零,然后找到最小正整数

import java.util.Scanner; 
public class Q2 
{ 
public static void main (String [] args) 
{ 
    System.out.println("Write a list of integers and type 0 when you are finished"); 
    Scanner kb=new Scanner(System.in); 
    int input=kb.nextInt(); 
    int smallestValue=Integer.MAX_VALUE; 
    boolean negative=false; 
    do{ 
     input=kb.nextInt(); 
     if(!negative){ 
      smallestValue=input; 
      negative=false; 
     } 
     if (input<smallestValue){ 
      smallestValue=input; 
     } 
    } 
    while(input!=0); 
    System.out.println(smallestValue+">0"); 
    } 
}  

回答

1

我会建议使用while循环,而不是dowhile环

System.out.println("Write a list of integers and type 0 when you are finished"); 
Scanner kb=new Scanner(System.in); 
int input=kb.nextInt(); 
int smallestValue=Integer.MAX_VALUE; 

while(input!=0){//loop until user inputs 0 
    if(input>0) {//check for inputs greater than 0 and ignore -ve values 
     if(input<smallestValue) // save the smallest value 
      smallestValue = input; 
    } 
    input=kb.nextInt(); 
} 
System.out.println(smallestValue+">0"); 
+0

谢谢,Aditya –

+0

Np。如果解决了您的问题,请接受答案 –

0

测试,这不是0小于smallestValue。更改

if (input<smallestValue){ 

if (input != 0 && input<smallestValue){ 

但是,你的算法的休息似乎是一个小缺陷。我想你想,

// if(!negative){ 
// smallestValue=input; 
// negative=false; 
// } 
if (input > 0) { 
    smallestValue = Math.min(smallestValue, input); 
} 

你目前也放弃了第一个值。一个完整的工作示例

public static void main(String[] args) { 
    System.out.println("Write a list of integers and type 0 when you are finished"); 
    Scanner kb = new Scanner(System.in); 
    int smallestValue = Integer.MAX_VALUE; 
    int input; 
    do { 
     input = kb.nextInt(); 
     if (input > 0) { 
      smallestValue = Math.min(input, smallestValue); 
     } 
    } while (input != 0); 
    System.out.println(smallestValue + " > 0"); 
} 

可以还写了一个内部if作为

if (input > 0 && input < smallestValue) { 
    smallestValue = input; 
} 
+0

没有,很遗憾。我已经尝试过了,它不起作用 –

相关问题