我在考試中遇到問題。起初它很容易。讓我來解釋這個問題:從單一方法返回多個值
使用戶指定多少整數希望把(陣)
號碼應該在1500 -1500之間
- (整蠱):創建方法計算投入數量的百分比,多少百分比是0,正數,負數。 (所有這一切都應該是在一個方法,沒有返回字符串,字符串緩衝區,返回的結果應該是一個double值)
我覺得我做了正確的,但是當我在實時測試它,我運行的問題是它返回值0.0,0.0,0.0 ...或者它只在值處於相同條件(例如全零)時才返回正確的百分比。
這裏是我的代碼:(我希望你能理解它)。我只是好奇,我不知道如何解決它。我也嘗試過使用靜態方法,但遇到同樣的問題。
import java.util.Scanner;
public class nPNZ {
public int [] number;
public nPNZ (int [] n){
number = n;
}
public double [] allCalcs(){
int countPos = 0; int countNeg = 0; int countZero = 0;
for (int i = 0; i < number.length; i++) {
if (number[i] == 0) {
countZero++;
}else if (number[i] > 0){
countPos++;
}else{
countNeg++;
}
}
//0 = 0 ; 1 = positive ; 2 = negative
double total [] = new double [3];
total[0] = (countZero/number.length)*100;
total[1] = (countPos/number.length)*100;
total[2] = (countNeg/number.length)*100;
return total;
}
public static void main (String args[]){
//min 20 number, -1500 to 1500
Scanner input = new Scanner (System.in);
final int MIN_SIZE = 5;
int size = 0;
while(size < MIN_SIZE){
System.out.println("Specify the size of the array: ");
size = input.nextInt();
while(size<MIN_SIZE){
System.out.println("Size should be greater than: " + MIN_SIZE);
size = input.nextInt();
}
}
input.nextLine();
int num [] = new int [size];
for (int i = 0; i < num.length; i++) {
System.out.println("Write number " + (i+1) + " : ");
num[i] = input.nextInt();
while(num[i] < -1500 || num[i] > 1500) {
System.out.println("The number should within the range of -1500 and 1500");
num[i] = input.nextInt();
}
}
nPNZ n = new nPNZ (num);
System.out.println("Percentage of zero numbers is: " + n.allCalcs()[0]);
System.out.println("Percentage of positive numbers is: " + n.allCalcs()[1]);
System.out.println("Percentage of negative numbers is: " + n.allCalcs()[2]);
}
}
你面臨什麼問題? –
說:我把5個數字,如果他們都說:0,0,0,0,0 ---我從輸出得到一個正確的問題: 零數字的百分比是:100.0 正數nubers是:0.0 負數的四氯乙烯是:0.0 但是,如果我把要說:0,0,0,3,-1 輸出如下: 零號的四氯乙烯是:0.0 正量擬合選取的PERZ是: 0.0 負數的二次方程式爲:0.0 –