gpt4 book ai didi

java - 有没有办法从用户输入中获取多行文本?

转载 作者:行者123 更新时间:2023-11-29 09:28:07 27 4
gpt4 key购买 nike

我正在创建一个程序,它需要从用户输入中读取多行文本并显示字母表中每个字母在字符串中出现的次数。最后一行以一个句点结尾,它将作为标记值。这是我目前所拥有的:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class LetterCounter
{

public static void main(String[] args)
{

try {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

String lineOfText;
char letter, choice;

int countArray[] = new int[26];
do
{

System.out.println("Enter the String (Ends with .):");
while ((lineOfText = input.readLine()) != null)
{

for (int i = 0; i < lineOfText.length(); i++)
{
letter = lineOfText.charAt(i);
int index = getIndex(letter);
if (index != -1)
{
countArray[index]++;
}
}
if (lineOfText.contains("."))
break;
}

System.out.println("Count Alphabets:");

for (int i = 0; i < countArray.length; i++)
{
System.out.println((char) (65 + i) + " : " + countArray[i]);
}

//Ask user whether to continue or not
System.out.println("\nWould you like to repeat this task? (Press y to continue or n to exit program): ");

choice = input.readLine().toLowerCase().charAt(0);

System.out.println();

} while (choice == 'y');

}

catch (IOException e)
{
// Auto-generated catch block
e.printStackTrace();
}
}


//method to get the index of alphabet

public static int getIndex(char letter)
{
if (Character.isAlphabetic(letter))
{
if (Character.isUpperCase(letter))
{
return (int) letter - 65;
}

else
{
return (int) letter - 97;
}
}

else
{
return -1;
}

}
}

我想知道如何允许多行文本。所以我可以做一行。

最佳答案

您可以更改扫描仪的分隔符,以便在第一次输入时,程序会在到达 .然后返回默认值以检查他是否要继续

    Scanner sc = new Scanner(System.in);
char choice = 'y';

while (choice == 'y'){
System.out.println("Enter the String (Ends with .):");
sc.useDelimiter("\\.");
System.out.println(sc.next());
//Ask user whether to continue or not
System.out.println("\nWould you like to repeat this task? (Press y to continue or n to exit program): ");
sc.useDelimiter("\n");
sc.next();
choice = sc.next().toLowerCase().charAt(0);

}

关于java - 有没有办法从用户输入中获取多行文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40617623/

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