這裏是我的主要方法的代碼:引用一個方法的輸出在同一個類的另一種方法
public class WeightCalculatorTest {
public static void main(String[] args) {
WeightCalculator weCa_init = new WeightCalculator(100);
weCa_init.displayWeight();
WeightCalculator weCa_def = new WeightCalculator();
weCa_def.displayWeight();
WeightCalculator weCa = new WeightCalculator(123);
weCa.setWeight();
weCa.displayWeight();
}
}
這裏是方法:
import java.util.Scanner;
public class WeightCalculator {
private int weight = 0;
private int hundreds;
private int fifties;
private int twenties;
private int tens;
private int fives;
private int ones;
private int total;
private int[] result;
// Default constructor
public WeightCalculator()
{
weight=0;
System.out.println();
}
// Initial constructor
public WeightCalculator(int w)
{
weight=w;
System.out.println();
}
public void setWeight() {
Scanner keyboard = new Scanner (System.in);
System.out.println("Life needs a balance");
System.out.print("How many pounds does the item weight? ");
weight = keyboard.nextInt();
}// end inputWeight
public int[] calculateBalanceWeights() {
hundreds = weight/100;
weight %= 100;
fifties = weight/50;
weight %= 50;
twenties = weight/20;
weight %= 20;
tens = weight/10;
weight %= 10;
fives = weight/5;
ones = weight %5;
total = hundreds+fifties+twenties+tens+fives+ones;
int [] result = {hundreds, fifties, twenties, tens, fives, ones, total};
return result;
}// end calcDays
public void displayWeight() {
System.out.println("You need "+calculateBalanceWeights()[6]+" weights in total:");
System.out.println(" "+hundreds +" 100 lbs");
System.out.println(" "+fifties +" 50 lbs");
System.out.println(" "+twenties +" 20 lbs");
System.out.println(" "+tens +" 10 lbs");
System.out.println(" "+fives +" 5 lbs");
System.out.println(" "+ones +" 1 lbs");
}// end of display
}// end of class Time
我的問題是在我這部分代碼:
System.out.println("You need "+calculateBalanceWeights()[6]+" weights in total:");
爲什麼如果我引用總量它不起作用 - 顯示0,而其他變量可以通過名稱引用。如果我在displayWeight中將其他varibales作爲calculateBalanceWeights()[0]引用數百,那麼它不起作用?
我真的很困惑如何返回變量存儲和引用其他方法?
ASLO從主要方法我可以打印與
System.out.print(Arrays.toString(weCa.calculateBalanceWeights()));
但結果是錯誤的數量進入結果陣列?
也許是一種整數除法的情況,即在方法中使用int變量'1/2 == 0' –