我的代码有问题,希望有人能看到我遗漏了什么。我的代码如下:
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和Settings>java Project2企业挑战者发现尼米兹
进取号已经准备好启航。
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和Settings>java Project2企业挑战者发现尼米兹
进取号已经准备好启航。
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!为什么第三个循环没有重置sail状态?
发布于 2012-05-08 12:47:39
变化
firstLetter == ("B")至
firstLetter.equals("B")等
==检查引用是否相等,而as .equals将检查值是否相等
发布于 2012-05-08 12:46:01
字符串是对象,所以您可以使用equals方法("C".equals(firstLetter))来比较它们,而不是使用==。
此外,如果只需要一个字符,可以提取字符(使用charAt(int))并与'A‘、'B’等(这次使用== :)进行比较。例如:
char firstLetter = boatArray[k].boatName.charAt(1);
if(firstLetter == 'B'){发布于 2012-05-08 12:46:28
在处理类型为String的对象时尝试使用方法'equals‘或'equalsIgnoreCase’A '==‘(也称为C样式相等)尝试比较对象引用。
像这样的东西
if( "B".equalsIgnoreCase( firstletter ) ){
// do whatever
}https://stackoverflow.com/questions/10492659
复制相似问题