我的代码出现问题,希望有人能看到我错过的内容。我的代码如下:
import java.io.IOException;
class Boat{
String boatName = (" ");
boolean sailUp = false;
}
public class Project2{
public static void main(String[] args){
System.out.println("\n");
Boat[] boatArray;
boatArray = new Boat[args.length];
for(int i = 0 ; i < args.length ; ++i){
boatArray[i] = new Boat();
}
for(int j = 0 ; j < args.length ; ++j){
boatArray[j].boatName = args[j];
}
for(int k = 0 ; k < args.length ; ++k){
String firstLetter = boatArray[k].boatName.substring(0, 1);
if(firstLetter == ("B")){
boatArray[k].sailUp = true;
}else if(firstLetter == ("C")){
boatArray[k].sailUp = true;
}else if(firstLetter == ("N")){
boatArray[k].sailUp = true;
}else{
boatArray[k].sailUp = false;
}
}
for(int l = 0 ; l < args.length ; ++l){
System.out.println("\nThe " + boatArray[l].boatName + " is ready to sail...");
if(boatArray[l].sailUp == false){
System.out.println("\n\tbut the sail is down, raise the sail!");
}else if(boatArray[l].sailUp == true){
System.out.println("\n\tthe sail is up, ahead full!");
}
}
}
}
我想要以下输出:
C:\ Documents and Settings&gt; java Project2 Enterprise Challenger Discovery Nimitz
企业已准备好开航......
but the sail is down, raise the sail!
挑战者准备开航......
the sail is up, ahead full!
发现号已准备好开航...
but the sail is down, raise the sail!
尼米兹准备开航......
the sail is up, ahead full!
但我明白了:
C:\ Documents and Settings&gt; java Project2 Enterprise Challenger Discovery Nimitz
企业已准备好开航......
but the sail is down, raise the sail!
挑战者准备开航......
but the sail is down, raise the sail!
发现号已准备好开航...
but the sail is down, raise the sail!
尼米兹准备开航......
but the sail is down, raise the sail!
为什么第三次循环不会重置航行状态?
答案 0 :(得分:4)
字符串是对象,因此您使用equals
方法(“C”.equals(firstLetter))而不是==
来比较它们。
此外,如果您只需要一个字符,则可以提取char(使用charAt(int)
)并与'A','B'等进行比较(这次使用==
:))例如:
char firstLetter = boatArray[k].boatName.charAt(1);
if(firstLetter == 'B'){
答案 1 :(得分:3)
更改
firstLetter == ("B")
到
firstLetter.equals("B")
等
==
检查引用相等性,其中.equals
将检查值相等
答案 2 :(得分:0)
在处理 String 类型的对象时,尝试使用'equals'或'equalsIgnoreCase'方法 '=='(也称为C样式相等)尝试比较对象引用。
像这样的东西
if( "B".equalsIgnoreCase( firstletter ) ){
// do whatever
}
答案 3 :(得分:0)
== -> checks for equality in reference.
equals -> checks for equality in value.
所以请尝试使用equals方法。
答案 4 :(得分:0)
将对象与另一个对象进行比较时,必须使用.equals()方法,但不能使用“==”。 “==”将比较两个字符串的指针。
答案 5 :(得分:0)
像这样使用string.equals()
if(firstLetter.equals("B")){
boatArray[k].sailUp = true;
}else if(firstLetter.equals("C")){
boatArray[k].sailUp = true;
}else if(firstLetter.equals("N")){
boatArray[k].sailUp = true;
}else{
boatArray[k].sailUp = false;
}