繁体   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