gpt4 book ai didi

java - 如何使用 Scanner 以一个整数获取存储输入

转载 作者:行者123 更新时间:2023-12-04 21:00:51 24 4
gpt4 key购买 nike

我怎样才能让问题的数量与用户输入的职位数量相同。例如,假设你从事过 5 份工作,我希望程序让用户询问,工作 1 的薪水工作 2工作 3工作 4作业 5,依此类推。我现在的代码是。

 import java.util.Scanner;
public class Personal_Info {
public static void main(String[] args) {


Scanner Scanner = new Scanner(System.in);

int Salary1;
int Salary2;
int Salary3;
int TotalJobs;
int Average;
String Name;
int Largest;
int Smallest;
int Sum;


System.out.print("What is your first name?: ");
Name = Scanner.nextLine();

System.out.print("How many jobs have you had?: ");
TotalJobs = Scanner.nextInt();

System.out.print("Enter income from job #1: ");
Salary1 = Scanner.nextInt();

System.out.print("Enter income from job #3: ");
Salary2 = Scanner.nextInt();

System.out.print("Enter income from job #3: ");
Salary3 = Scanner.nextInt();
Sum = Salary1 + Salary2 + Salary3;
Average = Sum / TotalJobs;

Largest = Salary1;
Smallest = Salary1;

if(Salary2 > Largest)
Largest = Salary2;

if(Salary3 > Largest)
Largest = Salary3;

if(Salary2 < Smallest)
Smallest = Salary2;

if (Salary3 < Smallest)
Smallest = Salary3;

System.out.println("Hello " + Name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + Largest + ". The lowest paying job paid is "+ Smallest + ". The average is " + Average + ".");

但它不会工作,因为它只会询问用户三次,作业 1、2 和 3。

如果我尝试,

for (int x = 0; x<TotalJobs; x++){ 
System.out.print("How many jobs have you had?: ");
number = Scanner.nextInt();

我不知道如何从存储的“数字”值中获取最高/最小/平均值。

最佳答案

希望对你有帮助

    class SalaryCalculate{
public static void main(String args[]){
int totalJobs,jobcounter,maxSalary,minSalary,averageSalary=0;;
int[] jobsincome;
String name;
Scanner sc= new Scanner(System.in);
System.out.println("Enter your name");
name=sc.nextLine();
System.out.println("How many jobs you had");
totalJobs= sc.nextInt();
jobsincome= new int[totalJobs];
for(int i=0;i<totalJobs;i++){
jobcounter=i+1;
System.out.println("Enter the income for your job "+jobcounter);
jobsincome[i]=sc.nextInt();
averageSalary=averageSalary+jobsincome[i];
}
jobsincome=average(jobsincome);
maxSalary=jobsincome[totalJobs-1];
minSalary=jobsincome[0];
averageSalary=averageSalary/totalJobs;
System.out.println("Hi "+name+" your min salary is "+minSalary+" max salary is "+maxSalary+" average salary is "+averageSalary);
}
public static int[] average(int jobsincome[]){
int length=jobsincome.length;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if(jobsincome[i]>jobsincome[j]){
int temp=jobsincome[j];
jobsincome[j]=jobsincome[i];
jobsincome[i]=temp;
}
}
}
return jobsincome;
}
}

关于java - 如何使用 Scanner 以一个整数获取存储输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47524404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com