您好我是一个初学者并尝试一个简单的输入/输出程序进行练习,整个程序在我的Eclipse编译器中运行,但结果类似于
输入维护费用:87
输入学费:67
输入Utility Bills:98
输入杂货费用:88
总费用: 88(这是我输入的最后一个值的问题)
import java.util.Scanner;
public class budgetSystem {
Scanner userInput = new Scanner(System.in);
private static Scanner userInput2;
public static void main(String[] args){
int utilityBills = 0;
int maintainceExp = 0;
int schoolExp = 0;
int groceryExp = 0;
int totalExp = 0;
userInput2 = new Scanner(System.in);
System.out.println("Enter Maintaince Expance:");
utilityBills = userInput2.nextInt();
System.out.println("Enter School Fees:");
utilityBills = userInput2.nextInt();
System.out.println("Enter Utility Bills:");
utilityBills = userInput2.nextInt();
System.out.println("Enter Grocery Expance:");
utilityBills = userInput2.nextInt();
totalExp= utilityBills + maintainceExp + schoolExp + groceryExp;
System.out.println("Total Expance: " + totalExp);
}
} // END OF BUDGET SYSTEM
答案 0 :(得分:2)
对于您重新分配utilityBills
变量的每一步,请更改以下代码:
System.out.println("Enter Maintaince Expance:");
utilityBills = userInput2.nextInt();
要
System.out.println("Enter Maintaince Expance:");
utilityBills += userInput2.nextInt();
在您输入的每个输入中,这将打印正确的输出。
答案 1 :(得分:1)
您一直覆盖变量utilityBills
。
将您的代码更改为:
System.out.println("Enter Maintaince Expance:");
maintainceExp = userInput2.nextInt();
System.out.println("Enter School Fees:");
schoolExp = userInput2.nextInt();
System.out.println("Enter Utility Bills:");
utilityBills = userInput2.nextInt();
System.out.println("Enter Grocery Expance:");
groceryExp = userInput2.nextInt();
答案 2 :(得分:1)
每次扫描一个值并将其分配回{utilityBills}时,请在程序中设置相应的变量。您最后输入的值是88,它是为{utilityBills}设置的,其余所有变量仍为零,从不设置为任何值。更改您的代码如下。
System.out.println("Enter Maintaince Expance:");
maintainceExp = userInput2.nextInt();
System.out.println("Enter School Fees:");
schoolExp = userInput2.nextInt();
System.out.println("Enter Utility Bills:");
utilityBills = userInput2.nextInt();
System.out.println("Enter Grocery Expance:");
groceryExp = userInput2.nextInt();
totalExp= utilityBills + maintainceExp + schoolExp + groceryExp;
答案 3 :(得分:0)
您正在保存utilityBills
中的每个值,而不是正确的变量。这就是为什么每隔一个值为0,然后将总数设置为最后输入的值。