簡體   English   中英

Java輸入法未終止

[英]Java Input method not terminating

我正在嘗試解決此問題:

輸入項

輸入流包含一組整數Ai(0≤Ai≤1018)。 數字由任意數量的空格和換行符分隔。 輸入流的大小不超過256 KB。

輸出量

對於從最后一個到第一個的每個數字Ai,應輸出其平方根。 每個平方根應打印在單獨的行中,小數點后至少應有四位數字。


樣品:

輸入:

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

有人知道這是什么嗎?

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()); 在循環之外? 您可以刪除它。

要退出輸入,只需在控制台中鍵入任何非長字符。

作為觀察者,我們應該有2個循環。 第一個循環用於“多行”,第二個循環用於單行的“多個長值”。

這是一個例子

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.
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM