简体   繁体   English

如何询问用户输入文件名和输出文件名java?

[英]How to ask user for an input file name and output file name java?

I am trying to make a program that asks for a program input and output file names, but i am having trouble in making the program, especially for asking the file name for the output file. 我正在尝试创建一个程序,询问程序输入和输出文件名,但我在制作程序时遇到问题,特别是在询问输出文件的文件名时。 Both of these methods will ask the user to enter the appropriate file name and return that name as a String. 这两种方法都会要求用户输入相应的文件名并将该名称作为String返回。 These methods will be called from the main method. 这些方法将从main方法调用。 They will return a String so there should be two String variables declared before the methods are called. 它们将返回一个String,因此在调用方法之前应该声明两个String变量。

This is the part program that reads an input file and creates an output file, but i am having trouble with adding the part of the program that will ask for the file names. 这是读取输入文件并创建输出文件的零件程序,但是我在添加要求文件名的程序部分时遇到问题。

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

In order for this program to work, i need to make 2 different methods with the headers names: 为了使这个程序工作,我需要使用标题名称制作两种不同的方法:

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

Please help, i am a beginner to programming, and i have tried a few different things, but nothing is really working. 请帮助,我是编程的初学者,我尝试了一些不同的东西,但没有什么是真的有效。 any help will be really appreciated 任何帮助将非常感激

This would be an example of something i have tried (I tried this after reading a comment from this post): 这将是我尝试过的一个例子(我在阅读了这篇文章的评论后试过这个):

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

and i get errors like these: 我得到这样的错误:

9 errors found: 找到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

If you want to ask a user for input the most common way is to create an instance of the Scanner class with an argument of the System input like so 如果要询问用户输入,最常见的方法是使用System输入的参数创建Scanner类的实例,如此

Scanner userInput = new Scanner(System.in);

You can then call methods of this class that get the next line of text the user types, so your code may look something like this 然后,您可以调用此类的方法来获取用户键入的下一行文本,因此您的代码可能看起来像这样

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

This code allows a user to read and write from the terminal in command line or netbeans/eclipse. 此代码允许用户在命令行或netbeans / eclipse中从终端读取和写入。

For your compile errors : 对于您的编译错误:

Line 10 : public static void String getInputFileName() 第10行: public static void String getInputFileName()

Methods/funcitons must be declared inside of the body of a class. 方法/函数必须在类的主体内声明。 So move the entire function 所以移动整个功能

Immediately after your function you have an extra closing curly brace so remove that. 在您的功能之后,您有一个额外的闭合花括号,所以删除它。

You cannot declare public static void main(String[] args) twice. 你不能两次声明public static void main(String [] args)。 You especially cannot have a method inside of another so remove the outer public static void main(String[] args) { and the extra opening curly brace that follows. 你尤其不能在另一个方法中使用一个方法,所以删除外部的public static void main(String[] args) {以及public static void main(String[] args) {的额外开口花括号。

public static void String getInputFileName() can only have one return type so set it to void since you do not return. public static void String getInputFileName()只能有一个返回类型,因此请将其设置为void,因为您不返回。

Finally delete the extras closing curly brace at the end. 最后删除结尾处的大括号。

Your code should look something like this 你的代码应该是这样的

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

NOTE : This code will now compile, it does not mean that I made it do what you want it to do. 注意:此代码现在将编译,这并不意味着我按照您的要求执行此操作。

If you need to read the user's input, you can do it for example like this: 如果您需要阅读用户的输入,您可以这样做,例如:

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

    String input = s.nextLine();

In the input you will have the text, which user wrote. input您将获得用户编写的文本。

If you want to ask users to provide file names via typing them in the console, you can use either BufferedReader's readLine or Scanner's nextLine for this. 如果要通过在控制台中键入文件来要求用户提供文件名,可以使用BufferedReader的readLine或Scanner的nextLine。 The example for BufferedReader: 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();
    }

  }
}

Example for Scanner 扫描仪示例

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

Examples taken from this article 本文中获取的示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何要求用户输入和输出文件名? - how to ask user for output and input file names? 如何询问用户输入的文件名,然后使用该文件名? - How do I ask a user for a input file name, and then use that file name? 我希望让用户输入 .txt 文件名,如果文件名不存在,则重新提示用户。 这怎么可能? - I am wishing to ask the user to input a .txt file name, and re-prompt the user if the file name does not exist. How is this possible? 如果我要求用户输入一个文件,而该文件不存在,如何在程序不停止的情况下继续询问文件名? - If I am asking a user to input a file, and the file does not exist, how can I continue to ask for the file name without the program stopping? 请求文件名作为输入--Java - Request File Name as Input --Java 要求用户输入将要创建的文本文件名 - Ask the user to type in the text file name that's going to be created 从 linux 终端上的用户输入读取文件名 - JAVA - Read file name from user input on linux terminal - JAVA 使用用户输入的文件名创建Java编程来编写网页源代码 - Creating a java programming to webpage source code with user input file name 如何向用户询问文件名,然后扫描文件夹以查找特定类型,如果为true,则打开文件名,否则抛出错误 - How to ask a user for file name then scan folder for a specific type and if true open the filename if not then throw error Java:尝试创建文件输入程序。 但是,用户必须输入正确的文件名,否则无法打开 - Java: Trying to create a file input program. But, user must input correct file name or it wont open
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM