扫描仪输入-输入流结束指示器 [英] Scanner input - end of input stream indicator

查看:57
本文介绍了扫描仪输入-输入流结束指示器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行以下操作:将数字读入堆栈; 从堆栈中逐一读出数字; 找到每个数字的平方根并打印结果

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();

    }
}

问题出在读取输入( inscan.hasNext()). 在控制台上输入了最后一个数字后,程序仍然希望我提供输入-一直在等待.

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.

如何让程序知道我已经输入完了/我应该在上面更改LOOP1吗?

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

推荐答案

您还可以使用哨兵输入来终止循环,即计算中未使用的输入.例如

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 '!'

这篇关于扫描仪输入-输入流结束指示器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