2017-10-10 1 views
2

저는 대학에서 입문 한 Java 과정입니다. 제 과제를 위해서 저는 문장에 1 자의 단어 수, 문장에 2 자의 단어 수 등을 표시하는 프로그램을 작성해야합니다. 문장은 사용자 입력입니다. 루프를 사용해야하고 배열을 사용할 수 없습니다.문장의 첫 단어에 나오는 글자 수를 계산하십시오.

그러나 지금은 시작하기 위해 문장의 첫 단어에있는 글자 수를 찾으려고합니다. 내가 가지고있는 것은 잘못된 문자 수 또는 String 인덱스가 범위를 벗어났다는 오류를 준다.

Scanner myScanner = new Scanner(System.in); 

    int letters = 1; 

    int wordCount1 = 1; 

    System.out.print("Enter a sentence: "); 
    String userInput = myScanner.nextLine(); 


    int space = userInput.indexOf(" "); // integer for a space character 

    while (letters <= userInput.length()) { 

    String firstWord = userInput.substring(0, space); 
    if (firstWord.length() == 1) 
     wordCount1 = 1; 
    int nextSpace = space; 
    userInput = userInput.substring(space); 
    } 
    System.out.print(wordCount1); 

I 입력이 "문자열 색인이 범위를 벗어 : 4"저를 준다 "이 문장은"예를 들어 이것에 어떤 도움을 주시면 감사하겠습니다.

int len = userInput.split(" ")[0].length(); 

이 당신에게 공백으로 갈라 단어의 배열을 줄 것이다 그럼 그냥 배열의 첫 번째 위치를 얻을 마지막 길이를 얻을 :와

+0

이제 디버거 사용 방법을 배우는 것이 좋습니다. 변수 "space"의 값은 무엇입니까? – OldProgrammer

+0

'space'의 값은 절대로 업데이트되지 않습니다 –

답변

0

는보십시오.

+0

답장을 보내 주셔서 대단히 감사합니다. 불행히도 우리는 클래스에서 아직 다루지 않았기 때문에 배열을 사용할 수 없습니다. –

0
userInput.indexOf(" "); 

이렇게하면 배열을 사용하지 않고 첫 단어의 길이를 알 수 있습니다. space가 업데이트되지 않기 때문에, 코드가 2의 길이의 문자열에서 4 문자열 인덱스 0에 노력 끝, 때문에

가없는 StringIndexOutOfBoundsException가 슬로우됩니다. userInput는 동안 루프에 인쇄 하였다

경우, 출력 될 것이다 :

This is a sentence 
is a sentence 
a sentence 
ntence 
ce 

그러자 StringIndexOutOfBounds가 발생된다. 내가 배열을 사용하지 않고 문장의 모든 단어를 셀 것

방법은 다음과 같습니다

Scanner in = new Scanner(System.in); 

System.out.print("Enter a sentence: "); 
String input = in.nextLine(); 
in.close(); 

int wordCount = 0; 

while (input.length() > 0) { 
    wordCount++; 
    int space = input.indexOf(" "); 
    if (space == -1) { //Tests if there is no space left 
     break; 
    } 
    input = input.substring(space + 1, input.length()); 
} 

System.out.println("The number of word entered is: " + wordCount); 
+0

답변 해 주셔서 감사합니다. 나는 지금 문제를 이해하고, 나는 그것을 고치는 법을 모른다. 나는 문제가'userInput = userInput.substring (space); '이라고 생각한다.이 단어는 다음 단어와 문장의 나머지 부분으로 간다.하지만 나는 틀렸다. –

+0

수정 된 앤서보기 ... –

0

귀하의 문제는 당신이 공간과 편지를 업데이트하지 않은 것이 었습니다. 잘 작동 할 것입니다 내 약간의 변경 사항을 아래 코드를 참조하십시오.

Scanner myScanner = new Scanner(System.in); 

     int letters = 1; 

     int wordCount1 = 1; 
     String firstWord = null; 

     System.out.print("Enter a sentence: "); 
     String userInput = myScanner.nextLine(); 


     int space = -2; //= userInput.indexOf(" "); // integer for a space character 

     while (letters <= userInput.length() && space != -1) { 

     space = userInput.indexOf(" "); 
     if (space != -1) 
      firstWord = userInput.substring(0, space); 
     if (firstWord.length() == 1) 
      wordCount1 = 1; 
     userInput = userInput.substring(space + 1); 
     } 
     System.out.print(wordCount1); 
} 
관련 문제