【问题标题】:How to ask user for an input file name and output file name java?java - 如何询问用户输入文件名和输出文件名java?
【发布时间】:2014-05-05 21:14:57
【问题描述】:

我正在尝试制作一个要求程序输入和输出文件名的程序,但是我在制作程序时遇到了麻烦,尤其是在询问输出文件的文件名时。 这两种方法都将要求用户输入适当的文件名并将该名称作为字符串返回。这些方法将从主方法中调用。它们将返回一个字符串,因此在调用方法之前应该声明两个字符串变量。

这是读取输入文件并创建输出文件的部分程序,但我无法添加将询问文件名的程序部分。

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class WebberProject3 {
private static Map<String, Integer> ticketTypeToPrice = new HashMap<String, Integer>();
private static final String SPACE = " ";
private static final String CURRENCY_SYMBOL = " $";

    public static void main(String[] args) {
    Scanner scanner = null;
    PrintWriter outputFile = null;
    DecimalFormat decimalFormat = new DecimalFormat();
    decimalFormat.setMinimumFractionDigits(2);
    try {
        File file = new File("portlandvip2.txt");
        scanner = new Scanner(file);
        outputFile = new PrintWriter("portland2out.txt");
        while (scanner.hasNext()) {
            String line = scanner.nextLine();
            String[] entriesOnLine = line.split(" ");
            // Line with price and ticket type
            if(entriesOnLine.length == 2) {
                ticketTypeToPrice.put(entriesOnLine[0],         Integer.parseInt(entriesOnLine[1]));
                StringBuilder sb = new StringBuilder();
                sb.append(entriesOnLine[0])
                    .append(CURRENCY_SYMBOL)
                    .append(decimalFormat.format(Integer.parseInt(entriesOnLine[1])));
                outputFile.println(sb.toString());
            } else if (entriesOnLine.length == 4) {
                //Line with First Name, Last Name, number of Tickets and Price
                int numberOfTickest = Integer.parseInt(entriesOnLine[2]);
                int ticketPrice = ticketTypeToPrice.get(entriesOnLine[3]);
                int totalPrice = numberOfTickest*ticketPrice;
                StringBuilder sb = new StringBuilder();
                sb.append(entriesOnLine[0])
                    .append(SPACE)
                    .append(entriesOnLine[1])
                    .append(CURRENCY_SYMBOL)
                    .append(decimalFormat.format(totalPrice));
                outputFile.println(sb.toString());
            }
        }
    } catch (IOException e) {
        System.out.println("exception:" + e);
    } finally {
        scanner.close();
        outputFile.close();
    }
}
}

为了让这个程序正常工作,我需要使用标题名称制作 2 种不同的方法:

public static String getInputFileName()
public static String getOutputFileName()

请帮忙,我是编程的初学者,我尝试了一些不同的东西,但没有任何效果。任何帮助将不胜感激

这将是我尝试过的一个例子(我在阅读了这篇文章的评论后尝试了这个):

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;


public static void String getInputFileName()
{
  System.out.println("Enter filename here : ");

   String sWhatever;

   Scanner scanIn = new Scanner(System.in);
   sWhatever = scanIn.nextLine();

   scanIn.close();            
   System.out.println(sWhatever);
}
}

