英文:
need a java program to detect if an input character is a vowel
问题
import java.util.Scanner;
public class Ush {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字母字符:");
char s = sc.next().charAt(0);
int s1 = s;
String s2 = Character.toString(s);
if (s2.length() > 1) {
System.out.println("错误!只能输入单个字符。");
}
}
}
英文:
Requirement:
- Ask the user to type a single character from the alphabet.
- Indicate then that this character is vowel or consonant, depending on the user's input.
- If the user input is not a letter (between a and z or A and Z), or is a word with length> 1, type an error message.*
Problem:
can anyone help me to fix this code for the bold one , i have to use character not String.
public class Ush {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("put an character of alphabet : ");
char s = sc.next().charAt(0);
int s1 = s;
String s2 = Character.toString(s);
if(s2.length() > 1){
System.out.println(" Mistake !");
}
}
}```
</details>
# 答案1
**得分**: -1
有很多方法可以做到这一点,但你可以简单地检查你的 `Scanner` 上是否还有更多字符,例如:
```java
if (sc.hasNext()) {
System.out.println("错误!");
}
这样,如果你的扫描器有另一个输入,你将会看到输出 "错误!"。
英文:
There are lots of ways of doing it but you can simply check if there are more chars on your Scanner
, ex:
if (sc.hasNext()) {
System.out.println(" Mistake !");
}
This way, if you scanner has another input, you will get the Mistake printed.
答案2
得分: -1
public class Ush {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字母字符:");
String s2 = sc.next();
char s = s2.charAt(0);
int s1 = s;
if (s2.length() > 1) {
System.out.println("错误!");
}
}
}
英文:
public class Ush {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("put an character of alphabet : ");
char s = sc.next().charAt(0);
int s1 = s;
String s2 = sc.next();
if(s2.length() > 1){
System.out.println(" Mistake !");
}
}
}
But you can optimize your program as below,
public class Ush {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("put an character of alphabet : ");
String s2 = sc.next();
char s = s2.charAt(0);
int s1 = s;
if(s2.length() > 1){
System.out.println(" Mistake !");
}
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论