gpt4 book ai didi

java - 在java中应用if/else语句时出错

转载 作者:行者123 更新时间:2023-12-02 06:12:53 34 4
gpt4 key购买 nike

我的代码有问题,希望有人能看到我缺少的内容。我的代码如下:

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>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>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!

为什么第三个循环没有重置航行状态?

最佳答案

字符串是对象,因此您可以使用 equals 方法(“C”.equals(firstLetter))而不是 == 来比较它们。

此外,如果您只需要一个字符,则可以提取 char(使用 charAt(int))并与 'A'、'B' 等进行比较(这次使用 == :) ) 例如:

char firstLetter = boatArray[k].boatName.charAt(1);
if(firstLetter == 'B'){

关于java - 在java中应用if/else语句时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10492659/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com