Line by line input via java console - java

Please help me to input by line by line via java console. Now i can give input only as one line. How to give multiple inputs in line by line??

InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String CurLine = ""; // Line read from standard in
while (!(CurLine.equals("quit"))){
CurLine = in.readLine();
if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}

You need to use Scanner and loop through to ask for multiple times.
For example
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
//Get input and do your logic.
}

I'm not sure I understand your question but...
final List<String> inputs = new ArrayList<String>();
final Scanner in = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("> ");
inputs.add(in.next());
}
System.out.println(inputs);

Use the new Console class:
Console console = System.console();
if (console != null) {
Scanner scanner = new Scanner(console.reader());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Do something with your line
}
}
End the input by pressing ^Z (control-Z) followed by ENTER.
It has one caveat and that is that the console can be null inside an IDE. Try it from the command-line and you should be fine:
java path.to.my.MainClass

Related

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

How to take input from console in java separated by comma and '\n'?

I want to take input from the console which is separated by the comma and next line. For eg. input is like as follow:
1,2(next line)1,2,3(next line)2,4,6 here next line means that the next input starts from next line.
I had tried it but there are many complications, I had tried it as:
Scanner sc = new Scanner(System.in);
String line;
String[] lineVector;
line = sc.nextLine();
System.out.print(line);
lineVector = (line.split('\n') || line.split(","));
int ii=2;
int m=Integer.parseInt(lineVector[0]);
int n=Integer.parseInt(lineVector[1]);
int z = n;
int[][] chuteArray = new int[m][n];
for(int i = 0;i < m;i++){
for(int j = 0;j <n;j++){
chuteArray[i][j] = Integer.parseInt(lineVector[ii]);
ii++;
}
}
But,its not working out.
You can use scanner.useDelimiter("([,\\n])");
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("([,\\n])");
while (scanner.hasNext()) {
System.out.println(scanner.nextInt());
}
For the input 1,2\n1,2,3\n2,4,6 this code prints
1
2
1
2
3
2
4
6
PrintStream stream = new PrintStream(new FileOutputStream("console.log", true));
System.setOut(stream);
This code changes the system console output to a file named console.log for example.

How can I read a file from the command line using scanner

It wont prompt the user to enter file? Please help me
public static void main (String args []){
if (0 < args.length) {
File inFile = new File(args[0]); // Make sure the file exists, can read, etc...
while (!inFile.exists()) {
Scanner console = new Scanner (inFile);
System.out.println ("Input file:"); //prompt user to input file
String inFileName = console.nextLine();
System.out.println ("Input file:"); //prompt user to input file
inFileName =inFileName.trim(); //get rid of whitespace
System.out.println(inFileName);
inFile = new File (inFileName);
}
The old way :
BufferedReader reader = new BufferedReader( new InputStreamReader( System.in)); String userInput = reader.readLine();
The new way :
Console console = System.console();
if( console != null) { String userInput = console.readLine();
For Scanner you need to use.
Scanner console = new Scanner(System.in);
I suppose you can do the expected task with few lines of code.
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Input file : ");
String inFile = userInput.next();
System.out.println("Input file is " + inFile);
}

Line/Token based processing (java)

I'm writing a program to read data from files with various sports statistics. Each line has information about a particular game, in say, basketball. If a particular line contains an "#" symbol, it means that one of the teams is playing at home. I'm trying to count the lines that contain an "#" and output that to the user as the Number of Games in which either team played at home. The first file has that 9 games were played at home for some team, but my output keeps printing out 0 rather than 9. How can I fix this?
Here's the relevant code:
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
input1.nextLine();
} else{
input1.nextLine();
}
}
System.out.println("Number of games with a home team: " + count);
}
Your line variable always has the first line's value. You should set line in the loop, something like that.
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
line = input1.nextLine();
} else{
line = input1.nextLine();
}
Edit: On the second look your code has other problem: the last line is never checked. You should not initialize line (set to null) and do the check after nextLine():
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = null;
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
line = input1.nextLine();
if(line.contains("#")){
count++;
}
}
System.out.println("Number of games with a home team: " + count);}

java scanner to detect 3 words on line

I am trying to write a little program that will use scanner to check if there is a next line (in awhile loop) and then maybe another one to check that the words on the line are tab appart and there are 3 strings (the use constructor to create a object) so the three strings would be Product Name Manufacturer Brcode
EG: Tyre17x60 Goodyear 458765464
and so and so
I am bit stuck with this so any help would be grateful
You can try this:
public static void main (String[] args) throws java.lang.Exception
{
String str = "Tyre17x60 Goodyear 458765464";
InputStream is = new ByteArrayInputStream(str.getBytes());
Scanner sc = new Scanner(is);
sc.useDelimiter("\n");
while (sc.hasNext())
{
String[] tmp = sc.next().split("\t");
if (tmp.length == 3)
System.out.println("Text contains 3 parts separated with tabs");
else
System.out.println("Text is not well formated");
// save data
//productName = tmp[0];
//manufacturer = tmp[1];
//brcode = tmp[2];
}
}
Assuming you are reading from a file, you can use the following code:
Scanner s = new Scanner(new File("file.txt"));
while(s.hasNext())
{
String productName = s.next();
String Manufacturer = s.next();
String Brcode = s.next();
}
Scanner scan = new Scanner("file.txt");
while(scan.hasNext()){
scan.nextLine();
System.out.println("Product : " + scan.next());
System.out.println("Name : " + scan.next());
System.out.println("Code : " + scan.nextLong());
}
Try something like this....

Categories

Resources