簡體   English   中英

如何重寫for循環以將字符串更改為int / double?

[英]How can I rewrite for loop to change string to int/double?

我在學校用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) ");
        }
}   
}

在這里,您將字符串解析為雙精度型:

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

但是,在接下來的一行中,您嘗試將字符串與數字進行比較:

if(args[i] > highest)

使用x代替:

if(x > highest)

“錯誤:二進制運算符'<'的錯誤的操作數類型”

這是因為您正在嘗試將字符串args[i]highest的double進行比較。 您已經將args[i]轉換為double,即x 確保在比較中使用x ,即if(x > highest)

“錯誤:類型不兼容:字符串無法轉換為雙精度”

同樣,您忘記了使用新的double x 確保在作業中使用x ,例如, highest = x;

如果您使用的是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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM