Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Can you give a new Scanner object something other than System.in?

+15 votes
Whenever I make a Scanner, the command always looks like this:

Scanner console = new Scanner(System.in);

but is there anything else that could go in the parenthesis?  Could the Scanner take in information from things other than the console?
asked Dec 16, 2015 in (Winter 15-16) by Gabriel Lance (100 points)

2 Answers

+3 votes

Yes, you can also use a scanner to read data from text files, as we'll learn about in Chapter 6...

You can also use a Scanner to parse a String directly... e.g.

String data = "15   22.5  35";
Scanner inputSource = new Scanner(data);
int firstNum = inputSource.nextInt();
double secondNum = inputSource.nextDouble();
answered Jan 4, 2016 by Forrest Stonedahl (100 points)
+1 vote
From what we know so far, I'm going to say no. However, I'm sure that we will learn more ways that we can do this that involve combining the .next methods with the Scanner command.
answered Dec 17, 2015 by Ryan McCarthy (100 points)