2016-10-20 4 views
2

그래서 하나의 String 객체와 하나의 정수를 허용하고 그 문자열을 정수로 반복하는 메소드를 작성해야합니다.메서드를 사용한 문자열 반복

예 : repeat ("ya", 3) "yayaya"를 표시해야합니다. 이 코드는 적어 두었지만 다른 하나는 인쇄합니다. 너 나 좀 도와 줄래?

public class Exercise{ 

    public static void main(String[] args){ 

    repeat("ya", 5); 
    } 

    public static void repeat(String str, int times){ 

    for(int i = 0;i < times;i++){ 
     System.out.println(str); 
    } 
    } 
} 
+4

변경 System.out.print''에'System.out.println','후 당신의 고리). –

+0

[Print a String 'X'Times (No Loop)] 가능한 복제본 (http://stackoverflow.com/questions/19455473/print-a-string-x-times-no-loop) – smac89

답변

2

, 그래서 이것을 사용해보십시오 : 당신은이를 변경하려면

public static void repeat(String str, int times){ 

    for(int i = 0;i < times;i++){ 
     System.out.print(str); 
    } 
} 
2

System.out.println은 포함 된 내용을 인쇄 한 다음 줄 바꿈 문자를 사용합니다. 당신은 새로운 라인을 인쇄하는

public class Exercise{ 
    public static void main(String[] args){ 
    repeat("ya", 5); 
    } 

    public static void repeat(String str, int times){ 
    for(int i = 0; i < times; i++){ 
     System.out.print(str); 
    } 
    // This is only if you want a new line after the repeated string prints. 
    System.out.print("\n"); 
    } 
} 
0
public class pgm { 

    public static void main(String[] args){ 

    repeat("ya", 5); 
    } 

    public static void repeat(String str, int times){ 

    for(int i = 0;i < times;i++){ 
     System.out.print(str); 
    } 
    } 
} 
+3

코드 만 응답 게시 금지 가능하다면. 답변을 통해 질문에 대한 답이나 제공된 솔루션의 문제점을 OP에게 알리십시오. – smac89

1

변경합니다 System.out.print()-System.out.println()합니다.

println() 사용 예 :

System.out.println("hello");// contains \n after the string 
System.out.println("hello"); 

출력 :

hello 
hello 

print() 사용 예 :

System.out.print("hello"); 
System.out.print("hello"); 

출력 :

다른 점을 이해하십시오.

루프없이/재귀를 사용하여 예 : (그리고`에서 System.out.println()를 추가

public class Repeat { 

    StringBuilder builder = new StringBuilder(); 

    public static void main(String[] args) {  
     Repeat rep = new Repeat(); 
     rep.repeat("hello", 10); 
     System.out.println(rep.builder);  
    } 


    public void repeat(String str, int times){ 
     if(times == 0){ 
      return; 
     } 
     builder.append(str); 

     repeat(str, --times); 
    } 

}