I want to create an array that empty and no size.
char[] enteredLettersArray = {};
That array stores letter I entered from keyboard. for example: I enter letters again and again until I find a correct letter, I want to store the letters all I entered. How can I do that?
import java.util.Scanner;
import java.util.Arrays;
public class FindTryC {
public static void main(String[] args) {
Scanner keybInput = new Scanner(System.in);
char secretLetter = 'C';
char[] enteredLettersArray = {};
System.out.print("Please Enter a Letter : ");
char enteredLetter = keybInput.next().charAt(0);
// ? ? ? ? ? ?;
while (secretLetter != enteredLetter) {
System.out.print("Please Enter a Letter : ");
enteredLetter = keybInput.next().charAt(0);
// ? ? ? ? ? ?;
}
System.out.println(enteredLettersArray.length);
System.out.println(Arrays.toString(enteredLettersArray)) ;
}
}
CodePudding user response:
An array is of fixed length so if you create as empty it will remain empty. What you want is a collection that can resize. The standard replacement for an array is a List and the preferred implementation is usually ArrayList.
List<Character> letters = new ArrayList<>();
However, looking at what you are trying to do you may prefer a Set. The HashSet is the typical choice.
Set<Character> letters = new HashSet<>();
In either case, you will have a Collection that can resize as you add things to it.
CodePudding user response:
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
This is what mentioned in official Java tutorial page.. So you have to create array & initialize with some size.
If you want to use dynamic data-structure , consider using List<Character>
so that you don't need to define size while creating object of list.
CodePudding user response:
import java.util.Arrays;
public class FindTryC {
public static void main(String[] args) {
Scanner keybInput = new Scanner(System.in);
char secretLetter = 'C';
char[] enteredLettersArray = {};
System.out.print("Please Enter a Letter : ");
char enteredLetter = keybInput.next().charAt(0);
// ? ? ? ? ? ?;
int i = 0;
while (secretLetter != enteredLetter) {
System.out.print("Please Enter a Letter : ");
enteredLettersArray[i]= keybInput.next();
i ;
}
System.out.println(enteredLettersArray.length);
System.out.println(Arrays.toString(enteredLettersArray));
enter code here
}
}```