=","==","!=","&&","||","$"}; ArrayList variables = new ArrayList(); -6ren">
gpt4 book ai didi

java - 扫描仪从文件而不是控制台读取

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:22 25 4
gpt4 key购买 nike

我试图通过使用命令“java PostFix < in.dat”从文件中获取表达式来计算后缀表达式。现在,当我想从用户(即控制台)获取变量的值时,它恰好从文件中读取并给出输入不匹配异常(因为它从文件而不是从控制台读取字符串值)。以下是我的代码的摘录。如何从控制台而不是文件获取输入?

public class PostFix{ 

String operators[] = new String[]{"+","-","*","/","_","!","#","^","<","<=",">",">=","==","!=","&&","||","$"};
ArrayList<String> variables = new ArrayList<String>();
ArrayList<Integer> variable_value = new ArrayList<Integer>();

public static void main(String[] args) {
// TODO Auto-generated method stub

PostFix pf = new PostFix();
pf.getVariables();

}

public void getVariables(){

Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String tokens[] = line.split(" ");

while(sc.hasNextLine()){
System.out.println("in geVariables()");
for(int i = 0; i < tokens.length; i++){

if(!Arrays.asList(operators).contains(tokens[i])){

try{
Integer.parseInt(tokens[i]);
}
catch(Exception e){
//e.printStackTrace();

variables.add(tokens[i]);
System.out.println("Please enter the value of "+tokens[i]);
variable_value.add(sc.nextInt());
}

}

}

}
sc.close();
}

}

错误:

Please enter the value of a
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at PostFix.getVariables(PostFix.java:51)
at PostFix.main(PostFix.java:16)

in.dat 文件的内容:

2 a + b _ * ! c c ^ 15 / # - $
value x + value y - != x y <= && $

最佳答案

java PostFix < in.dat

意味着所有标准输入都将从in.dat文件中获取。

您的 Java 代码不知道此重定向。它只是从System.in(即标准输入)读取,这通常意味着键盘

因此,解决方案就是简单地让您的代码运行而无需任何重定向

java PostFix

关于java - 扫描仪从文件而不是控制台读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28290457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com