gpt4 book ai didi

java - 如何检查 char 是否为某个字符

转载 作者:行者123 更新时间:2023-12-01 17:51:50 25 4
gpt4 key购买 nike

我想请某人输入一封信,当他们输入时,检查该字母是否是我要问他们的某个字母。如果是,我的输出将显示数组列表。我的代码:

import java.util.Scanner;
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] rodent;
String[] dog;
String[] cat;

rodent = new String[] {"Rat", "Guinea Pig", "Mouse"};
dog = new String[] {"Rottweiler", "Basset Hound", "Weiner Dog"};
cat = new String[] {"Lion", "Tiger", "Mountain Lion"};

Scanner input = new Scanner(System.in);

System.out.print("Please Enter [R] for Rodent, [D] for Dogs, and"
+ " [C] for Cats: ");
char character = input.next().charAt(0);

if(character == 'R'); {
System.out.print(rodent[0]+", "+rodent[1]+", "+rodent[2]);
} // closes 'R' statement
if(character == 'D') {
System.out.print(dog[0]+", "+dog[1]+", "+dog[2]);
} //closes 'D' statement
if(character == 'C') {
System.out.print(cat[0]+", "+cat[1]+", "+cat[2]);
} //closes 'C' statement
}

如果他们输入 R,它就会正确输出。

如果输入 D,则会输出啮齿动物和狗。

如果它们输入 C,则仅输出啮齿动物。

解决这个问题的方法是什么?

最佳答案

这确实是因为不需要的分号,但始终尝试使用 switch-case 结构进行此类检查以获得最佳实践。

Scanner input = new Scanner(System.in);

public static void main(String[] args) {
String[] rodent;
String[] dog;
String[] cat;

rodent = new String[] {"Rat", "Guinea Pig", "Mouse"};
dog = new String[] {"Rottweiler", "Basset Hound", "Weiner Dog"};
cat = new String[] {"Lion", "Tiger", "Mountain Lion"};

Scanner input = new Scanner(System.in);

System.out.print("Please Enter [R] for Rodent, [D] for Dogs, and"
+ " [C] for Cats: ");
char character = input.next().charAt(0);


switch (character){
case 'R': System.out.print(rodent[0]+", "+rodent[1]+", "+rodent[2]);break;
case 'D': System.out.print(dog[0]+", "+dog[1]+", "+dog[2]);break;
case 'C': System.out.print(cat[0]+", "+cat[1]+", "+cat[2]);break;
}
}

关于java - 如何检查 char 是否为某个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49315114/

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