how to redo/avoid linebreak in console? - java

I would like to redo a line break in the console.
For example if I use:
reader.readLine();
and the user enters some input and returns
then the cursor is in a new line.
| ... cursor
: input
[enter]
: |
I would like to read the input but stay in the
same line and if the user again presses enter
a new line occurs.
: input [enter] |
How would I achieve that ?

Take a look at the Scanner class:
import java.util.Scanner;
class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a some input: ");
String userInput = scanner.nextLine();
System.out.println("Received input: " + userInput);
}
}
Side note from personal experience, do not declare the scanner in a try-with-resources block if you intend on using the System.in stream again, as it will close the stream without any means of reopening the stream without restarting the process.

Related

I tried the java language using netbeans 12 with jdk version 8, but it always got an error in the output [duplicate]

I am trying to use Console class to get input from user but a null object is returned when I call System.console(). Do I have to change anything before using System.console?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
Using Console to read input (usable only outside of an IDE):
System.out.print("Enter something:");
String input = System.console().readLine();
Another way (works everywhere):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console() returns null in an IDE.
So if you really need to use System.console(), read this solution from McDowell.
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.
It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.
From the command line, it should be fine though. Sample:
import java.io.Console;
public class Test {
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.out.println("Unable to fetch console");
return;
}
String line = console.readLine();
console.printf("I saw this line: %s", line);
}
}
Run this just with java:
> javac Test.java
> java Test
Foo <---- entered by the user
I saw this line: Foo <---- program output
Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).
Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:
import java.util.Scanner;
String data;
Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();
scanInput.close();
System.out.println(data);
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LoopingConsoleInputExample {
public static final String EXIT_COMMAND = "exit";
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
while (true) {
System.out.print("> ");
String input = br.readLine();
System.out.println(input);
if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
System.out.println("Exiting.");
return;
}
System.out.println("...response goes here...");
}
}
}
Example output:
Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.
I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.
It introduces an abstraction layer similar to the one proposed by McDowell.
If System.console() returns null, the library switches to a Swing-based console.
In addition, Text-IO has a series of useful features:
supports reading values with various data types.
allows masking the input when reading sensitive data.
allows selecting a value from a list.
allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).
Usage example:
TextIO textIO = TextIoFactory.getTextIO();
String user = textIO.newStringInputReader()
.withDefaultValue("admin")
.read("Username");
String password = textIO.newStringInputReader()
.withMinLength(6)
.withInputMasking(true)
.read("Password");
int age = textIO.newIntInputReader()
.withMinVal(13)
.read("Age");
Month month = textIO.newEnumInputReader(Month.class)
.read("What month were you born in?");
textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
"was born in " + month + " and has the password " + password + ".");
In this image you can see the above code running in a Swing-based console.
Use System.in
http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html

same input calling two different methods in java

