루프를 사용하여 다음 출력을 인쇄해야 합니다.
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
이 패턴에서 가장 높은 숫자(이 예에서는 7)는 사용자 입력에 의해 결정됩니다. 패턴에 적용 가능한 코드는 다음과 같습니다.
index=patternLength+1; n=1; //These values are all previously intitialized
while (index!=1) {
index--;
printSpaces((index*2)-2); //A static method that prints a certain number of spaces
while(n!=1) {
n--;
System.out.print(n + " ");
}
System.out.print("\n");
n=patternLength+1-index;
}
다음은 사용자 입력 "7"에 대한 잘못된 출력입니다.
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
잘못된 출력 앞에 두 개의 빈 줄이 있습니다. 이 줄에는 완전한/올바른 패턴에 필요한 올바른 수의 공백이 있지만 어떤 이유로 실제 숫자는 루프에서 너무 "늦게" 인쇄되기 시작합니다. 즉, 올바른 예에서 "1, 2 1" 앞에 나타나는 공백은 잘못된 출력에 있습니다. 일부 숫자가 누락되어 잘못된 예를 틀리게 만듭니다.
알겠습니다.
index=patternLength+1; n=1;int nSetter=1;
//Loop C
System.out.println("Pattern C:");
while (index!=1) {
index--;
printSpaces((index*2)-2);
while(n!=0) {
System.out.print(n + " ");
n--;
}
System.out.print("\n");
nSetter++;
n = nSetter;
}
내 문제는 내 "n"이 위아래로 모두 이동해야 했기 때문에 추가 변수 "nSetter"가 해결한 것 같지만 이것이 우회적인 솔루션일 수 있습니다. 도대체 무엇이. 올바른 방향을 알려주신 @Andreas와 유용한 편집을 위해 @JohnKugelman에게 감사드립니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다