0

Heres my basic goal: Convert a program that uses a Scanner and the keyboard as input into a program that uses the Scanner and java args as input. This will be done programatically for a variety of programs, so I'd like to make as few and as small changes to the actual program itself. I'm able to do this by changing Scanner scanner = new Scanner(System.in); into Scanner scanner = new Scanner(args[0]);.

Now I can seperate each argument with a space in args[0] and the program runs fine, but ONLY if it doesn't use scanner.nextLine(). As soon as scanner.nextLine() is used, the scanner munches up the entire String and breaks the program.

I can't figure out a workaround without changing the program structure all together (Removing all the scanner.nextLine()s. Is there maybe some sort of character/sequence that will stop scanner.nextLine(), or will it always process the entire String?

Thanks

Edit: My initial idea was to give the scanner a String array and have it go through that, index by index, regardless of which method was used (next, nextInt, nextLine). Is that perhaps possible?

1 Answer 1

2
  1. Look at Apache Commons CLI, it would almost certainly be better than trying to "convert" (kludge) a program that is currently using Scanner.

  2. You can just insert newlines in the command line arguments if you really need to.

    public static void main( String[] args ) { StringBuilder cla = new StringBuilder(); for( String command : args ) { cla.append( command ); cla.append( '\n' ); // newline } String finalCommand = cla.toString(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

I'm actually basically finished the project, I just have this bug and then some GUI and finalizing stuff. If #2 works, I'll use that. Otherwise I'll redesign and attempt #1. The \n idea should work well, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.