2017-11-19 22 views
0

사용자가 임의의 문자열을 입력 할 수있는 프로그램을 구현하려고합니다. 콘솔에 문자 만 표시됩니다. 문자 이외의 문자열을 입력하면 사용자에게 알려야합니다. 지금까지 몇 가지 코드가 있지만 예를 들어 "I-Love-You", "너무 많이"라고 입력하면됩니다. 결과물은 "ILoveYou so much"이어야하지만 실제로 출력물이 "I-Love-You so much"이기 때문에 실제로 이렇게 작동하지 않습니다. 내 코드의 실수는 어디에 있습니까?Java - 문자열의 문자 만 인식합니다.

// Input 
int i = 0; 
write("Please enter consecutively at least one word (only letters) and finish it with an empty one."); 
String input = readString("Enter a word:"); 
while(input.length() == 0) { // Enter at least one word 
    input = readString("Wrong input. Enter at least one word:"); 
} 
while(input.length() != 0) { // End input by an empty String 
    while(i < input.length()) { // Iterate through input 
     char text = input.charAt(i); 
     if(text >= 'a' && text <= 'z') { // Check lower case letters 
      if(text >= 'A' && text >= 'Z') { // Check upper case letters 
       if(text == 'ä' || text == 'ö' || text == 'ü' || text == 'ß'){ // Check mutated vowel 
        text = input.charAt(i-1); // Ignore wrong input 
        write("Wrong input."); 
       } 
      } 
     } 
    ++i; 
} 
String inPut = input +" "; 
System.out.print(inPut); 
input = readString("Enter a word:");  

}

+1

복잡한 것을 살펴보면 더 간단한 방법이 있습니다. –

+0

이 문제를 해결하는 더 간단한 방법이 좋을 것입니다. –

답변

1

당신이 다음과 같은 코드를 사용할 수 있습니다, 그것은 도움이 될 것입니다 바랍니다.

int i = 0; 
    System.out.println("Please enter consecutively at least one word (only letters) and finish it with an empty one."); 
    Scanner lire=new Scanner(System.in); 
    String input = lire.nextLine(); 
    while(input.length() == 0) { // Enter at least one word 
     System.out.println("Wrong input. Enter at least one word:"); 
     input = lire.nextLine(); 
    } 

    String output=""; 
    while(input.length() != 0){ 
     while(i < input.length()) { 
      char text = input.charAt(i); 
      if((text >= 'a' && text <= 'z') || (text >= 'A' && text <= 'Z') || text == 'ä' || text == 'ö' || text == 'ü' || text == 'ß' || text==' ') { 
       output=output+text; 
      } 

      ++i; 
     } 
     System.out.println("Input : "+input); 
     System.out.println("Output : "+output); 
     System.out.println("Enter a word:"); 
     input = lire.nextLine(); 
    } 

출력 :

그것은 바로 지금, 당신은 readString에서 입력을 설정하고 있지만 루프가 실제로 아무것도하지 않는 보이는
Please enter consecutively at least one word (only letters) and finish it with an empty one. 
I-Love-you so much. 
Input : I-Love-you so much. 
Output : ILoveyou so much 
Enter a word: 
+0

이것은 실제로 아주 멋지다! 하지만 사용자에게 그가 잘못된 문자열을 입력했음을 알릴 수있는 위치는 어디입니까? 아마도 "++ i;" 권리? –

+0

예, 다음과 같이 else else 절을 ​​추가 할 수 있습니다 :'else {System.out.println ("잘못된 문자를 부여했습니다 :"+ text);}' –

1

. 텍스트는 설정되었지만 사용되지 않았습니다. while 루프를 빠져 나오면 초기 값에 공간이 추가되고 수정되지 않고 인쇄되므로 원래 문자열이 나옵니다.

이 문제를 개선하려면 처음 시도를 if 문으로 변경하십시오. 문자열을 반복하는 루프를 사용 - 더 나은, 각 루프/향상 사용

