gpt4 book ai didi

java - 我如何计算在 java 中以 "im"结尾的人键入的条目?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:45:43 25 4
gpt4 key购买 nike

我想计算在控制台中以“im”结尾的条目(字符串),那么我该如何作为入门者呢?

import java.lang.String; 
import java.util.Scanner;

public class WordCount {
public static void main (String[]args){

final String SENTINEL = "END";
Scanner sc = new Scanner(System.in);
String text = "xy";

do {
System.out.print("Type a text or type "+SENTINEL+" when you are done. ");
text = sc.nextLine();
} while(!text.equalsIgnoreCase(SENTINEL));

boolean IMcheck = text.endsWith("im");
int count = 0;
if(IMcheck == true){
count++;
}
System.out.println("You have typed "+ count +" texts that end in \"im\" ");
}
}

最佳答案

正如评论者所说,您需要将 if 语句移到 do-while 循环中。这里不需要变量“IMcheck”。

为解决此问题,我已将您用于分配“IMcheck”变量的代码放入您的 if 语句中,并将其移至您的 do-while 循环中。

public class WordCount {

public static void main (String[]args) {
final String SENTINEL = "END";
int count = 0;
Scanner sc = new Scanner(System.in);
String text = "xy";

do {
if(text.endsWith("im"))
count++;

System.out.print("Type a text or type "+SENTINEL+" when you are done. ");
text = sc.nextLine();

} while(!text.equalsIgnoreCase(SENTINEL));

System.out.println("You have typed "+ count +" texts that end in \"im\" ");
}
}

关于java - 我如何计算在 java 中以 "im"结尾的人键入的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54174317/

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