计算短语中的空白字符-Java
我正在为课堂做这个小的硬件问题。我的程序的要点是从用户输入中计算短语中的所有空白字符。一切都很好,直到我达到我的循环。我在循环中设置了一个断点,它运行罚款并计算空白字符。但是当循环结束时,程序崩溃并给我这个错误: 线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:5 我不太明白是否有人能给我指出正确的方向计算短语中的空白字符-Java,java,Java,我正在为课堂做这个小的硬件问题。我的程序的要点是从用户输入中计算短语中的所有空白字符。一切都很好,直到我达到我的循环。我在循环中设置了一个断点,它运行罚款并计算空白字符。但是当循环结束时,程序崩溃并给我这个错误: 线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:5 我不太明白是否有人能给我指出正确的方向 import java.util.Scanner; public class Cray { public
import java.util.Scanner;
public class Cray {
public static void main(String[] args){
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
// and count the blank spaces
for(int i =0; i<=length; i++ ){
if(phrase.charAt(i)==' '){
countBlank++;
}
}
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}
import java.util.Scanner;
公营部门{
公共静态void main(字符串[]args){
字符串短语;//一个字符串
int countBlank;//短语中的空格数
int length;//短语的长度
char ch;//字符串中的单个字符
扫描仪扫描=新扫描仪(System.in);
//打印程序标题
System.out.println();
System.out.println(“字符计数器”);
System.out.println();
//读入字符串并找出其长度
System.out.print(“输入句子或短语:”);
短语=scan.nextLine();
长度=短语。长度();
//初始化计数
countBlank=0;
//一个for循环,用于逐个字符地遍历字符串
/和计数空白空间
对于(int i=0;i您正在尝试读取超出字符串长度的字符短语
。要修复此问题,您可以使用:
for (int i = 0; i < length; i++) {
for(int i=0;i
要详细说明和解释给出的答案:
循环的条件:
for(int i =0; i<=length; i++ )
for(inti=0;i实际上扫描器将忽略空格,所以使用BufferedReader
公共静态void main(字符串[]args)引发IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String word=null;
System.out.println("Enter string input: ");
word = br.readLine();
String data[] ;
int k=0;
data=word.split("");
for(int i=0;i<data.length;i++){
if(data[i].equals(" "))
k++;
}
if(k!=0)
System.out.println(k);
else
System.out.println("not have space");
}
BufferedReader br=新的BufferedReader(新的InputStreamReader(System.in));
字符串字=null;
System.out.println(“输入字符串:”);
word=br.readLine();
字符串数据[];
int k=0;
data=word.split(“”);
对于(int i=0;我不想,我不只是想让你们都解决我的硬件问题。如果我能解决这个问题,我必须进一步修改我的程序,所以我还没有完全完成。哇。我发誓我第一次这么做了,它给了我一个错误,所以我把它切换到了我