[英]Color Recognizer: Recognizes red or blue in a string
So basically I have to take these words as an input or hard coded(doesn't really matter).所以基本上我必须将这些词作为输入或硬编码(并不重要)。 And I have to print what color the word has for example.例如,我必须打印单词的颜色。 "Red Dogs"-->Red. “红狗”-->红。 And I have two colors red and blue.我有两个 colors 红色和蓝色。 When its neither I get an extra empty string.当它都没有时,我得到一个额外的空字符串。
Scanner input=new Scanner(System.in);
String h=System.out.println("Enter a word");
String i=input.next();
public static String color(str r, str b){
for(int i=0;i<=h.length;i++){
if(i="red"){
System.out.println("Red");
}else if(i="blue"){
System.out.println("Blue");
}else{
return("");
}
}
} }
practice more.多加练习。
public static void main(String[] args) {
String colorStr = "RED DOG BLUE BIRD";
System.out.println(color(colorStr));
}
public static String color(String colorStr) {
Set<String> set = new HashSet<>(Arrays.asList("RED", "BLUE"));
StringBuilder presentColorStr = new StringBuilder();
String[] words = colorStr.split(" ");
for (String word : words) {
if(set.contains(word)) {
presentColorStr.append(word).append(" ");
}
}
return presentColorStr.toString();
}
Looks like you are entirely new to Java code.看起来您对 Java 代码完全陌生。 I will explain few things about your code.我将解释一些关于你的代码的事情。
Conditinal construct if..else accept a boolean literal only.条件构造 if..else 仅接受 boolean 文字。
if(a = b) // this is error as = is assignment operator and will not return boolean unless you assign a boolean if(a = b) // 这是错误,因为 = 是赋值运算符并且不会返回 boolean 除非你指定了 boolean
if(a == b) // this is right approach to compare two values. if(a == b) // 这是比较两个值的正确方法。
Comparison of two reference is different than values.两个参考的比较不同于值。 Ex.前任。 String holds reference so you cannot compare two string with ==.字符串包含引用,因此您无法将两个字符串与 == 进行比较。 You must compare two Strings with equals method that returns boolean if both string are same.如果两个字符串相同,则必须使用返回 boolean 的 equals 方法比较两个字符串。
String str1 = "hello";字符串 str1 = "你好"; String str2 = "hello";字符串 str2 = "你好";
if(str1.equals(str2)) { System.out.println("both are same."); if(str1.equals(str2)) { System.out.println("两者相同。"); } }
Further, your requirement to check if input string contains a string can be done using String.contains() function此外,您可以使用 String.contains() function 来检查输入字符串是否包含字符串
String str1 = "Red Ball";
String str2 = "ball";
if(str1.contains(str2)) {
System.out.println("String conatins str2");
}
You can also use methods toLowerCase() and toUpperCase() to make it case independent.您还可以使用 toLowerCase() 和 toUpperCase() 方法使其大小写无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.