im having trouble with my homework. it asks to translate a user input string to a number. for example if i entered blue the translated int value would be 1. red would be 2 and yellow would be 3. i checked the api but couldnt find anything. thanks =]
Five answers:
deonejuan
2008-10-05 10:24:49 UTC
The Roman Numeral program, which is very similar, works with the
if( string.equalsIgnoreCase( anotherString) )
// do something
just s.equals( anObject ) // is useful for other things
I would write one method
private int translated( String colorVal ) {
if( colorVal.equalsIgnoreCase( "yellow")
return 1;
if( colorVal.equalsIgnoreCase( "blue")
return 2;
else
return 3
}
Steven V
2008-10-05 18:29:57 UTC
I can think of several solutions to this problem.
1. You could use Enums. Your enum could be values like BLUE, RED, YELLOW etc. They could have member variables for the index.
2. You could have a HashMap with the colors as the key and the index as the value. This would allow for very quick look ups.
3. You could have an ArrayList and loop through the ArrayList to find the appropriate value.
The key is to not use an if or switch statement, which lists all the values you want.
modulo_function
2008-10-05 16:50:36 UTC
I don't see what Ahmed's talking about. There's one equals() method for the string class and it compares strings and returns a boolean.
I looked through all the methods and didn't find one that works. You'll need to write your own.
I'd recommend naming it color() and using something like:
public int color(){
if (this.equalsIgnoreCase("blue") return 1;
if (this.equalsIgnoreCase("red") return 2;
... etc...
return 0; // this is for an undefinded color
}
Matthew
2008-10-05 17:01:53 UTC
This code should work.
import java.util.Scanner;
class StringToInt {
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
String color;
int number;
System.out.print("What is the color? ");
color = myScanner.next();
if (color.equals("blue")) {
number = 1;
System.out.print(number);
}
if (color.equals("red")) {
number = 2;
System.out.print(number);
}
if (color.equals("yellow")) {
number = 3;
System.out.print(number);
}
}
}
anonymous
2008-10-05 16:40:23 UTC
Checked API for what? Equals() method? Well, it's there...
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.