2017-02-19 48 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

沒有,很遺憾。我已經嘗試過了,它不起作用 –

相關問題