在没有文件处理的情况下计算 java 中的空格、制表符和新行
Counting blank spaces, tabs and new lines in java without file handling
这是我编写的代码,用于计算用户输入的字符串中的空格、制表符和换行符的数量(新行用句号 (".") 标记,我正在这样做没有文件处理。
此代码在运行时抛出字符串越界异常,我无法弄清楚原因。请帮忙
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
这是我编写的代码,用于计算用户输入的字符串中的空格、制表符和换行符的数量(新行用句号 (".") 标记,我正在这样做没有文件处理。 此代码在运行时抛出字符串越界异常,我无法弄清楚原因。请帮忙
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