Scanner not actually taking in user input - java

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..

Related

Can not enter subscript via console (lost before System.in)

Problem
In short, if you try out the following snippet:
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter ₂
System.out.println(text); // 2, not ₂
and enter a subscript number, like ₂, text is actually 2, without subscript.
Tests
Now, I tried to factor out some classic reasons here.
Printing?
You can also compare the string instead of printing it, and it is still incorrect:
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter ₂
System.out.println(text.equals("₂")); // false
System.out.println(text.equals("2")); // true
Scanner?
Scanner is capable of doing it correctly, for example if the input is given as String:
Scanner scanner = new Scanner("₂");
String text = scanner.nextLine();
System.out.println(text); // now prints ₂
System.in?
The issue is still present if factoring out Scanner completely, for example:
byte[] data = System.in.readAllBytes(); // enter ₂
String text = new String(data, StandardCharsets.UTF_8).trim();
System.out.println(text); // 2, not ₂
Encoding?
It does not seem to be a general problem with Unicode/encoding. When entering another character, such as 🤔, it works as expected.
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // enter 🤔
System.out.println(text); // 🤔
Hypothesis
It seems that the subscript is lost between the console input and System.in, possibly even before reaching Java at all.
Maybe this is a console specific quirk I am not aware of? I tried it with VSC and Windows CMD (Java 18).

This code is supposed to get N values from the user. Then input then into a .txt file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This code is supposed to get N values from the user. Then input the values into a .txt file. I'm having trouble getting the values to show in the .txt file. Not sure why.
// This program writes data into a file.
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("namef.txt");
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
PrintWriter outputfile = new PrintWriter("/Users/******/Desktop/namef.txt");
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for ( int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
input.nextInt();
outputfile.print(N);
}
System.out.println("Data entered into the file.");
inputFile.close(); // Close the file.
}
} // End of class
In your program you seemed to have thrown everything and hoping that it works. To find out what class you should use you should search it in Javadoc of you Java version.
Javadoc of Java 12
PrintWriter:
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
FileWriter:
Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform's default charset.
Scanner (File source):
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
Now you can see what each class is for. Both PrintWriter and FileWriter are used to write file however PrintWriter offer more formatting options and Scanner(File source) is for reading files not writing files.
Since there is already an answer with PrintWriter. I am writing this using FileWriter.
public static void main(String[] args) throws Exception {
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
// You can provide file object or just file name either would work.
// If you are going for file name there is no need to create file object
FileWriter outputfile = new FileWriter("namef.txt");
System.out.print("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++) {
System.out.print("Enter the number into the file: ");
// Writing the value that nextInt() returned.
// Doc: Scans the next token of the input as an int.
outputfile.write(Integer.toString(input.nextInt()) + "\n");
}
System.out.println("Data entered into the file.");
input.close();
outputfile.close(); // Close the file.
}
Output:
Enter the number of data (N) you want to store in the file: 2
Enter 2 numbers below:
Enter the number into the file: 2
Enter the number into the file: 1
Data entered into the file.
File:
2
1
Here's a working variant of what you want to achieve:
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("path/to/your/file/namef.txt");
PrintWriter outputfile = new PrintWriter(fname);
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
int tmp = input.nextInt();
outputfile.print(tmp);
}
System.out.println("Data entered into the file.");
outputfile.close(); // Close the file.
}
}
Several comments on above:
1) Got rid of redundant rows:
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
You actually didn't use them at all.
2) In PrintWriter we pass File object, not String.
3) In for loop there was a logic mistake - on every iteration you should have written N instead of actual number which user entered on console.
4) Another mistake was in closing wrong file in the last line.
EDIT: adding according to comment.
in point 2) there's an alternative way - you can skip creating File object and pass as a String a path to even non-existing file directly in PrintWriter, like this:
PrintWriter outputfile = new PrintWriter("path/to/your/file/namef.txt");

Accept arbitrary multi-line input of String type and store it in a variable

