gpt4 book ai didi

java - 当前涉及 String 的 If 语句

转载 作者:行者123 更新时间:2023-12-01 09:26:22 25 4
gpt4 key购买 nike

本质上,我的作业应该采用 2 个单词,计算我所做的两个单词中最小的一个,但现在我需要引用最小的单词本身而不是数字。我认为这需要一个 If 语句,但我无法让我的字符串初始化,并且当我使用 system.out.println 命令结束程序时,控制台变得挑剔。

Scanner scan = new Scanner(system.In); 
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
Int pass1l = pass1.length();
System.out.println(" input second password ");
String pass2 = scan.nextLine();
Int pass2l = pass2.length();
Int spassl = Math.min(pass1l,pass2l);
// problematic part here.
String spass;
If (pass1l > pass2l){ spass = pass2}
else if (pass1l < pass2l) {spass = pass1}
else if (pass1l == pass2l) {spass = null;};

Else if 语句也作为 not 语句出现,第一个是表达式的非法开始。

然后,如果我修复这些问题,我会用 system.out 调用 spass ,它会说它尚未初始化。我刚刚开始学习基础的Java,我之前使用过处理,但不是用于字符串相关的if语句,仅用于整数。

最佳答案

你就快到了。当您使用没有final else的if block 时,需要初始化变量spass。您可以给出 spass=""或将 Final else if 更改为 else ,如下所示。

    Scanner scan = new Scanner(System.in);
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
System.out.println(" input second password ");
String pass2 = scan.nextLine();
// problematic part here.
String spass;
if (pass1.length() > pass2.length()) {
spass = pass2;
} else if (pass1.length() < pass2.length()) {
spass = pass1;
} else {
spass = null;
}
System.out.println("result: " + spass);

关于java - 当前涉及 String 的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804807/

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