Java 扫描仪输入-输入流结束指示器
我想做以下工作:将数字读入堆栈; 从堆栈中逐个读出数字; 找到每个数字的平方根并打印结果Java 扫描仪输入-输入流结束指示器,java,java.util.scanner,Java,Java.util.scanner,我想做以下工作:将数字读入堆栈; 从堆栈中逐个读出数字; 找到每个数字的平方根并打印结果 //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) {
//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();
}
}
//需要一个堆栈类
导入java.util.Iterator;
导入java.util.Stack;
导入java.io.*;
导入java.util.*;
导入java.lang.Math;
公共类根{
公共静态void main(字符串[]args){
扫描仪inscan=新扫描仪(System.in);
PrintWriter out=新的PrintWriter(System.out);
堆栈stk=新堆栈();
//迭代器iterate=stk.Iterator();
//读取输入流并将其推送到堆栈上
而((inscan.hasNext()){//LOOP1
stk.push(inscan.nextInt());
}
//逐个弹出堆栈内容并找到平方根
而(!stk.isEmpty()){
int num=stk.pop();
双根=Math.sqrt(num);
out.printf(“%.4f\n”,根);
}
inscan.close();
out.flush();
}
}
问题在于读取输入(inscan.hasNext())。
在控制台上输入最后一个数字后,程序仍然希望我提供输入-一直等待
我如何让程序知道我输入了输入/我应该更改上面的LOOP1 [编辑]
系统中的
从不关闭;因此,hasNext()
会产生一个无限循环
按CTRL+D(linux)或CTRL+Z+Enter(Windows)发送
EOF
以关闭它。[EDIT]
系统中的
从不关闭;因此,hasNext()
会产生一个无限循环
按CTRL+D(linux)或CTRL+Z+Enter(Windows)发送
EOF
以关闭它。还可以使用sentinel输入终止循环,即计算中未使用的输入。e、 g
while ( (inscan.hasNext()) ){
String val = inscan.next();
if(val.equals("!"))
break;
stk.push(Integer.parseInt(val));
}
更新:循环在输入“!”时终止 您还可以使用sentinel输入来终止循环,即计算中未使用的输入。e、 g
while ( (inscan.hasNext()) ){
String val = inscan.next();
if(val.equals("!"))
break;
stk.push(Integer.parseInt(val));
}
更新:循环在输入“!”时终止 您还可以在一行中输入所有文本,并按所需的delimeter进行拆分:
//Read the input stream and push them onto the stack
for(String str: inscan.nextLine().split(" "))
stk.push(Integer.parseInt(str));
例子:
您还可以在一行中输入所有文本,并按您想要的delimeter进行拆分:
//Read the input stream and push them onto the stack
for(String str: inscan.nextLine().split(" "))
stk.push(Integer.parseInt(str));
例子: 所有平台都是这样(ctrl+D)吗?所有平台都是这样(ctrl+D)吗?