I'm trying to implement the main method in java for a KWIC. The issue I'm having is that I have to ask the user if they want to write the input from the console/file and write the output to the console/file. The first time asking the user for console/file works fine when I have to read, but when I ask them again for the output I believe it goes back into the first If condition. Here is the code for reference.
try {
System.out.println("Please enter FILE to input from file or CONSOLE to input from console:");
String userInput = "";
while ((userInput = scannerWrapper.nextLine()) != "-1") {
if (userInput.equals("CONSOLE")) {
System.out.println("Please enter FILE to output from file or CONSOLE to output from console:");
List<String> cshiftConsole = circularShifter.shiftLines(inputFromConsole.read());
if (userInput.equals("CONSOLE")) {
System.out.println("Please enter lines to add, then enter -1 to finish:");
// Console
cshiftConsole = alphabetizer.sort(cshiftConsole);
outputToConsole.write(cshiftConsole);
for (String element : cshiftConsole) {
System.out.println(element);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
This is my console output
Please enter FILE to input from file or CONSOLE to input from console:
CONSOLE
Please enter FILE to output from file or CONSOLE to output from console:
CONSOLE
Software Architecture
-1
Please enter lines to add, then enter -1 to finish:
Architecture Software
CONSOLE
Software Architecture
After the second CONSOLE(userInput) I should be asked to enter the lines, But this is taking CONSOLE as the input I want to circularly shift. Any help would be great thank you.
You have some issues in your code, and if I understand correctly you want to decide where to INPUT from, where to OUTPUT to and get a couple of Strings into a List.
(userInput = scannerWrapper.nextLine()) != "-1" You compare Strings in Java using .equals(...) as you did in your code further below.
Every time you're asking your user where he wants to input from, you just have to read it once, so instead of having it inside a while do it on an if.
You create your list on every iteration, have it as an instance member instead.
On every iteration you're printing your objects, wait until the user stops adding items first (they type -1)
A better approach could be like this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class InputCycle {
private Scanner scanner;
private static final String CONSOLE = "CONSOLE";
private static final String EXIT_CODE = "-1";
private List<String> list;
public static void main(String[] args) {
new InputCycle().readAndWrite();
}
private void readAndWrite() {
scanner = new Scanner(System.in);
list = new ArrayList<String>();
System.out.println("INPUT FROM CONSOLE / FILE");
String input = scanner.nextLine(); // Read where to input from
if (input.equals(CONSOLE)) {
System.out.println("OUTPUT TO CONSOLE / FILE");
String output = scanner.nextLine(); // Read where to output to
if (output.equals(CONSOLE)) {
System.out.println("WRITE LINES (" + EXIT_CODE + " TO EXIT)");
String line = "";
do {
line = scanner.nextLine(); // Read every line
if (!line.equals(EXIT_CODE)) {
list.add(line);
}
} while (!line.equals(EXIT_CODE));
} else { // Write to a file with your own code
System.out.println("Writing to a file");
}
} else { //Read from a file
System.out.println("Reading from a file");
}
System.out.println("ALL LINES: ");
list.forEach(line -> System.out.println(line)); //Print all the lines user wrote
}
}
That has this output:
INPUT FROM CONSOLE / FILE
CONSOLE
OUTPUT TO CONSOLE / FILE
CONSOLE
WRITE LINES (-1 TO EXIT)
FOO
BAR
BANANA
-1
ALL LINES:
FOO
BAR
BANANA

Scanner not actually taking in user input

I've tried different uses for Scanners (I want it to read in Files but I also tried just Strings), and it just skips over the code as if it doesn't exist. No error messages are shown.
public static void main(String[] args)
throws FileNotFoundException {
Scanner test = new Scanner(System.in);
String testLine = test.next();
Scanner input = new Scanner(new File("data.txt"));
while(input.hasNextLine){
String name = input.nextLine();
String letters = input.nextLine();
System.out.println(name + ": " + letters);
}
}
Your code doesn't compile, because hasNextLine() is a function, not a class member.
You are actually reading from System.in at test.next(); - you have to enter some text, then your code will continue to run. It's just waiting for a user input - thus no exception is thrown.
At this line of code:
String testLine = test.next();
your program is waiting for your input. It cannot proceed to next line till you provide an input.
EDIT:
Taking cue from Charlie's comment below, here is a quote about System.in from docs.
The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
More here..

Does Scanner suppress linefeed characters (i.e. \n)? [duplicate]

This question already has answers here:
How to make Scanner Properly Read Escape Characters?
(3 answers)
Closed 7 years ago.
I've noticed how Scanner ignores the linefeed characters like \n for new line or \" for in-string double-quotes, it seemed kinda necessary to work, so I'm wondering if there is something that I'm doing wrong, or Scanner does, indeed, ignore linefeed?
Here is the code example, where the commented String text = "This \n Must \n Work!!" has linefeed working and would output
ThisMustWork!!
But, if we were to use the String text = sc.nextLine(); and type "This \n Wont \n Work" it wouldn't create a new line but would just output
This \n Wont \n Work
to test.txt
Code Example:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class StoringTheString {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.println("Type anything: ");
String text = sc.nextLine();
// String text = "This \n Must \n Work!!!" ;
sc.close();
PrintWriter out = new PrintWriter("test.txt");
out.println(text);
out.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I'm sorry if I wasn't clear in my post, please comment if there are some misunderstandings and I'll try to elaborate.Thanks for your time ^...^
Try using a scanner to get the input from the keyboard, then use another scanner to break the input into separate lines.
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type anything: ");
String text = keyboard.nextLine();
Scanner scanner = new Scanner(text);
// This is what will break the line apart
scanner.useDelimiter("\\s?\\\\n\\s?");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
}
Results:
Type anything: This \n Must \n Work!!!
This
Must
Work!!!
Try this:
String text = "This "+ "\r\n"+ "Must"+ "\r\n"+ "Work!!!" +"\r\n";
if doesn't work,change out.println(text); to out.print(text);

Is a scan line escaping?

I've been doing a small project for class, it runs perfectly without problems but when pitted against the class's auto testers it gives back 2 No line found errors. Asking the course's staff they say it's probably because I'm trying to scan a line when none exist, but I tried printing all my scans and didn't discover anything like that.
That's all the scans I have in my code:
Scanner sc = new Scanner(System.in);
String sentence;
int choice;
System.out.println("Please enter a sentence:");
sentence = sc.nextLine();
printMenu(); // calls a function to print the menu.
// gets the require action
System.out.println("Choose option to execute:");
choice = sc.nextInt();
sc.nextLine();
(I tried with and without the last sc.nextLine)
static void replaceStr(String str)
{
String oldWord, newWord;
Scanner in = new Scanner(System.in);
// get the strings
System.out.println("String to replace: ");
oldWord = in.nextLine();
System.out.println("New String: ");
newWord = in.nextLine();
// replace
str = str.replace(oldWord, newWord);
System.out.println("The result is: " + str);
in.close();
}
static void removeNextChars(String str)
{
Scanner in = new Scanner(System.in);
String remStr; // to store the string to replace
String tmpStr = ""; //the string we are going to change.
int i; // to store the location of indexStr
// gets the index
System.out.println("Enter a string: ");
remStr = in.nextLine();
i=str.indexOf(remStr);
in.close(); // bye bye
if (i < 0)
{
System.out.println("The result is: "+str);
return;
}
// Build the new string without the unwanted chars.
/* code that builds new string */
str = tmpStr;
System.out.println("The result is: "+str);
}
Any idea how a line can leak here?
Here is the problem. You are using in.close(); at multiple places(last statement in replaceStr method and around the middle in removeNextChars method). When you close the scnaner using close() method, it closes your InputStream (System.in) as well. That InputStream can't be reopened with-in your program.
public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**
Any read attempts after the scanner close will result into exception NoSuchElementException.
Please close your scanner only once, when your program is done.
EDIT: Scanner Closing/usage:
In yout main function:
Scanner sc = new Scanner(System.in);
....
.....
replaceStr(Scanner sc, String str);
.....
....
removeNextChars(Scanner sc ,String str);
....
....
//In the end
sc.close();
static void replaceStr(Scanner in, String str){
//All the code without scanner instantiation and closing
...
}
static void removeNextChars(Scanner in, String str){
//All the code without scanner instantiation and closing
...
}
You should be all good.

Categories