I tried to program it but I can only do it with integers
No, you can do it if you use in.next().charAt(0)
rather than in.nextInt()
from Scanner
Class to take the first Character
form String
.
I don't know how to change it to letters / characters?
Here you don't need to change it, or some regex
or split
it, the method in.next()
get the String from the input (end-use) and then get the charAt(0)
the first one.
Now, what i have changed in your code to be worked as you mentioned above:
- Change
search
andarray[]
tochar
Data type. - Change the declaration of
array[]
toarray = new char[n]
- Change the input for
search
andarray
toin.next().charAt(0)
.
Try this:
public static void main(String args[]) {
int n,c;
char search,array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new char[n];
System.out.println("Enter " + n + " Letters");
for ( c = 0; c < n; c++) {
array[c] = in.next().charAt(0);
}
System.out.println("What letter do you want to find?");
search = in.next().charAt(0);
for ( c = 0; c < n; c++) {
if (array[c] == search) /* Searching element is present */ {
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
if (c == n) /* Searching element is absent */ {
System.out.println(search + " Letter is not found.");
}
}
}