我需要创建一个程序,提示用户输入工资并获得最高和最低工资。我已经工作了4天了。我终于创建了我的程序使用的一些教程互联网,但我只有一个问题...我只是无法将INT转换为Double @ @它让我头疼..我哪里出错了?有人能帮我吗?我需要传递java类; ;
这是代码:
import java.util.*;
public class HighestLowestSalary
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many salary do you want to enter?: ");
int sal = input.nextInt();
//starting here should be double already..
System.out.println("Enter the "+sal +" salaries");
int[]salary = new int[sal];
for (int i=0; i<sal; i++)
{
salary[i]=input.nextInt();
}
System.out.println("The Highest Salary is: " +high(salary));
System.out.println("The Lowest Salary is: " +low(salary));
}
public static int high(int[] numbers)
{
int highsal = numbers[0];
for (int i=1; i<numbers.length;i++){
if (numbers[i] > highsal){
highsal = numbers[i];
}
}
return highsal;
}
public static int low(int[] numbers){
int lowsal = numbers[0];
for (int i=1;i<numbers.length;i++){
if (numbers[i] < lowsal){
lowsal = numbers[i];
}
}
return lowsal;
}
}
任何能帮助我并教我如何将其转换为双倍的人?提前谢谢你..
答案 0 :(得分:4)
嗯...要将int
转换为double
,您只需指定它即可。赋值将导致“原始扩展转换”发生;见JLS 5.1.2。
int myInt = 42;
double myDouble = myInt; // converts to a double.
(原始扩展转换不需要进行类型转换......虽然添加一个不会造成伤害。)
将int数组转换为double数组....
int[] myInts = ....
double[] myDoubles = new double[myInts.length];
for (int i = 0; i < myInts.length; i++) {
myDoubles[i] = myInts[i];
}
答案 1 :(得分:3)
您可以将int值分配为double,如:
int n = 1;
double j = n;
System.out.println(j);
Output:
1.0
注意:使用nextDouble
api代替nextInt
答案 2 :(得分:1)
由于你的帮助,我能够解决问题!这就是我所做的......就像每个人都说要将int转换为Double
//this is where I changed all the int to double
System.out.println("Enter the "+sal +" salaries");
double[]salary = new double[sal];
for (int i = 0; i<sal; i++){
salary[i] = input.nextDouble();
}
System.out.println("The Highest Salary is: " +high(salary));
System.out.println("The Lowest Salary is: " +low(salary));
}
public static double high(double[] numbers)
{
double highsal = numbers[0];
for (int i=1; i<numbers.length;i++){
if (numbers[i] > highsal){
highsal = numbers[i];
}
}
return highsal;
}
public static double low(double[] numbers){
double lowsal = numbers[0];
for (int i=1;i<numbers.length;i++){
if (numbers[i] < lowsal){
lowsal = numbers[i];
}
}
return lowsal;
}
}