2014-03-30 1 views
0

프로젝트에서이 작업을 수행하고 있으며 지시는 다음과 같습니다 : 프로그램 인수로 두 개의 문자열을 취하는 StringSearch 프로그램을 작성하고, 두 번째 문자열의 첫 번째 문자열 발생 횟수를 인쇄하고 두 번째 문자열의 첫 번째 문자열의 첫 번째 발생 위치 인 의 위치를 ​​인쇄합니다. 저는 아직 초보자이며 교과서에서이 코드의 청크를 빌려 왔지만 제가 작성한 코드에이 코드를 통합하는 방법을 아직 이해하지 못했습니다. 내가 정말로 구체적인 질문을하지 않고 있다는 것을 알고있다. 나는 그 일을 성취하기 위해 코드를 얻는 법을 이해하지 못한다.이 코드에서 바늘과 haystacks 변수에 대한 사용자 입력 방법은 무엇입니까?

package StringSearch; 

/** 
* 
* @author devan 
*/ 
import java.util.Scanner; 

public class SearchString { 

    public static void main(String[] args) { 
    int nargs = args.length; 
    Scanner scanner = new Scanner(System.in); 
System.out.println("Please enter value for needle:"); 
     String needle; 
     needle = scanner.nextLine(); 

System.out.println("Please enter value for haystack:"); 
     String haystack = scanner.nextLine(); 
    if(nargs < 2) { 
System.out.println("Insufficient arguments provided"); 
System.out.println("Usage is: java SearchString needle haystack"); 
    } 
    else { 
     System.out.println(searchString(args[0].toCharArray(),args[1].toCharArray())); 
     System.out.println(getFrequency(args[0].toCharArray(),args[1].toCharArray())); 
    } 
    } 
    public static int searchString(char[] needle, char[] haystack) { 
    int nsize = needle.length; 
    int hsize = haystack.length; 

    for(int i = 0; i < hsize; i++) { 
    int j; 

    for(j = 0; j < nsize; j++) { 
     if(i+j >= hsize) { 
     break; 
     } 
     if(needle[j] != haystack[i+j]) { 
     break; 
     } 
    } 
    if(j == nsize) { 
     return i+1; 
    } 
    } 
    return -1; 
} 

public static int getFrequency(char[] needle, char[] haystack) { 
    int freq = 0; 
    int nsize = needle.length; 
    int hsize = haystack.length; 
    for(int i = 0; i < hsize; i++) { 
    int j; 
    for(j = 0; j < nsize; j++) { 
     if(i+j >= hsize) { 
     break; 
     } 
     if(needle[j] != haystack[i+j]) { 
     break; 
     } 
    } 
    if(j == nsize) { 
     freq++; 
    } 
    } 
    if(freq == 0) 
    return -1; 
    else 
    return freq; 
} 
    } 
+1

귀하의 질문이 명확하지 않습니다. –

답변

1

명령 행 인수의 일반적인 형식은 프롬프트,

오류 메시지
사용법 : 올바른 사용법

그래서 코드가 보일 것이다 뭔가 원하는 경우

if(nargs < 2) { 
    System.out.println("Insufficient arguments provided"); 
    System.out.println("Usage is: java SearchString needle haystack"); 
} ... 

같은 사용자가 상호 작용 방식으로 데이터를 입력 한 다음 스캐너를 사용하는 경우

Scanner scanner = new Scanner(System.in); 
System.out.println("Please enter value for needle:"); 
String needle = scanner.nextLine(); 

System.out.println("Please enter value for haystack:"); 
String haystack = scanner.nextLine(); 
관련 문제