简体   繁体   English

将正整数转换为负值

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

So today in class we had to make a program that asked to input values between or equal to -25 and 25, and to quit the program when a number outside those values is entered. 因此,今天在上课时,我们不得不创建一个程序,要求输入介于-25到25之间的值,并在输入超出这些值的数字时退出该程序。 When I try to input any number higher than 25 or a negative value, the program crashes and an error report pops up. 当我尝试输入大于25或负值的任何数字时,程序崩溃,并弹出错误报告。

So here's my question, how to make these negative values work. 所以这是我的问题,如何使这些负值发挥作用。 I included the program below to help anyone you is willing to help figure this problem out. 我在下面提供了该程序,以帮助任何愿意解决此问题的人。

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]);

    }
}

The problem is on line 问题在线

occurrences [entered] ++;

Negative numbers cannot be used as indices to an array. 负数不能用作数组的索引。 In order to fix this, you can use a separate variable to track the number of scanned values, such as count and use this to access the array. 为了解决这个问题,您可以使用一个单独的变量来跟踪扫描值的数量,例如count并使用它来访问数组。

The problem is that you can't use negative numbers to index into a Java array. 问题是您不能使用负数来索引Java数组。

You could shift array indices like so: 您可以像这样移动数组索引:

    occurrences [entered + 25] ++;

This will remap the numbers from -25 to 25 as 0 to 50, allowing them to be used as array indices. 这会将-25到25的数字重新映射为0到50,从而可以将它们用作数组索引。

(You'll need to change the rest of the program accordingly; I leave this as an exercise for the reader.) (您需要相应地更改程序的其余部分;我将其留给读者练习。)

Array indices cannot be negative. 数组索引不能为负。 So a dirty solution (but working) would be to add 25 to value entered before using it as array index. 因此,一种肮脏的解决方案(但可行)是在将其用作数组索引之前,在输入的值上加上25。 This will work for negative numbers but not for nurber > 25. To use such values, you need to use a larger array or use a different method of storing the values. 这将适用于负数,但不适用于nurber>25。要使用此类值,您需要使用更大的数组或使用其他存储值的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM