我想写一个程序来检查字符串中的每个字符。如果连续两个字符相同,我想将计数增加1.程序应该扫描所有字符并给我们一个值。 T用于决定我们将输入多少个字符串。
例如:(输入) 五 AAAA BBBBB ABABABAB BABABA AAABBB
输出继电器 3 4 0 0 4
但我得到0 3 4 0 0
你可以帮忙吗?我做错了什么? import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args)
{
int i,T,j,count;
String S;
char K;
count = 0;
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
for (i = 0; i <= T - 1; i++)
{
count = 0;
S = scan.nextLine();
char[] list = new char[S.length()];
for(j = 0; j <= S.length() - 1; j++)
{
list[j] = S.charAt(j);
}
for(j = 1; j <= S.length() - 1; j++)
{
if(list[j - 1] == list[j])
{
count++;
}
}
System.out.println(count);
}
}
}
答案 0 :(得分:1)
我认为类似下面的内容可以帮助你,首先需要输入一些字符串,然后在输入的字符串中计算字符与前一个字符相同的次数。它不会采用一系列字符串,它将逐个执行,请参见下面的示例输出:
public static void main(String[] args){
int numInput;
String inputString;
Scanner scanner = new Scanner(System.in);
numInput = scanner.nextInt();
for(int y = 0; y < numInput;y++){
inputString = scanner.next();
char[] chars = inputString.toCharArray();
int counter = 0;
char curr;
for(int x = 0; x < chars.length;x++){
curr = chars[x];
if(x>0){
if(chars[x-1] == curr){
counter++;
}
}
}
System.out.println("Count for string " + inputString + " was " + counter);
}
scanner.close();
}
测试:
5
AASAAB
Count for string AASAAB was 2
AAAAAA
Count for string AAAAAA was 5
AAVAAD
Count for string AAVAAD was 2
MOOMOO
Count for string MOOMOO was 2
MAAAAAA
Count for string MAAAAAA was 5
答案 1 :(得分:-1)
试试这个......
public static void main(String[] args) {
int i, T, j, count;
String S;
char K;
count = 0;
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
for (i = 0; i <= T - 1; i++) {
scan = new Scanner(System.in);
count = 0;
S = scan.nextLine();
char[] list = new char[S.length()];
for (j = 0; j <= S.length() - 1; j++) {
list[j] = S.charAt(j);
}
for (j = 1; j <= S.length() - 1; j++) {
if (list[j - 1] == list[j]) {
count++;
}
}
System.out.println(count);
}
}