2012-09-09 2 views
2

그래서 내가 가진 코드는 사용자가 문장 (문자열)을 입력하고 문자열을 검색하여 가장 작은 단어를 반환해야하는 숙제를위한 코드입니다. 그러나 문자열의 첫 번째 자리에 숫자가 입력되어야합니다. 예 : "4 이것은 무엇입니까?" 출력은 "IS"이어야하며 숫자는 무시하십시오. 숫자를 무시하는 방법을 알아내는 유일한 방법은 숫자가 될 첫 번째 지점으로 루프를 건너 뛰는 것입니다. 그것은 그 자체로 작동하지만 나는 그것을 나의 프로그램의 나머지 부분에 넣을 때마다 작동을 멈춘다. 어쨌든이 프로그램을 더 깨끗하게 만들 수 있습니까? 당신의 for 루프 (즉 i = 0에서 시작한다) 내부코드를 수정하십시오. 검색 문자열

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    // Lexicographically smallest word 
    String TheSentence = sc.nextLine(); 
    String[] myWords = TheSentence.split(" "); 
    int shortestLengths, shortestLocation; 
    shortestLengths = (myWords[1]).length(); 
    shortestLocation = 1; 
    for (int i = 1; i < myWords.length; i++) { 
     if ((myWords[i]).length() < shortestLengths) { 
      shortestLengths = (myWords[i]).length(); 
      shortestLocation = i; 
     } 
    } 
    System.out.println(myWords[shortestLocation]); 
} 
+4

것 "123A abc 방송의 AB3"짧은 단어의 "가", "ABC"와 같은 문장에 대해, "AB"또는 "ab3"? – Kru

답변

1

, 다음과 같은 코드를 추가 :

try { 
    double value = Double.parseDouble(myWords[i]); 
} catch (NumberFormatException e) { 
    // add the rest of your code here 
} 

아이디어는 당신이 번호로 단어를 변환하려고한다는 것입니다 그리고 당신은 그것을 실패하는 경우 숫자가 아님을 의미하므로 단어의 길이 논리를 사용할 수 있습니다.

+0

답과 함께, 코드에서'shortestLocation = 0;'을 만드는 것을 잊지 마십시오. –

0

가장 먼저해야 할 일은 입력 스트림에서 행을 읽는 것과 같은 연습 문제와 관련된 코드를 믹싱하는 대신 사용할 함수를 만드는 것입니다.

Character.isLetter(char)을 사용하여 문자가 문자인지 테스트 할 수 있습니다. 좋은 연습은 그 기능 만 사용하고 루프 내에서 각 문자 (String.charAt(int) 방법)를 개별적으로 바라 보는 솔루션을 만드는 것입니다. 해결책은 현재 가장 짧은 단어의 시작 위치와 길이를 기억하는 것입니다.


실제로, 난 그냥 같은 정규 표현식에를 사용합니다 :

public static String shortestWord(String sentence) { 
    String shortest = null; 
    Pattern word = Pattern.compile("\\w+"); 
    Matcher m = word.matcher(sentence); 
    while (m.find()) { 
    String candidate = m.group(); 
    if (shortest == null || shortest.length() > candidate.length()) 
     shortest = candidate; 
    } 
    return shortest; 
} 
0

을 당신은 문자열을 사용하여 예를 시도해 볼 수도 있습니다

String result=inputString.substring(1) 

'1'은 문자열의 두 번째 문자이고, 첫 번째 문자열에 대한 모든 값을 반환하는 하위 문자열입니다.

0

아래 코드는 기본적으로 코드를 줄입니다. 그 말은 .. 그것은 shortestWord() 또는 뭔가라는 메서드에서이 모든 것을 만드는 것이 훨씬 낫습니다. 아래 코드가 작동하지 않아야 할 이유는 없습니다.

개정 코드 :

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    String[] myWords = (sc.nextLine()).split(" "); 
    int shortestLocation = 1 
    for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have 
               // already made shortestLocation = 1 
     if (myWords[i].length() < myWords[shortestLocation].length()) { 
      shortestLocation = i; 
     } 
    } 
    System.out.println(myWords[shortestLocation]); 
} 

하기 권장 코드 :

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    String[] myWords = (sc.nextLine()).split(" "); 
    System.out.println("The shortest word is: " + shortestWord(myWords)); 
} 

public static String shortestWord(String[] myWords) { 
    int shortestLocation = 1 
    for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have 
               // already made shortestLocation = 1 
     if (myWords[i].length() < myWords[shortestLocation].length()) { 
      shortestLocation = i; 
     } 
    } 
    return myWords[shortestLocation]; 
} 
관련 문제