这是我编写的代码,用于计算用户输入的字符串中空格、制表符和换行符的数量(新行用句号(“.”)标记),并且我在没有文件的情况下执行此操作处理。 这段代码在运行时抛出字符串越界异常,我无法弄清楚为什么。请帮忙。
import java.io.*;
class Specialchars
{
public static void main(String arg[]) throws IOException
{
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter one or more lines");
String s=obj.readLine();
int count1=0,count2=0,count3=0;
for(int i=0; i<=s.length(); i++)
{
char ch=s.charAt(i);
if(ch==' ')
{
count1++;
}
else
if(ch=='\t')
{
count2++;
}
else
if(ch=='.')
{
count3++;
}
}
System.out.println("The number of blank spaces is = "+count1);
System.out.println("The number of tabs is = "+count2);
System.out.println("The number of new lines is = "+count3);
}
}
最佳答案
你应该使用
for(int i=0; i < s.length(); i++)
而不是
for(int i=0; i<=s.length(); i++)
像数组这样的字符串是从0开始枚举的,所以最后一个索引是length() - 1
关于java - 在没有文件处理的情况下计算java中的空格、制表符和新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793209/