简体   繁体   中英

User input other than print prompt and scanner

I wrote a program that asks for user input like this:

System.out.println("Where would you like the output file to end up? (full path and desired file name): ");
Scanner out_loc = new Scanner(System.in);
output_loc = out_loc.nextLine();

...

System.out.println("Hey, please write the full path of input file number " + i + "! ");
System.out.println("For example: /home/Stephanie/filein.txt");
Scanner fIn = new Scanner(System.in);

I ask several times for input in this way but it can get to be a huge pain if you mistype because then you have to kill the program and rerun. Is there an easy way to just take input all at once when you run a program? As in just declaring it in the command line when having it run?

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?

You can use file redirection.

program < file

sends the file to the standard input of the program. In your case,

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere < file

Or you can read from a file in your program. You can make this optional like

InputStream in = args.length < 1 ? System.in : new FileInputStream(args[0]);
Scanner scan = new Scanner(in); // create the scanner just once!

When you run the command as :

java -jar /home/Stephanie/NetBeansProjects/cBelow/dist/cBelow.jar -userinputhere?

It runs the public static void main(String[] args) method of your primary class where you can get the userinputhere directly as:

  public static void main(String[] args)
     String userinputhere = args[0];
     ..... rest of your code
   }

If there are multiple user Inputs, you can get them all as :

  public static void main(String[] args)
      String userinput1 = args[0];
      String userinput2 = args[1];
      String userinput3 = args[2];
      //and so on..
      ..... rest of your code
  }

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