【发布时间】:2017-12-04 23:23:46
【问题描述】:
我正在编写代码,询问用户的姓名、他们有多少工作以及这些工作的收入。然后代码会找到最高和最低的收入,以及他们输入的工作的平均值。
我遇到了最高和最低支付部分的问题,以及找到平均数,同时仍保留用户输入的内容以便以后复述。
例如: 输入:10000 30000 50000 “你好,奥黛丽。你有 3 个工作。最高薪工作支付 50000 美元。最低薪工作支付 10000 美元。输入的工作的平均工资是 30000 美元
**** 这里是我编辑的代码,但运行不正常。我相信它与int和double有关。我不确定哪些代码应该是 double 的,哪些应该是 int.****
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();
Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();
//Declarations
int total = 0;
int average = 0;
//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
System.out.println("Enter the income of job #" + i + " : ");
arrayOfIncomes[i] = scan.nextInt();
total = total + arrayOfIncomes[i];
}
average = total/jobNum;
//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] > max) {
max = arrayOfIncomes[i];
}
}
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] < min) {
min = arrayOfIncomes[i];
}
}
//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
System.out.println("");
} else {
System.out.println("Goodbye.");
}
//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);
//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
out.close();
}
【问题讨论】:
-
剩下的代码在哪里?
-
这就是我目前所拥有的一切
-
声明一个变量来保存最低工资和另一个用于最高工资的变量。然后另一个保存所有工资的总和,另一个保存输入了多少工资。在适当的地方更新这些变量,你应该能够得到你想要的。
-
制作一个数组或其他东西来保存工作工资的多少,这样您就可以在这些价格上进一步操作。