这里是我的主要方法的代码:引用一个方法的输出在同一个类的另一种方法
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' –