如何重写for循环以将字符串更改为int / double?

时间:2018-06-21 20:42:00

标签: java

我正在用Java在学校里写,用户输入的最低和最高整数(从字符串更改)。由于“错误的二进制运算符'>'的操作数类型”和“不兼容的类型:字符串无法转换为双精度”,所以在第36-39行我无法编译它(该类有些奇怪的东西)

public class average2{

// accept string args
public static void main( String[] args ){

    //initialize variables 
    double x = 0;
    double temp = 0;
    double sum = 0;
    double avg = 0;
    double highest = 0;
    double lowest = 0;

    System.out.print("java average ");
    for(String arg:args){
        System.out.print(arg);
        System.out.print(" ");
        //x = Double.parseDouble(args[ i ]);

    }

        System.out.println("");
        System.out.println("Welcome to the Average Program. It is rather average.");

        // add numbers
        for( int i = 0; i< args.length; i++ ){      
            // convert string to either double or int 
            x = Double.parseDouble(args[ i ]);
            temp = ( x + sum);
            sum = temp; 
        }

        //find highest value
        for( int i = 1; i< args.length; i++ ){
            x = Double.parseDouble(args[ i ]);
            if(args[i] > highest)
                highest = args[i];
            else if(args[i] < lowest)
                lowest = args[i];
            //display answer
            System.out.println( "The highest given value: " + highest);
            System.out.println( "The lowest given value: " + lowest);
        }   

        if ( args.length > 0 ){

            // do math add numbers divide by length
            avg = sum / args.length;

            // display answer
            System.out.println( "The average is: " + avg);
        }

            // test for null input
        else if( args.length == 0 ){
            System.out.println( "Usage java average X (where X is a list of integers) ");
        }
}   
}

3 个答案:

答案 0 :(得分:1)

在这里,您将字符串解析为双精度:

x = Double.parseDouble(args[ i ]);

但是,在接下来的一行中,您尝试将字符串与数字进行比较:

if(args[i] > highest)

改为使用x

if(x > highest)

答案 1 :(得分:0)

  

“错误:二进制运算符'<'的错误操作数类型

这是因为您试图将字符串args[i]highest的双精度进行比较。您已经将args[i]转换为双精度值,即x。确保在比较中使用x,即if(x > highest)

  

“错误:类型不兼容:字符串无法转换为双精度”

同样,您忘记使用新的双精度x。确保在作业中使用x,例如highest = x;

答案 2 :(得分:0)

如果您使用的是Java 8,则可以在一行中获取所有统计信息...

DoubleSummaryStatistics doubleSummaryStatistics = Arrays.stream(args).mapToDouble(Double::parseDouble).summaryStatistics();

完整的代码示例是

public static void main( String[] args ){
    DoubleSummaryStatistics doubleSummaryStatistics = Arrays.stream(args).mapToDouble(Double::parseDouble).summaryStatistics();
    System.out.println(doubleSummaryStatistics.getMin());
    System.out.println(doubleSummaryStatistics.getMax());
    System.out.println(doubleSummaryStatistics.getAverage());
    System.out.println(doubleSummaryStatistics.getSum());
}