我是 Java 新手。我在一個類中創建了一個陣列,并為它創建了一個 setter 和 getter。
public class Calculation{
private int[] data;
private int size;
public int[] getData() {
return data;
}
public void setData(int[] data) {
this.data = data;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
我使用陣列創建了一個回圈方法。但它的輸出是 1. Method,
public int ProductOfArray(int data[], int size){
int product = 1;
for (int i =1; i <= getSize(); i ) {
product = product * this.data[i];
}
return product;
}
主要的,
System.out.println("Enter size: ");
int size = num.nextInt();
cal1.setSize(size);
System.out.println("Enter elements of array: ");
[] myArray = new int[size];
for(int i=0; i<size; i ) {
myArray[i] = num.nextInt();
}
System.out.println(cal2.ProductOfArray(myArray, size));
當我運行這個程式時,它顯示最后一個輸出為 1。它不計算用戶輸入。
uj5u.com熱心網友回復:
正如 Thomas 提到的,您需要將 Calculation 實體中的資料(在本例中為 cal1 執行此操作)設定為您從 for 回圈中讀取的資料。這是您可以做到的一種方法:
import java.util.Scanner;
public class TestCalc {
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
System.out.println("Enter size: ");
int size = num.nextInt();
Calculation cal1 = new Calculation();
cal1.setSize(size);
System.out.println("Enter elements of array: ");
int [] myArray = new int[size];
for(int i=0; i<size; i ) {
myArray[i] = num.nextInt();
}
cal1.setData(myArray); //Here is where you set the int array field of the object.
System.out.println(cal1.ProductOfArray(myArray, size));
}
}
class Calculation {
private int[] data;
private int size;
public int[] getData() {
return data;
}
public void setData(int[] data) {
this.data = data;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int ProductOfArray(int data[], int size) {
int product = 1;
for (int i = 1; i < getSize(); i ) {
product = product * this.data[i];
}
return product;
}
}
注意:我已將該類與 main 方法放在同一個檔案中。您可能有一個單獨的檔案,您可以將此類內容復制并粘貼到其中以使其正常作業。我還更改了 for 回圈的邊界(從<=getSize()to <getSize()),因此您不會遇到越界錯誤。
輸出:
Enter size:
5
Enter elements of array:
1
2
3
4
5
120
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/433028.html
下一篇:如何根據條件洗掉行
