pat
pat

Reputation: 53

How do I debug this error regarding with the string and int

I want to know the position of the inputted numbers so I decided to convert the String type to an int data type using parse, the source code is below:

public static void main (String [] Args) {
    Scanner input = new Scanner (System.in);
    String x = "0" ;
    int number = Integer.parseInt(x);

    System.out.print("\nEnter 5 numbers: ");
    number = input.nextInt();

    if ((x.charAt(0) == x.charAt (4)) && (x.charAt(1) == x.charAt(3))) {
        System.out.print("The set of numbers is equal to its original value");
    } else {
        System.out.print("The set of numbers is not equal to its original value");
    }   
}   

After I compile the file, it won't run and this error appears

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4 at java.base/java.lang.StringLatin1.charAt(Unknown Source) at java.base/java.lang.String.charAt(Unknown Source) at activity10.main(activity10.java:12)

Upvotes: 0

Views: 430

Answers (2)

Antimon
Antimon

Reputation: 231

The method charAt(i) returns the i-th character of a String (starting at index 0). This means that if you want to call yourString.charAt(k) it is necessary for yourString to have at least k+1 characters.

According to your code

String x = "0";

x will always be "0". So any call x.charAt(i) for i > 0 will result in an StringIndexOutOfBoundsException.

Update

Does the following code do what you need?

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);

    System.out.print("\nEnter 5 numbers: ");
    String x = input.next();

    if ((x.charAt(0) == x.charAt (4)) && (x.charAt(1) == x.charAt(3))) {
        System.out.print("The set of numbers is equal to its original value");
    } else {
        System.out.print("The set of numbers is not equal to its original value");
    }
}

Upvotes: 1

Mohan
Mohan

Reputation: 334

You are trying to get the input number using Scanner input

The, you would not need these lines

String x = "0" ;
int number = Integer.parseInt(x);

All you need to do is to get the numbers first

int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();

and then start with the comparison of numbers.

Also, You can go through some Java tutorials and then start coding as it would help you to understand the programming basics

Upvotes: 0

Related Questions