public class WebberProject3Test1
{
public static void main(String[] args) {
{
private static Map<String, Integer> ticketTypeToPrice = new HashMap<String, Integer>();
private static final String SPACE = " ";
private static final String CURRENCY_SYMBOL = " $";

public static void main(String[] args) {
    Scanner scanner = null;
    PrintWriter outputFile = null;
    DecimalFormat decimalFormat = new DecimalFormat();
    decimalFormat.setMinimumFractionDigits(2);
    try {
        File file = new File("portlandvip2.txt");
        scanner = new Scanner(file);
        outputFile = new PrintWriter("portland2out.txt");
        while (scanner.hasNext()) {
            String line = scanner.nextLine();
            String[] entriesOnLine = line.split(" ");
            // Line with price and ticket type
            if(entriesOnLine.length == 2) {
                ticketTypeToPrice.put(entriesOnLine[0],    Integer.parseInt(entriesOnLine[1]));
                StringBuilder sb = new StringBuilder();
                sb.append(entriesOnLine[0])
                    .append(CURRENCY_SYMBOL)
                    .append(decimalFormat.format(Integer.parseInt(entriesOnLine[1])));
                outputFile.println(sb.toString());
            } else if (entriesOnLine.length == 4) {
                //Line with First Name, Last Name, number of Tickets and Price
                int numberOfTickest = Integer.parseInt(entriesOnLine[2]);
                int ticketPrice = ticketTypeToPrice.get(entriesOnLine[3]);
                int totalPrice = numberOfTickest*ticketPrice;
                StringBuilder sb = new StringBuilder();
                sb.append(entriesOnLine[0])
                    .append(SPACE)
                    .append(entriesOnLine[1])
                    .append(CURRENCY_SYMBOL)
                    .append(decimalFormat.format(totalPrice));
                outputFile.println(sb.toString());
            }
        }
    } catch (IOException e) {
        System.out.println("exception:" + e);
    } finally {
        scanner.close();
        outputFile.close();
    }
}
}
}

我得到这样的错误:

发现 9 个错误:

File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 10]
Error: Syntax error on tokens, ClassHeader expected instead

File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 12]
Error: Syntax error on token(s), misplaced construct(s)
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 12]
Error: Syntax error on token ""Enter filename here : "", delete this token
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 16]
Error: Syntax error on token ";", { expected after this token

File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 26]
Error: Duplicate method main(java.lang.String[]) in type WebberProject3Test1

File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 27]
Error: Syntax error, insert "}" to complete BlockStatements

File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 27]
Error: Syntax error, insert "}" to complete MethodBody

File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 32]
Error: Duplicate method main(java.lang.String[]) in type WebberProject3Test1

File: C:\Users\Eddie\CISS100\WebberProject3Test1.java  [line: 74]
Error: Syntax error on token "}", delete this token

【问题讨论】:

  • 您可以使用时髦的新 Console 类。好吧,不是那么新 - 从 1.6 开始
  • 你应该把你的错误列表写成不同的帖子,并将某人的代码标记为答案。你代码中的错误是编译错误,如果你给我一个链接,我可以在另一篇文章中解释。
  • 我更新了我的答案以反映您的更新

标签: java


【解决方案1】:

如果您想要求用户输入,最常见的方法是创建 Scanner 类的实例,并带有 System 输入的参数,如下所示

Scanner userInput = new Scanner(System.in);

然后您可以调用此类的方法来获取用户键入的下一行文本,因此您的代码可能看起来像这样

System.out.println("where to read?");
String in = userInput.nextLine();
System.out.println("where to write?");
String out = userInput.nextLine();
Scanner scanner = new Scanner(new File(in));
PrintWriter outputFile = new PrintWriter(out);

此代码允许用户在命令行或 netbeans/eclipse 中从终端读取和写入。

对于您的编译错误:

第 10 行:public static void String getInputFileName()

方法/函数必须在类的主体内声明。所以移动整个函数

在你的函数之后,你有一个额外的右花括号,所以删除它。