Is there any possible way to accept a arbitrary(unknown) no. of input lines of string from the user until user explicitly enters -1 and store it in a string for further manipulation.
From what I gather, you're trying to get input from a user until that user types -1. If thats the case, please see my function below.
public static void main (String[] args)
{
// Scanner is used for I/O
Scanner input = new Scanner(System.in);
// Prompt user to enter text
System.out.println("Enter something ");
// Get input from scanner by using next()
String text = input.next();
// this variable is used to store all previous entries
String storage = "";
// While the user does not enter -1, keep receiving input
// Store user text into a running total variable (storage)
while (!text.equals("-1")) {
System.out.println("You entered: " + text);
text = input.next();
storage = storage + "\n" + text
}
}
I've left comments in that code block but I'll reiterate it here. First we declare our I/O object so that we can get input from the keyboard. We then ask the user to "Enter something" and wait for the user to enter something. This process is repeated in the while loop until the user specifically types -1.
Your question makes no sense... You're talking about taking input from a user, but also reaching the end of a file, implying you are taking reading input from a file. Which is it?
If you're trying to say that for each line in a file, the user must enter something for some action to be taken, then yes, that can be done.
I'll assume you already have a File object or String containing the file path, named file.
// make a stream for the file
BufferedReader fileReader = new BufferedReader(new FileReader(file));
// make a stream for the console
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
// declare a String to store the file input
String fileInput;
// use a StringBuilder to construct the user input lines
StringBuilder inputLines = new StringBuilder();
// while there is a line to be read
while ((fileInput = fileReader.readLine()) != null) {
/*
** maybe some output here to instruct the user?
*/
// get some input from the user
String userInput = consoleReader.readLine();
// if the user wants to stop
if (userInput.equals("-1")) {
// exit the loop
break;
}
// else append the input
inputLines.append(userInput+"\r\n");
}
// close your streams
fileReader.close();
consoleReader.close();
// perform your further manipulation
doSomething(inputLines.toString());
Those classes are located in java.io.*. Also, remember to catch or have your method throw IOException.
If you want to perform your manipulation each time you have some input instead of doing it all at the end, get rid of the StringBuilder, and move doSomething(userInput) into the loop before the if statement.

how to redo/avoid linebreak in console?

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.

How to determine the end of a line with a Scanner?

I have a scanner in my program that reads in parts of the file and formats them for HTML. When I am reading my file, I need to know how to make the scanner know that it is at the end of a line and start writing to the next line.
Here is the relevant part of my code, let me know if I left anything out :
//scanner object to read the input file
Scanner sc = new Scanner(file);
//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);
//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNext() == true)
{
String tempString = sc.next();
if (colorMap.containsKey(tempString) == true)
{
String word = tempString;
String color = colorMap.get(word);
String codeOut = colorize(word, color);
fWrite.write(codeOut + " ");
}
else
{
fWrite.write(tempString + " ");
}
}
//closes the files
reader.close();
fWrite.close();
sc.close();
I found out about sc.nextLine(), but I still don't know how to determine when I am at the end of a line.
If you want to use only Scanner, you need to create a temp string instantiate it to nextLine() of the grid of data (so it returns only the line it skipped) and a new Scanner object scanning the temp string. This way you're only using that line and hasNext() won't return a false positive (It isn't really a false positive because that's what it was meant to do, but in your situation it would technically be). You just keep nextLine()ing the first scanner and changing the temp string and the second scanner to scan each new line etc.
Lines are usually delimitted by \n or \r so if you need to check for it you can try doing it that way, though I'm not sure why you'd want to since you are already using nextLine() to read a whole line.
There is Scanner.hasNextLine() if you are worried about hasNext() not working for your specific case (not sure why it wouldn't though).
you can use the method hasNextLine to iterate the file line by line instead of word by word, then split the line by whitespaces and make your operations on the word
here is the same code using hasNextLine and split
//scanner object to read the input file
Scanner sc = new Scanner(file);
//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);
//get the line separator for the current platform
String newLine = System.getProperty("line.separator");
//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNextLine())
{
// split the line by whitespaces [ \t\n\x0B\f\r]
String[] words = sc.nextLine().split("\\s");
for(String word : words)
{
if (colorMap.containsKey(word))
{
String color = colorMap.get(word);
String codeOut = colorize(word, color);
fWrite.write(codeOut + " ");
}
else
{
fWrite.write(word + " ");
}
}
fWrite.write(newLine);
}
//closes the files
reader.close();
fWrite.close();
sc.close();
Wow I've been using java for 10 years and have never heard of scanner!
It appears to use white space delimiters by default so you can't tell when an end of line occurs.
Looks like you can change the delimiters of the scanner - see the example at Scanner Class:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

Categories