2013-11-14 7 views
1

다음 코드는 사용자로부터 10자를 취하여 역순으로 인쇄해야하는 코드입니다. Scanner에 대해이 구문 오류를 지나칠 수 없습니다. 한 번에 하나의 문자를 어떻게 입력 할 수 있습니까? 여기에 지금까지 무엇을 가지고 :배열에서 문자 읽기

import java.util.Scanner; 

public class ReverseOrder 
{ 
    //----------------------------------------------------------------- 
    // Reads a list of char from user and prints in reverse. 
    //----------------------------------------------------------------- 
    public static void main (String[] args) 
    { 
     Scanner scan = new Scanner (System.in); 

     char[] letters = new char[10]; 

     System.out.println ("The size of the array: " + letters.length); 
     for (int index = 0; index < letters.length; index++) 
     { 
     System.out.print ("Enter number " + (index+1) + ": "); 
     letters[index] = scan.nextchar(); //doesnt like this line 
     } 

     System.out.println ("The numbers in reverse order:"); 

     for (int index = letters.length-1; index >= 0; index--) 
     System.out.print (letters[index] + " "); 
    } 
} 
+1

을 http://stackoverflow.com/questions/18746185/why-doesnt-the-scanner-class-have 참조 -a-nextchar-method 및 http://stackoverflow.com/questions/2597841/scanner-method-to-get-a-char 및 http://stackoverflow.com/questions/19417813/compiler-says-java-code -is-invalid/19417824 # 19417824 – Justin

답변

0

char c = scan.nextLine(). charAt (0);

그는 항상 첫 글자를 원하기 때문에 charAt (인덱스)가 아니어야합니다.

+0

나는 그것을 달리고있다. 도움을 주신 모든 분들께 감사드립니다. – Lou44

+0

해당 질문에 동의하는 대답을 선택하십시오. 덕분에 – user2664856

1

불행하게도, nextChar()이 방법이 아닙니다. 대신 next().charAt(0)을 사용하여 해결할 수 있습니다!

public class ReverseOrder 
{ 
    //----------------------------------------------------------------- 
    // Reads a list of char from user and prints in reverse. 
    //----------------------------------------------------------------- 
    public static void main (String[] args) 
    { 
     Scanner scan = new Scanner (System.in); 

     char[] letters = new char[10]; 

     System.out.println ("The size of the array: " + letters.length); 
     for (int index = 0; index < letters.length; index++) 
     { 
     System.out.print ("Enter number " + (index+1) + ": "); 
     letters[index] = scan.next().charAt(0); 

     } 

     System.out.println ("The numbers in reverse order:"); 

     for (int index = letters.length-1; index >= 0; index--) 
     System.out.print (letters[index] + " "); 
    } 
} 
+0

"chars"는 어떻게 읽을 수 있습니까? – Lou44

+0

왜 그냥 >> char c = scan.nextLine(). charAt (0);을 호출 할 수 있다면 "in"이라는 문자열을 생성해야합니다. < user2664856

+0

@ user2664856 방금 코드를 편집하고 업데이트하고 단순화했습니다. 결국 그것은 정말로 중요하지 않습니까? 모든 가독성 대 코드 우아함 토론을 반복합니다.) – knordbo

1

당신은 당신의 경우에 사용할 수 있습니다 scan.nextchar에 대한 교체로

letters[index] = scan.nextLine().charAt(0); 

();

2

또한 루프를 사용하지 않고 역순으로 인쇄 할 수 있습니다 : 또한

System.out.println("The numbers in reverse order:"); 
System.out.println(new StringBuilder(new String(letters)).reverse()) 
+1

좋은 지적입니다. 그러나 그것은 문제가되지 않습니다. 묻는 사람은'Scanner.nextChar()'와 같은 것을 사용하는 방법을 묻습니다. – Justin