사용자 입력을 int
으로하고 그 번호를 입력하려고합니다.스캐너로 배열 길이를 초기화했습니다.
프로그램은 이러한 이름을 거꾸로 역순으로 인쇄합니다. 그러나, 내가이 이름들을 저장하고있는 배열은 항상 Scanner
을 사용할 때 하나의 요소가 너무 작게 만들어집니다. 방금 번호를 할당하면이 문제가 발생하지 않습니다. Scanner
과 관련된 고유 항목이 있습니까? 아니면 내가 뭘 잘못하고 있습니까?
import java.util.Scanner;
class forTester {
public static void main (String str[]) {
Scanner scan = new Scanner(System.in);
//Why does this commented code scan only one less name than expected???
/*
System.out.println("How many names do you want to enter?");
int num = scan.nextInt();
System.out.println("Enter " + num + " Names:");
String names[] = new String[num];
*/
//Comment out the next two lines if you use the four lines above.
System.out.println("Enter " + 4 + " Names:");
String names[] = new String[4];
// The code below works fine.
for (int i = 0; i < names.length; i++) {
names[i]=scan.nextLine();
}
for(int i = names.length - 1; i >= 0; i--) {
for(int p = names[i].length() - 1; p >= 0; p--) {
System.out.print(names[i].charAt(p));
}
System.out.println("");
}
}
}