for(char c : input) { 
    // stuff here 
} 

그것은 또한 당신이 전화의 미친 스택으로 끝나는 같은 방법을 많이 호출 될 예정처럼 보인다 - 함수의 시작 부분에서 다시 시작하려는 입력에 문제가있는 경우 대신. 희망이 당신에게 시작

편집 제공 : 예

while(true) { 
    System.out.println("Please enter consecutively at least one word (only letters) and finish it with an empty one."); 
    Scanner sc = new Scanner(System.in); 
    String input = sc.nextLine();  
    StringBuilder result = new StringBuilder(); 
    if (input.length() == 0) { 
     System.out.println("Please enter at least one word"); 
    } 
    if (input.length() > 0) { 
     for (char c : input) { 
      // validate your characters 
      result.append(c); 
     } 
     System.out.println(result.toString()); 
     // optionally use return here to end the loop 
    } 
} 

을 당신이 할 수 물론 사용 문자열 연결의 있지만 모두 StringBuilder가 너무 좋다. 캐릭터를 문자열 (Character.toString(c))으로 바꾸면됩니다. 우리는 while(true)으로 무한 루프에 있으며, 단어가 없다면 두 번째 if 문을 실행하지 않으므로 처음부터 루프가 시작된다는 것을 알 수 있습니다.

+0

이것은 매우 유용한 답변입니다. 이것을 고려해. 고맙습니다. –

1

정규 표현식을 살펴볼 수도 있습니다. 예를 들어 .matches("[a-zA-Z]")은 글자 만 일치합니다.

String str = "I-Love-You so 234much'^Br7u..h."; 
StringBuilder sb = new StringBuilder(); 
char[] arrr = str.toCharArray(); 
for (char c : arrr) { 
    // I'm sure there's a way to include the space in the regex but I don't know how to 
    if (String.valueOf(c).matches("[a-zA-Z]") || String.valueOf(c).matches(" ")) { 
     sb.append(c); 
    } 
} 
System.out.println(sb.toString()); 

출력 : ILoveYou so muchBruh

+0

대단히 고마워요! 나는 정규 표현식이 무슨 뜻인지 모르겠다. 그것은 Ascii 테이블에 연결되어 있습니까? –

+1

"정규식, regex 또는 regexp는 이론적 인 컴퓨터 과학 및 형식 언어 이론에서 검색 패턴을 정의하는 일련의 문자입니다."Wikipedia의 첫 번째 라인 내가 말했듯이, 조사 할 가치가있다. 어떤 패턴이든 꽤 많이 찾을 수있다. – Touniouk

1

나는 readString 방법 일 수 없었다, 그래서 내가 대신 정규 표현식을 사용했다. 희망이 도움이 될 것입니다.

import java.util.regex.*; 
import java.util.Scanner; 

public class wordSieve 
{ 

    public static void main(String[] args) 
    { 
     String str; 
     StringBuilder c = new StringBuilder(); 
     Scanner input = new Scanner(System.in); 
     System.out.println("Please enter consecutively at least one word (only letters) and finish it with an empty one."); 
     str = input.nextLine(); 

     while (str.length() != 0) 
     { 
      // Find a to z or A to Z at least of length 1 
      // maybe starting and ending with whitespace. 
      regexChecker("\\s?[A-Za-z]\\s?{1,}", str, c); 
      System.out.print(""); 
      str = input.nextLine(); 
     } 
     System.out.print(c); 
    } 

    public static void regexChecker(String theRegex, String str2Check, StringBuilder outputStr) { 
     Pattern checkRegex = Pattern.compile(theRegex); 
     Matcher regexMatcher = checkRegex.matcher(str2Check); 
     while (regexMatcher.find()) // find all the matches 
     { 
      if (regexMatcher.group().length() != 0) 
      { 
       outputStr.append(regexMatcher.group()); 
      } 
     } 
    } 
}