2014-11-02 2 views
0

내 프로그램이 사용자가 다음 행에서 입력 한 문자를 0이 될 때까지 빼는 데 문제가 있습니다. 예를 들어 길이와 문자에 대한 사용자 입력 5는 첫 번째 줄에 5 개의 "Y"를 인쇄 한 다음 두 번째 줄에 4 개의 "Y"를 인쇄하여 0이 될 때까지 인쇄해야합니다. 이 같은 ... LN (YYYYY)
LN (YYYY) LN (YYY) LN (YY) LN (Y) 내가 얻을 것이 첫 번째 라인을지나 갈 수있는 프로그램 캔트 : LN을 (YYYYY LN (Y) LN (Y) LN (Y) LN (Y)사용자 입력이있는 명령문 프로그램의 단순화

내가 무엇을 가지고 :

int length; 
    char d;  // tried using only char 'd' but scanner has a hard time with chars, so I used  String 
    String UserChar; 

    //scanner is needed 
    Scanner sc = new Scanner(System.in); 

    //get user data and initialize variables 
    System.out.println("Please input a positive whole number."); 
    length = sc.nextInt(); 
    sc.nextLine(); 
    System.out.println("Please input one character."); 
    UserChar = sc.next(); 
    sc.nextLine(); 
    sc.close(); 

    //do computation 
    for(int a = length; a > 1 ; a = a - 1) //prints user input on first line 
    { 
     System.out.print(UserChar); 
    } 

    for(int i = 0; i < length; i = i + 1) //how many lines get printed 
    { 
     System.out.println(UserChar); 
    } 



    // print results (occurs in previous step) 
} 

}

답변

0

은 수행 이 중첩 된 루프를 사용하려고합니다. 첫 번째 루프는 인쇄 할 내용의 길이를 제어하고, 두 번째 루프는 첫 번째 루프에서 사용 된 변수를 기반으로 인쇄를 수행합니다.

//Gets how many chars to print going from n..1 
for(int a = length; a >= 1 ; a = a - 1) 
{ 
    for(int i = 0; i < a; i = i + 1) //prints char a times 
    { 
     System.out.print(UserChar); 
    } 
    System.out.println(); 
} 

Here is an example

: 예를 들어,
관련 문제