初歩的な質問ですみません.
Javaでコンソール入力を受け取りたいのですが,実行すると Scanner#nextLine()で止まらず java.util.NoSuchElementException: No line found
が発生してしまいます.
Scannerをcloseしてるつもりは無いのですが,何か見落としていたらご指摘いただけると幸いです.
java
1public class Main { 2 3 public static void main(String[] args) { 4 try { 5 new Main().start(); 6 } catch (Exception e) { 7 e.printStackTrace(); 8 } 9 } 10 11 private void start() throws IOException { 12 loadProperties(); 13 getConsumerAuth(); 14 saveProperties(); 15 } 16 17 private void saveProperties() throws IOException { 18 try(FileWriter writer = new FileWriter(propertiesFile)) { 19 properties.store(writer, null); 20 } 21 } 22 23 private void getConsumerAuth() throws IOException { 24 Scanner scanner = new Scanner(System.in); 25 // ここで入力値を受け取りたいが,スルーされて Exception 26 // closeはあえてしていない 27 System.out.println("input: " + scanner.nextLine()); 28 } 29 30 private void loadProperties() throws IOException { 31 if (!propertiesFile.getParentFile().exists()) { 32 if(!propertiesFile.getParentFile().mkdirs()) { 33 throw new IOException("Could not make dirs: " + propertiesFile.getParent()); 34 } 35 } 36 if(!propertiesFile.exists() && !propertiesFile.createNewFile()) { 37 throw new IOException("Could not make file: " + propertiesFile); 38 } 39 try (FileReader reader = new FileReader(propertiesFile)) { 40 properties.load(reader); 41 } 42 } 43} 44
追記1:
http://www.javadrive.jp/start/scanner/index2.html
上記サンプルプログラムをコピペしましたが,同様のエラーが出ています.
環境の問題なんでしょうか.
OS: Ubuntu 16.04 x64
IDE: Intellij IDEA
Java: 1.8
Build tool: Gradle
java
1 public static void main(String[] args) { 2 try { 3// new Main().start(); 4 System.out.println("数値を入力して下さい。"); 5 6 Scanner scan = new Scanner(System.in); 7 8 int val = scan.nextInt(); 9 System.out.println("最初の数値のトークンは: "+ val); 10 11 val = scan.nextInt(); 12 System.out.println("次の数値のトークンは : "+ val); 13 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } 17 } 18
追記2:
どうやらGradleだとstandardInputの指定が必要な様子.
http://stackoverflow.com/questions/36723447/java-util-scanner-throws-nosuchelementexception-when-application-is-started-with
ただ,指定しても結果は変わらず...
build.gradle
1(略) 2repositories { 3 mavenCentral() 4} 5 6run { 7 standardInput = System.in 8} 9 10dependencies { 11 testCompile group: 'junit', name: 'junit', version: '4.11' 12} 13
