[英]JAVA - reading character with SCANNER
Here is the problem that I'm working on. 这是我正在研究的问题。
We have to ask the user to enter a string, and then enter a character (any character would be fine). 我们必须要求用户输入一个字符串,然后输入一个字符(任何字符都可以)。 And then count the number of times that character appears in the scanner. 然后计算该字符出现在扫描仪中的次数。
I cannot figure out how to add character to scanner. 我不知道如何向扫描仪添加字符。 We haven't done arrays yet so I don't wanna go there but this is what I have done so far: 我们还没有完成数组,所以我不想去那里,但这是我到目前为止所做的:
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");
}
}
}
I know this is incorrect but I cannot figure this out right now. 我知道这是不正确的,但我现在无法解决。
Any help would be highly appreciated. 任何帮助将不胜感激。
To verify your inputs [String, char] use a while loop for getting the character from the user. 要验证您的输入[String,char],请使用while循环从用户那里获取字符。 Basically you will check whether user enters a string of length 1 for character input. 基本上,您将检查用户是否输入长度为1的字符串进行字符输入。 Here is the compiling and running version of your code: 这是代码的编译和运行版本:
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 );
}
}
First, the for loop condition should be changed to : 首先,for循环条件应更改为:
for (i = 0; i < a.length(); i++)
The index starts from 0, but when you count length you start from 1. Therefore you don't need '='. 索引从0开始,但是当您计算长度时,从1开始。因此,您不需要'='。
Second, in the for loop, you only need to do one thing: compare each character of a with b: 其次,在for循环中,您只需要做一件事:将a的每个字符与b进行比较:
if (b == a.charAt(i))
count += 1;
Here, compared with the other solution, char is cheaper than String to be compared. 在这里,与其他解决方案相比,char比要比较的String便宜。
Third, after the for loop, output depends on count: 第三,在for循环之后,输出取决于计数:
if (count > 0)
System.out.println(" Number of times the character appears in the string is "
+ count);
else // must be count == 0
System.out.println("The character appears 0 times in this string");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.