簡體   English   中英

將正整數轉換為負值

[英]Converting a positive integer to have a negative value

因此,今天在上課時,我們不得不創建一個程序,要求輸入介於-25到25之間的值,並在輸入超出這些值的數字時退出該程序。 當我嘗試輸入大於25或負值的任何數字時,程序崩潰,並彈出錯誤報告。

所以這是我的問題,如何使這些負值發揮作用。 我在下面提供了該程序,以幫助任何願意解決此問題的人。

import java.util.Scanner;
public class Program2 
{

    public static void main(String[] args) 
    {
        Scanner scan = new Scanner (System.in);
        int occurrences[] = new int [51];

        System.out.println ("Enter integers in the range if -25 through 25.");
        System.out.print ("Signal end with a");
        System.out.println ("number outside the range.");

        int entered = scan.nextInt();       
        while (entered >= -25 && entered <= 25)
        {
           occurrences [entered] ++;
           entered = scan.nextInt();
        }

        System.out.println ("Number\tTimes");
        for (int check = -(25); check <= 25; check++)
            if (occurrences [check] >= 1)
                System.out.println (check + "\t" + occurrences [check]);

    }
}

問題在線

occurrences [entered] ++;

負數不能用作數組的索引。 為了解決這個問題,您可以使用一個單獨的變量來跟蹤掃描值的數量,例如count並使用它來訪問數組。

問題是您不能使用負數來索引Java數組。

您可以像這樣移動數組索引:

    occurrences [entered + 25] ++;

這會將-25到25的數字重新映射為0到50,從而可以將它們用作數組索引。

(您需要相應地更改程序的其余部分;我將其留給讀者練習。)

數組索引不能為負。 因此,一種骯臟的解決方案(但可行)是在將其用作數組索引之前,在輸入的值上加上25。 這將適用於負數,但不適用於nurber>25。要使用此類值,您需要使用更大的數組或使用其他存儲值的方法。

暫無
暫無

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

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