您不能两次声明 public static void main(String[] args)。您尤其不能在另一个方法中使用方法,因此请删除外部 public static void main(String[] args) { 和后面的额外开口花括号。

public static void String getInputFileName() 只能有一种返回类型,因此将其设置为 void,因为您不返回。

最后删除多余的结束大括号。

你的代码应该是这样的

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class WebberProject3Test1 {

    private static Map<String, Integer> ticketTypeToPrice = new HashMap<String, Integer>();
    private static final String SPACE = " ";
    private static final String CURRENCY_SYMBOL = " $";

    public static void getInputFileName() {
        System.out.println("Enter filename here : ");

        String sWhatever;

        Scanner scanIn = new Scanner(System.in);
        sWhatever = scanIn.nextLine();

        scanIn.close();
        System.out.println(sWhatever);
    }

    public static void main(String[] args) {
        Scanner scanner = null;
        PrintWriter outputFile = null;
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setMinimumFractionDigits(2);
        try {
            File file = new File("portlandvip2.txt");
            scanner = new Scanner(file);
            outputFile = new PrintWriter("portland2out.txt");
            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                String[] entriesOnLine = line.split(" ");
                // Line with price and ticket type
                if (entriesOnLine.length == 2) {
                    ticketTypeToPrice.put(entriesOnLine[0], Integer.parseInt(entriesOnLine[1]));
                    StringBuilder sb = new StringBuilder();
                    sb.append(entriesOnLine[0])
                            .append(CURRENCY_SYMBOL)
                            .append(decimalFormat.format(Integer.parseInt(entriesOnLine[1])));
                    outputFile.println(sb.toString());
                } else if (entriesOnLine.length == 4) {
                    //Line with First Name, Last Name, number of Tickets and Price
                    int numberOfTickest = Integer.parseInt(entriesOnLine[2]);
                    int ticketPrice = ticketTypeToPrice.get(entriesOnLine[3]);
                    int totalPrice = numberOfTickest * ticketPrice;
                    StringBuilder sb = new StringBuilder();
                    sb.append(entriesOnLine[0])
                            .append(SPACE)
                            .append(entriesOnLine[1])
                            .append(CURRENCY_SYMBOL)
                            .append(decimalFormat.format(totalPrice));
                    outputFile.println(sb.toString());
                }
            }
        } catch (IOException e) {
            System.out.println("exception:" + e);
        } finally {
            scanner.close();
            outputFile.close();
        }
    }
}

注意:这段代码现在可以编译了,这并不意味着我让它做你想做的事。

【讨论】:

  • 时髦的新 Console 更时髦,但无论如何 +1。
【解决方案2】:

如果你需要读取用户的输入,你可以这样做:

    System.out.println("Type an input path: ");
    Scanner s = new Scanner (System.in);

    String input = s.nextLine();

input 中,您将看到用户编写的文本。

【讨论】:

    【解决方案3】:

    如果您想要求用户通过在控制台中输入文件名来提供文件名,您可以使用 BufferedReader 的 readLine 或 Scanner 的 nextLine。 BufferedReader 的例子:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class ReadConsoleSystem {
      public static void main(String[] args) {
    
        System.out.println("Enter filename here : ");
    
        try{
            BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
            String s = bufferRead.readLine();
    
            System.out.println(s);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    
      }
    }
    

    扫描仪示例

    import java.util.Scanner;
    
    public class ReadConsoleScanner {
      public static void main(String[] args) {
    
          System.out.println("Enter filename here : ");
    
           String sWhatever;
    
           Scanner scanIn = new Scanner(System.in);
           sWhatever = scanIn.nextLine();
    
           scanIn.close();            
           System.out.println(sWhatever);
      }
    }
    

    示例取自this article

    【讨论】:

    • 我在尝试将您的答案添加到程序中后编辑了我的初始帖子,如果我做错了什么,您能告诉我吗?为什么我会收到这些错误?
    • 该代码是一个示例,用于说明 BufferedReader 的 redLine 和 Scanner 的 nextLine 的用法。在新版本中,我在 getInputFileName 方法中看到了嵌套的 main 方法。
    • 是否应该先执行 main 方法,然后是 getInputFileName 方法?我遇到的一个问题是,我试图弄清楚应该首先使用哪个方法,主要方法还是 getInput 方法。
    • 这些方法可以按任何顺序出现。它们只是不应该像您上次编辑那样在彼此内部。分别声明它们。
    • @user3605753 你能想想你在做什么吗?您有两个 main 方法 - 这必须是错误的。您也很可能有不匹配的括号。如果你被灌输了答案,你将永远无法理解它。您有所有要查找的参考资料,现在做一些工作
    猜你喜欢
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 2012-05-16
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多