I'm trying to do a program wherein a user can input a string, which will be converted into a char array. The program has three functions:
- toString(): returning the char array as a string again
- isFull(): checks if the array is full
- append(): allows the user to input another character
I think my code is going the right way for the most part but I can't seem to get the append() to work. Here's my code:
import java.util.Arrays;
import java.util.Scanner;
public class CharSeq {
private static Scanner sc = new Scanner(System.in);
private static final int maxLength = 5;
private static char[] cArray = new char[maxLength + 1];
private static String input;
private static char append, yesNo;
private static int cLength = 0;
public static void main(String[] args) {
CharSeq cs = new CharSeq();
System.out.println("Input sequence: ");
input = sc.next();
cArray = input.toCharArray();
cLength = cArray.length;
System.out.print(cs.toString());
System.out.print(" (space left: " + (maxLength - cLength) + ")");
cs.append(yesNo, append);
System.out.println(cs.toString());
}
public String toString(){
String s = "";
for(int i = 0; i < cLength; i++){
s = s + cArray[i];
}
return s;
}
public boolean isFull(){
if(cLength == maxLength){
return true;
}
else{
return false;
}
}
public void append(char a, char c){
if(isFull()){
System.out.println("\nCharSeq is full.");
}
else{
System.out.println("\nDo you want to add sequence? [Y/N]");
a = sc.next().charAt(0);
if(a == 'Y' || a == 'y'){
System.out.println("Input sequence: (space left: " + (maxLength - cLength) + ")");
c = sc.next().charAt(0);
cArray[++cLength] = c;
}
}
}
}
Here's the stacktrace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at CharSeq.append(CharSeq.java:53)
at CharSeq.main(CharSeq.java:22)