2016-08-25 7 views
0

을 종료하지. 숫자는 공백과 줄 바꿈으로 구분됩니다. 입력 스트림의 크기는 256KB를 초과하지 않습니다.자바 입력 방법은 내가이 문제를 해결하기 위해 노력하고있어

당신은 출력의 제곱근을해야 첫 번째까지 마지막에서 각 번호 아이의 출력

. 각 제곱근은 소수점 이하 4 자리 이상의 별도 행에 인쇄해야합니다.


샘플 :

입력 :

1427 0 

876652098643267843 

5276538 

출력 :

2297.0716 

936297014.1164 

0.0000 

37.7757 

그리고 여기 내 코드입니다 :

public class ReverseRoot 
{//start class 
    public static void main(String[] args) 
    {//start main 
     Scanner in = new Scanner(System.in); 
     ArrayList<Long> array = new ArrayList<Long>(); 
     array.add(in.nextLong()); 

     while(in.hasNextLong()) 
     { 
      array.add(in.nextLong()); 
     } 
     in.close(); 

     for (int i = array.size(); i > 0; i--) 
      System.out.printf("%.4f%n", Math.sqrt((double)array.get(i))); 
    }//end main 
}//end class 

거래가 무엇인지 압니까?

+1

나는이 문제입니다 확신이 충분히 익숙하지 해요,하지만 JavaDoc을에서 :는 "next()와 hasNext() 방법과 그들의 원시적 형 (nextInt() 및 hasNextInt()와 같은) 컴패니언 메서드는 먼저 구분 기호 패턴과 일치하는 입력을 건너 뛰고 다음 토큰을 반환하려고 시도합니다. hasNext 및 next 메서드는 모두 이후 입력을 기다리는 것을 차단할 수 있습니다. 연결된 다음 메소드가 차단되는지 여부에 대한 연결이 없습니다. " –

+0

while 루프가 무한 실행 중입니다. 어딘가에 부셔 야합니다 – FallAndLearn

+0

@FallAndLearn 길지 않은 문자를 입력 할 때까지 실행됩니다. – Blobonat

답변

0

목록의 기존 요소에 액세스하려고 시도하면 for 루프가 작동하지 않습니다.

변경은 다음과 루프 :

for (int i = array.size() - 1; i >= 0; i--) 
      System.out.printf("%.4f%n", Math.sqrt((double)array.get(i))); 
    } 

이 왜 루프 외부 array.add(in.nextLong());해야합니까? 이것을 삭제할 수 있습니다.

입력을 종료하려면 비 긴 문자를 콘솔에 입력하기 만하면됩니다.

+0

그가 직면하고있는 오류는 입력입니다. – FallAndLearn

+0

@FallAndLearn 필자는 시스템에서 입력 코드를 테스트했으며 예상대로 작동합니다. – Blobonat

+0

@Blobonat 루프를 시작하기 위해 루프 외부에서 필요하다고 생각 했습니까? 가정하지 마라. 어쨌든 배열 길이는 항상 나를 잡아주는 것처럼 보이므로 문제가되는 것이 당연합니다. 감사! –

0

내가 관찰 한 것처럼 2 개의 루프가 있어야합니다. 첫 번째 루프는 'multiple lines'을위한 것이며 두 번째 루프는 한 줄의 'multiple long value'를위한 것입니다. 여기

은 예입니다

public static void main(String[] args) throws Exception { 
     Scanner console = new Scanner(System.in); 
     Scanner lineTokenizer; 

     // this is to handle all 'lines' 
     while (console.hasNextLine()) { 
      String lineContent = console.nextLine(); 

      if (lineContent == null || lineContent.isEmpty()) { 
       // this is to exit the program if there is no input anymore 
       break; 
      } 
      lineTokenizer = new Scanner(lineContent); 

      // this is to handle a 'line' 
      while (lineTokenizer.hasNext()) { 
       if (lineTokenizer.hasNext()) { 
        long number = lineTokenizer.nextLong(); // consume the valid token 

        System.out.printf("%.4f%n", Math.sqrt((double) number)); 
       } 
      } 
      lineTokenizer.close(); // discard this line 
     } 

     console.close(); // discard lines. 
    } 
관련 문제