i only found how to fill a char array with the same character, like:
char[] charArray = new char[5];
char charValue = 'A';
Arrays.fill(charArray, charValue);
System.out.println("The char array content is: " Arrays.toString(charArray));
// output: The char array content is: [A, A, A, A, A]
what i tried is this:
char[] abc = new char[5];
Scanner sc = new Scanner(System.in);
String s;
char c;
for (int i = 0; i < abc.length; i ) {
s = sc.next();
if (s.length() == 1) {
c = s.charAt(0);
System.out.println("for position " i " the character is: " c);
Arrays.fill(abc[i], c);
System.out.println("so we get the current array " Arrays.toString(abc));
} else {
System.err.println("pls give just one charcter");
break;
}
}
I always get the error, to change the abc-array from a char[] to a long[].\
EDIT:
what i want for an output is that i give 5 characters (for example a, b, c, d, e) in in the end I have the array
abc[] = {a, b, c, d, e}
Thank you in advance :)
CodePudding user response:
You can use:
Arrays.fill(abc, c);
or just:
abc[i]=c;
if you only want to fill the specified position of the array
CodePudding user response:
From what I can understand, you're trying to let the user enter data into your char array one by one... If that's what you want then this should help.
char[] input = new char[5];
for( int i = 0; i < input.length; i ) {
System.out.println("Enter only one character");
input[i] = (char)System.in.read();
System.out.println("Thus we have the current array as " Arrays.toString(input));
}
This code accepts only one character at a time, is faster than using Scanner. Here's a dry run of this code:
Enter a charcater
a
Thus we have cuurent array as [a, ., ., ., .]
Enter a charcater
b
Thus we have cuurent array as [a, b, ., ., .]
Enter a charcater
c
Thus we have cuurent array as [a, b, c, ., .]
Enter a charcater
d
Thus we have cuurent array as [a, b, c, d, .]
Enter a charcater
a
Thus we have cuurent array as [a, b, c, d, e]
If you want to accept a String and change it to a character Array instead, you can use the String function toCharArray(), char[] input = "abcde".toCharArray()
CodePudding user response:
The Answer by YourHelper seems correct.
Avoid char
Unfortunately, even the fixed version of your code will fail with most characters. The char
type is essentially broken since Java 2, and legacy since Java 5.
To see char
break, use a character like “