I need to write a program which creates an array of 5 characters randomly filled(A-Z), then asks the user to input a character using this
1 java.util.Scanner in = new java.util.Scanner(System.in);
2
3 // . . . .
4
5 char c = in.next().charAt(0);
then the program has to count occurrances in the given array, print out the count in console and replace matching characters in the given array by '0'. The program has to finish when whole array is filled with '0'.
Here's what I have so far:
public class New{
public static void main(String[] args){
char arr[] = new char[5];
for(int i=0;i<arr.length;i++){
arr[i] = (char)(Math.random()*((90-65)+1)+65);
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+ " ");
}
java.util.Scanner in = new java.util.Scanner(System.in);
int counter = 0;
char c = in.next().charAt(0);
for(int j = 0;j<arr.length;j++){
if(arr[j] == c){
counter++;
arr[j]= '0';
}
}
System.out.println("The character is present " + counter+" times");
for(int j = 0;j<arr.length;j++){
System.out.print(arr[j]+ " ");
}
The code above asks for input ones, replaces the character and prints out the number of times that character was in the array. The problem is that I need to ask the user for input several times until whole array is filled with zeros.
What I have tried:
I tried to place char c = in.next().charAt(0); into another loop(external loop) and the one I have in the code above was inside that loop, it didn't work
I tried to find an answer on Google but I couldn't find anything that would fit in this situation.
I can't use methods which were not discussed in class, so there has to be a way to place char c = in.next().charAt(0); into a loop so that a user is asked for input several times.