0

Why won't the program work? When I type '1' at the first question and then type in something at the second, a red text comes up: (The program is not done but it should work shouldn't it?)

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:658) at javaapplication2.JavaApplication2.main(JavaApplication2.java:37) Java Result: 1

Code:

package javaapplication2;
import java.util.Scanner;
/**
 *
 * @author John
 */
public class JavaApplication2 {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int charAt = 0;
        int[] karies = new int[99];
        char[] ko = new char[99];
        char[] firstchar = new char[99];

        System.out.println("Type \"1\" for encryption and \"2\" for decryption:");


        if (sc.nextInt() == 1) {
            System.out.println("Enter the text you want to encrypt:");
        } else {
            System.out.println("Enter the text you want to decrypt:");
        }
        String krypt = sc.nextLine();
        int longd = (sc.nextLine()).length();

        while (charAt < longd) {
            firstchar[charAt] = krypt.charAt(charAt);
            karies[charAt] = ((int)firstchar[charAt]);
            ko[charAt] = (char)(karies[charAt] - 7);
            charAt++;
        }
        System.out.println(krypt.charAt(0));
    }
}
ilter
  • 3,905
  • 3
  • 28
  • 49

1 Answers1

0

Here, The problem is not with the Netbeans. sc.nextLine() is the culprit. After entering the choice when you press enter that carriage return is consumed by the sc.nextLine(), as sc.nextInt() will read only number, not the \n at the end. To solve this you can use an extra sc.nextLine().

if (sc.nextInt() == 1){
System.out.println("Enter the text you want to encrypt:");
}else{
System.out.println("Enter the text you want to decrypt:");
}
sc.nextLine(); // Extra added
String krypt = sc.nextLine();
int longd = (sc.nextLine()).length();

For more details you can refer to this or this questions.

Community
  • 1
  • 1
Hardik Modha
  • 9,434
  • 3
  • 31
  • 38
  • It's simple. When you enter the choice as either 1 or 2, that you have scanned from user using the `sc.nextInt()`, now after this you are pressing the enter to go to new line to enter the string that you are trying to store in `krypt`. Here, `sc.nextInt()` takes only number part not the enter(carriage return part - `\n`) Hope it's bit clear now. – Hardik Modha Aug 30 '15 at 05:14