问题:让函数NumberStream(str)接受传递的str参数,该参数将包含数字2到9,并确定是否存在长度至少为N的连续数字流,其中N是实际数字值。如果是,则返回字符串true,否则返回字符串false。例如:如果字符串是“6539923335”,那么你程序应该返回字符串true,因为有一个长度为3的3的连续流。输入字符串将始终包含至少一个数字。
错误信息:第29章:你是谁?错误:'.class' expected if(temp.length()>1 && char(temp.length()+ 48 == temp[0])^ Main.java:29:错误:';'如果(temp.length()>1 && char(temp.length()+ 48 == temp[0]),则需要
有人能帮我解决这个错误吗?我是Java新手
我的解决方案:
mport java.util.*;
import java.io.*;
class Main {
public static String NumberStream(String str) {
// code goes here
if (str.length()==1)
{
return "false";
}
string temp = "";
temp +=str[0];
for (int x =1; x<str.length();x++)
{
if (temp.empty())
{
temp.push_back(str[x]);
continue;
}
if (str[x] ==temp[0])
{
temp +=str[x];
}
else
{
temp.clear();
}
if (temp.length()>1 && char(temp.length() + 48 == temp[0])
{
return "true";
}
}
return "false";
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(NumberStream(s.nextLine()));
}
}
1条答案
按热度按时间kqlmhetl1#
你混淆了数组和字符串语法。在Java中没有
[index]
表示法,你需要使用charAt
。另外,Java是大小写敏感的,你必须使用String
,而不是string
。我还修复了一些其他的东西,比如缺少括号,以及转换为
char
。还要注意,您的代码似乎对输入
"1"
是错误的---难道不应该得到"true"吗?您的代码打印“false”。你也可以使用Java的indexOf函数在String中查找一个String:
此版本的代码在命令行上接受测试输入(这使得运行上一个命令更容易,而不必再次键入所有输入):