首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java相关 >

这程序该如何改正,求指导

2012-05-16 
这程序该怎么改正,求指导。// **********************************************************//Count.java//

这程序该怎么改正,求指导。
// ********************************************************** 
// Count.java 
// 
// This program reads in strings (phrases) and counts the  
// number of blank characters and certain other letters 
// in the phrase. 
// ********************************************************** 
 
import java.util.Scanner; 
 
public class Count 

  public static void main (String[] args) 
  { 
  String phrase; // a string of characters 
  int countBlank; // the number of blanks (spaces) in the phrase  
  int length,i; // 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
  for(i = 0;i <= length ;i++)
  {
  if(phrase.charAt(i) == ' ') {
  countBlank++;
  }
  }
  System.out.println (countBlank);
  } 
}

[解决办法]

Java code
for(i = 0;i < length ;i++)  {  if(phrase.charAt(i) == ' ') {  countBlank++;  }  }
[解决办法]
上楼正确从0开始 或者for(i=0;i<=length-1;i++)
[解决办法]
java的下标是从0 --> (长度 -1) ;

热点排行