I’m working on a Bruce Eckel exercise on how to take a keyboard command line input and put it into an array. It’s supposed to take 3 separate inputs and place them into an array and print them back out.
Here is the code I have so far:
//: object/PushtoArray import java.io.*; import java.util.*; class PushtoArray { public static void main(String[] args) { String[] s = new String[3]; int i = 0; //initialize console Console c = System.console(); while ( i <= 2 ) { //prompt entry: //System.out.println('Enter entry #' + i + ': '); //readin s[i] = c.readLine('enter entry #' + i + ': '); //increment counter i++; } //end while //reset counter i = 0; //print out array while ( i <= 2 ) { System.out.println(s[i]); i++; } //end while }//end main } //end class
UPDATE: Now I get a different error:
PushtoArray.java:15: readline(boolean) in java.io.Console cannot be applied to (java.lang.string) s[i]= c.readline('Enter entry #' + i + ': ');
I’m trying to read in from the command prompt but it isn’t prompting at all. It compiles correctly when I javac the java file.
Am I using the wrong function? Should I be using a push method instead of an assignment?
Are you sure you’re running
javacon the right file? There is no way that file could compile.You need a semicolon on the import statement:
You forgot an end brace:
There is no such method as
readline(). You need to read fromSystem.in. The easiest way is to make aScannerbefore the loop, then read from it in the loop. See the Javadocs forScannerfor an example.Edit: See the Java Tutorials for more on reading from the command line. The
Consoleclass (introduced in Java 6) looks like it has thereadLine()method that you wanted.Edit 2: You need to capitalize Line. You wrote ‘
readline‘, but it should be ‘readLine‘.