Click here to Skip to main content
15,918,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
For example if A = 0, B=1, C=2 and D =3. If i input 'A' , the output would be '0'.
This is easy for one character, but how about if i input 4 characters at one without space like the 'BACC', the output should be '1022'. But how do i do that?. Pls help asap

What I have tried:

I haven't tried anything as im new to java, pls make the answer as simple as possible so i can understand.
Posted
Updated 30-May-18 21:20pm

1 solution

You have to read the input at once as string and iterate then over the characters of that string.

Assuming that the input is from the console (keyboard) and terminated by pressing the RETURN key, you can read the input with
Java
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();

To iterate over items you need knowledge about loops, the class holding the items (String (Java SE 9 & JDK 9 )[^]), and which methods of that class might be useful for the problem to be solved.

With strings, this is obviously the length (number of characters) and how to get the character at a specific position in the string.

Because this might be homework and you have no tried anything so far, I will not give you code.

Very important aspects of learning a programming language are trying to do it yourself, reading the official documentation for the language, and reading a good book, tutorials or your course notes.
 
Share this answer
 
Comments
Adam Anselm 31-May-18 3:46am    
I did try this but the code for 'cat' is 312 even though i set it to '012'
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);

System.out.println("Please enter elements...");
char[] a=input.next().toCharArray();
switch(a[0]+ a[1] + a[2]){
case 'c' : a[0] = 0;break;
case 'a' : a[1] = 1;break;
case 't' : a[2] = 2;break;

}


{
System.out.print(a[0]+ a[1]+ a[2]);
}
System.out.println();
Jochen Arndt 31-May-18 4:18am    
- You need a loop to process each single character
- A switch for concatenated characters makes no sense
- You have a char array. So you should use chars (a[0] = '0') and not numeric values (the numeric value for the character '0' is 48)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900