2012-10-12 4 views
0

클래스에 대해 이처럼 작은 HW 문제를 수행하고 있습니다. 내 프로그램의 요점은 사용자 입력에서 구문에있는 모든 공백 문자를 계산하는 것입니다. for 루프에 도달 할 때까지 모든 것이 정상입니다. 루프에 중단 점을 두었고 벌금을 부과하고 공백 문자를 계산합니다. "주"java.lang.StringIndexOutOfBoundsException 스레드에서공백 문자 수 계산 - Java

예외 : 문자열 색인이 범위를 벗어 : 루프는 프로그램이 충돌 끝나는 날이 오류를 제공하지만 5

사람이 할 수 있다면 아주 이해가 안 돼요 올바른 방향으로 나를 가리켜 라.

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(); 
      } 
     } 
+0

가 발생합니다 공백이 너무 BufferedReader로

공공 정적 무효 메인 (문자열 []에 args)를 사용하여 무시합니다 그리고 더 나는 "방금 당신이 모두 해결하도록 노력 아니에요없는 내 HW 문제.이 문제를 해결할 수 있다면 프로그램을 더 수정해야만하기 때문에 아직 완료되지 않았습니다. – recheej

답변

1

이 정교하고 설명 : 해결하려면 사용할 수 있습니다

  1. '길이'항목이있는 배열을 가져 와서 0 번째 요소부터 시작하십시오.
  2. 0 번째 요소 처리
  3. 다음 요소로 이동하여 처리합니다. 당신은 = 길이

당신이 정의에 의해, 이상 반복되는 배열 인덱스에있는 요소에 도달 할 때까지 3 단계를 수행

  • 보관할는 4 단계에서 실패 할 것이다. 배열은 0부터 시작하여 인덱스되기 때문에 'n'요소를 갖는 배열은 'n-1'의 최대 인덱스를가집니다.

  • 1

    문자열 길이가 phrase 이상인 문자를 읽으려고합니다.

    루프의 조건 :

    for(int i =0; i<=length; i++) 
    

    다음을 수행 할 수있는 프로그램을 지시 : 조금 주어진 답을

    for (int i = 0; i < length; i++) { 
    
    +0

    와우. 나는 처음으로 그렇게했다고 맹세했기 때문에 오류가 발생하여 i <= 길이로 바꿨습니다. 그러나 그것은 그 문제를 해결했습니다. 고맙습니다. – recheej

    0

    실제로 스캐너는 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"); 
    
    }