【发布时间】:2017-02-15 23:48:08
【问题描述】:
这是我的主要方法代码:
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 中的其他变量引用为 calculateBalanceWeights()[0] 数百个它不起作用?
我真的很困惑返回变量是如何被其他方法存储和引用的?
从主要方法中,我可以打印结果数组
System.out.print(Arrays.toString(weCa.calculateBalanceWeights()));
但是输入的数字结果有误?
【问题讨论】:
-
可能是整数除法的情况,即使用 int 变量
1 / 2 == 0