Индекс вне границ с кодом систем счисления - PullRequest
0 голосов
/ 30 января 2020

У меня сейчас проблема с проблемой, когда мой индекс java выходит за пределы. Ошибка speci c находится внутри моего метода binaryToDecimal и составляет Index 32 out of bounds for length 32. Я попытался реорганизовать свой код, как при объявлении int binaryVal[] = new int[32]; в качестве глобальной переменной, чтобы исправить ошибку, но она не работает. Как мне исправить эту проблему?

import java.util.Scanner;

public class NumberConverter {

    public static Scanner input = new Scanner(System.in);   

    static boolean success;
    static String originalNum;
    static int value = 0;
    static int choice = 0;
    static int intNum = 0;
    static int remainder;
    static char [] valueBinaryArray;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        greeting();
        getOriginalNumber();
        getOutputType();
        //checkValidInput();

        if (value == 2 && choice == 3) {
            decimalToHex();
        }
        else if (value == 3 && choice == 2) {
            hexToDecimal();
        }
        else if (value == 2 && choice == 1) {
            decimalToBinary();
        }
        else if (value == 1 && choice == 2) {
            binaryToDecimal();
        }

    }

    public static void greeting() {

        System.out.println("Hello and welcome to the number systems converter");
        System.out.println("Below you will be givin options as to what numbers you'd like to convert");
        System.out.println("");

    } 

    public static String getOriginalNumber() { 

        System.out.println("Enter a number:");

        originalNum = input.next();

        System.out.println("What type of number is this?");
        System.out.println("");
        System.out.println("1. Binary");
        System.out.println("2. Decimal");
        System.out.println("3. Hexadecimal");

        value = input.nextInt();

        return originalNum;

    }

    public static void getOutputType() {

        System.out.println("Which number system would you like to convert to?");
        System.out.println("");
        System.out.println("1. Binary");
        System.out.println("2. Decimal");
        System.out.println("3. Hexadecimal");

        choice = input.nextInt();

    }

    public static void checkValidInput() {




    }

    public static void decimalToHex() {

        int intNum = Integer.valueOf(originalNum);

        String str2 = "";

        char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

        while (choice > 0) {

            remainder = intNum % 16;
            str2 = hex[remainder] + str2;
            intNum = intNum/16;

        }

    }

    public static void hexToDecimal() {

        int intNum = Integer.valueOf(originalNum);

        int counter = 0;

        String hexVal = "";

        int digit;

        while (choice > 0) {
            digit = intNum % 16;

            switch (digit) {
            case 1:
                hexVal+="F"; break;
            case 2:
                hexVal+="E"; break;
            case 3:
                hexVal+="D"; break;
            case 4:
                hexVal+="C"; break;
            case 5:
                hexVal+="B"; break;
            case 6:
                hexVal+="A"; break;
            default:
                hexVal+=Integer.toString(digit);          
            }

            intNum = intNum/16;

        }

        for (counter = hexVal.length()-1; counter>=0; counter--)
            System.out.print(hexVal.charAt(counter));

    }

    public static void decimalToBinary() {

        int intNum = Integer.valueOf(originalNum);

        int counter = 0;

        int binaryVal[] = new int[32];

        while (choice > 0) {
            binaryVal[counter++] = intNum % 2;
            intNum = intNum/2;

        }

        for (int i = counter-1; i >= 0; i--) {
            System.out.println(binaryVal[i]);

        }

    }

    public static void binaryToDecimal() {

        int intNum = Integer.valueOf(originalNum);

        int counter = 0;

        int binaryVal[] = new int[32];

        while (choice > 0) {
            binaryVal[counter++] = intNum % 2;
            intNum = intNum/2;

        }        

        for (int i = counter-1; i >= 0; i--) {
            System.out.print(binaryVal[i]);

        }

    }

}

Ответы [ 2 ]

0 голосов
/ 30 января 2020

так что причиной вашей ошибки является ваше условие для вашего заявления. В настоящее время вы просто проверяете, является ли choice >= 0 проблема с этой проверкой в ​​том, что она позволяет оператору for go превышать длину указанного вами массива (32). Чтобы исправить эту ошибку, вам просто нужно добавить еще одну проверку, чтобы убедиться, что for l oop не может go превышать длину указанного вами массива. Это можно сделать, добавив это утверждение в ваш файл для l oop: counter < binaryVal.length. Это должно предотвратить выход for l oop за пределы длины вашего массива, и вы не должны сталкиваться с какими-либо ошибками. Ваш окончательный код для вашего метода binaryToDecimal должен выглядеть следующим образом:

public static void binaryToDecimal() {

    int intNum = Integer.valueOf(originalNum);

    int counter = 0;

    int binaryVal[] = new int[32];

    while (choice > 0 && counter < binaryVal.length) {
        binaryVal[counter++] = intNum % 2;
        intNum = intNum/2;
    }

    for (int i = counter-1; i >= 0; i--) {
        System.out.print(binaryVal[i]);
    }

}
0 голосов
/ 30 января 2020

Если у вас есть массив из 32 элементов, первый из них имеет индекс 0, а последний - индекс 31. Попытка получить доступ к элементу в позиции 32 выходит за пределы диапазона массива, поэтому вы получаете индекс массива исключение границ.

Чтобы увидеть вывод, я бы предложил сделать массив 33 большим вместо 32. Это не совсем корректно, но вы должны увидеть, что он делает.

Если он все еще выходит за пределы, я бы посмотрел на вас поближе, пока l oop конечное условие.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...