简体   繁体   中英

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. When I try to input any number higher than 25 or a negative value, the program crashes and an error report pops up.

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.

The problem is that you can't use negative numbers to index into a Java array.

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.

(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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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