简体   繁体   中英

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. These methods will be called from the main method. They will return a String so there should be two String variables declared before the methods are called.

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:

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

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.

For your compile errors :

Line 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. 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 String getInputFileName() can only have one return type so set it to void since you do not return.

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.

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. The example for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM