Scanner input - end of input stream indicator

守給你的承諾、 提交于 2021-02-19 08:21:22

问题


I want to do the following : Read numbers into a stack; Read out numbers from stack one by one; Find square root for each number and print result

//need a stack class 
import java.util.Iterator;
import java.util.Stack;
import java.io.*;
import java.util.*;
import java.lang.Math;


public class Root { 
    public static void main (String[] args) {

        Scanner inscan  = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);

        Stack<Integer> stk = new Stack<Integer>(); 
        //Iterator iterate = stk.iterator();

        //Read the input stream and push them onto the stack
        while ( (inscan.hasNext()) ){                        //LOOP1
            stk.push(inscan.nextInt());     
        }
        //Pop contents of stack one by one and find square root 
        while ( ! stk.isEmpty() ) {
            int num = stk.pop();
            double root = Math.sqrt(num);
            out.printf("%.4f\n",root);
        }
        inscan.close();
        out.flush();

    }
}

The problem is with reading inputs (inscan.hasNext() ). After entering the last number on the console, program still expects me to supply input - keeps waiting.

How do I let the program know Im done entering input/ should I change LOOP1 above?


回答1:


Also you can use a sentinel input to terminate the loop i.e an input not used in the computation. e.g

while ( (inscan.hasNext()) ){
    String val = inscan.next();
    if(val.equals("!"))
        break;                      
    stk.push(Integer.parseInt(val));     
}

Update: loop terminates on entering '!'




回答2:


[EDIT]

System.in is never closed; so hasNext() results in an infinite loop

Press CTRL + D (linux) or Ctrl + Z + Enter (Windows) to send EOF to close it.




回答3:


You can also input all the text on a single line and split by whichever delimeter you want:

//Read the input stream and push them onto the stack
for(String str: inscan.nextLine().split(" "))
    stk.push(Integer.parseInt(str));

Example:

Input:  1 4 9 16 25
Output: 5.0000
        4.0000
        3.0000
        2.0000
        1.0000


来源:https://stackoverflow.com/questions/20722857/scanner-input-end-of-input-stream-indicator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!