【问题标题】:Parsing String from input as argument issues从输入解析字符串作为参数问题
【发布时间】:2014-10-04 22:35:17
【问题描述】:

我想在我用 unix 编写的 java 程序中添加更多命令,但在传递参数时遇到问题。我刚刚在 unix 中输入了之前使用文本文件作为程序参数的命令,它工作得很好,但想要求输入。试图自己修复它,但对 java 有点新

我有,

     public static void main(String[] args) 
    {
        String input = args[0];
        ///
        String count = args[1];  
        File newF = new File(input); //
        StartProcess start = new StartProcess(input, Integer.parseInt(count));   //begin 

    }

效果很好,然后尝试了这个,失败了

 public static void main(String[] args) 
    {
    //String inputFile = args[0]; //read the input file
    Scanner scanner = new Scanner(new InputStreamReader(System.in));
    System.out.println("Please enter file");
    String input = scanner.nextLine();

    System.out.println("Please enter number");
    int count = scanner.nextInt();
    //String interruptCounter = args[1];  //read the interrupt value
    File newFile = new File(input); //create a new file with the input file
    StartProcess being = new StartProcess(input, Integer.parseInt(count));   //begin 

}

所以我得到了这些错误

CPU.java:24:错误:不兼容的类型 整数计数 = 扫描仪.nextLine(); ^ 必需:整数 找到:字符串 CPU.java:27:错误:找不到适合 parseInt(int) 的方法 StartProcess being = new StartProcess(input, Integer.parseInt(count)); //开始运行进程 ^ 方法 Integer.parseInt(String) 不适用 (实参int不能通过方法调用转换为String) 方法 Integer.parseInt(String,int) 不适用 (实际参数列表和形式参数列表的长度不同) 2 个错误

【问题讨论】:

  • 编译错误似乎与您粘贴的代码无关。根据我的代码应该可以正常编译。

标签: java string file unix


【解决方案1】:

count 已经是整数 - 无需解析变量

StartProcess being = new StartProcess(input, count);

【讨论】:

  • 谢谢,但只修复了一个错误,我仍然得到这个错误 java:24: error: incompatible types int count =scanner.nextLine(); ^ 必需:找到 int:字符串 1 错误
  • 这与您在第二个列表中的不同 - 将其切换回 int count = scanner.nextInt();
【解决方案2】:

此方法nextLine 返回一个字符串而不是整数。

您可能想改用它。

int count = scanner.nextInt();

【讨论】:

    【解决方案3】:

    你输入了一个字符串,改成整数,它应该可以工作。

    【讨论】:

      【解决方案4】:

      您正在重新发明轮子。改用任何标准库,例如Commons CLI.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-11
        • 2017-04-02
        • 2012-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        相关资源
        最近更新 更多