作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个程序,它需要从用户输入中读取多行文本并显示字母表中每个字母在字符串中出现的次数。最后一行以一个句点结尾,它将作为标记值。这是我目前所拥有的:
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/
我是一名优秀的程序员,十分优秀!