这是我正在解决的问题。
我们必须要求用户输入一个字符串,然后输入一个字符(任何字符都可以)。然后计算该字符在扫描仪中出现的次数。
我不知道如何向扫描仪添加字符。我们还没有完成数组,所以我不想去那里,但这就是我到目前为止所做的:
import java.util.Scanner;
public class Counter {
public static void main (String args[]){
String a;
char b;
int count;
int i;
Scanner s = new Scanner (System.in);
System.out.println("Enter a string");
a = s.nextLine();
System.out.println("Enter a character");
b = s.next().charAt(0);
count = 0;
for (i = 0; i <= a.length(); i++){
if (b == s.next().charAt(b)){
count += 1;
System.out.println(" Number of times the character appears in the string is " + count);
else if{
System.out.println("The character appears 0 times in this string");
}
}
}
我知道这是不正确的,但我现在无法弄清楚。
任何帮助将不胜感激。
最佳答案
要验证您的输入 [String, char],请使用 while 循环从用户处获取字符。基本上,您将检查用户是否输入长度为1的字符串进行字符输入。 这是代码的编译和运行版本:
import java.util.Scanner;
public class Counter
{
public static void main ( String args[] )
{
String a = "", b = "";
Scanner s = new Scanner( System.in );
System.out.println( "Enter a string: " );
a = s.nextLine();
while ( b.length() != 1 )
{
System.out.println( "Enter a single character: " );
b = s.next();
}
int counter = 0;
for ( int i = 0; i < a.length(); i++ )
{
if ( b.equals(a.charAt( i ) +"") )
counter++;
}
System.out.println( "Number of occurrences: " + counter );
}
}
关于JAVA - 用扫描仪读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9509631/