gpt4 book ai didi

java - 编写一个程序,从键盘读取字符,直到读取换行符 '\n'

转载 作者:行者123 更新时间:2023-12-02 00:27:11 26 4
gpt4 key购买 nike

编写一个程序,从键盘读取字符,直到读取一行馈送字符“\n”。然后让它打印元音的数量,辅音、位数和其他字符的数量。包括其他字符计数中的最后一个换行字符。

我做了其中的大部分,但是当我输入\n 时,它并没有停止。谁能给我一些帮助吗?

import java.util.Scanner;
class characters{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int v=0;
int c=0;
int n=0;
int o=0;
char ch;
do{
System.out.println("Type in any characters: ");
System.out.println("Type in \\n to stop. ");
ch = scan.next().charAt(0);
if(ch=='\n') {
o++;
break;}
else
{
if('a'<=ch && ch<='z')
{
if(ch=='a') v++;
else if(ch=='e') v++;
else if(ch=='i') v++;
else if(ch=='o') v++;
else if(ch=='u') v++;
else c++;
}
else if('0'<=ch && ch<='9') n++;
else o++;
}

}while(ch!='\n');
System.out.println("There are "+v+" vowels, "+c+" consonants, "+n+" digits, and "+o+" other characters.");
}
}

最佳答案

“读取字符直到键入换行符”是“读取一行输入”的一种奇特方式。因此,只需读取整行输入,然后逐个字符地迭代它即可获得计数。像这样的事情:

int v=0;
int c=0;
int n=0;
int o=0;
System.out.println("Enter a string of characters (Press ENTER when done):");
String line = scan.nextLine();

// OPTION 1 for iterating over the line character by character
for (char ch : line.toCharArray(){
if ('a' <= ch && ch <= 'z')
// etc...
}

// OPTION 2 for iterating over line
for (int i = 0; i < line.length(); ++i){
char ch = line.charAt(i);
if ('a' <= ch && ch <= 'z')
// etc...

}

关于java - 编写一个程序,从键盘读取字符,直到读取换行符 '\n',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58045145/

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