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);
Related
So, I am creating a program in which the user has to enter the body(message) of the email. Now when I display that instead of doing it in a proper way the compiler just displays a long line. I have tried using \n but it doesn't work.
System.out.println("Enter message");
Scanner e4 = new Scanner(System.in);
String message = e4.nextLine();
System.out.println(message);
I have a solution for you. You can keep pushing line after line onto an ArrayList until you see a particular end string. In my example it's "end", but equally it could be "</p>" or something else.
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Scan {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter here:");
List<String> input = new ArrayList<String>();
while(true) {
String temp = in.nextLine();
if(temp.equals("end"))
break;
input.add(temp);
}
for(String s : input) {
System.out.println(s);
}
}
}
I am creating a CSV parser library in Java. I have the following code so far:
However I keep getting the error when I try to include user input to the ("Enter a delimiter") part:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at demo.CSV.main(CSV.java:19)
Also can you please help me figure out how I would create a test application that can use the library.
Thank you.
package demo;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CSV {
public static void main(String[] args) throws FileNotFoundException {
Scanner x = new Scanner(System.in);
System.out.println("Enter the File");
String s = x.next();
x.close();
Scanner scanner = new Scanner(new File(s));
scanner.useDelimiter(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
System.out.println("Enter delimiter");
Scanner scanner1 = new Scanner(System.in);
String format = scanner1.nextLine();
while(scanner.hasNext()){
System.out.println(scanner.next()+format);
}
scanner.close();
}
}
The problem boils down to the fact that you're not using Scanner.nextLine() properly, compounded by the fact that your input file is empty.
When you use nextLine(), you need to enclose it within a loop that checks to see if an input source has a next line using hasNextLine() before trying to read the line with nextLine().
Your code assumes that there's a next line without first checking. Meanwhile, your input file is empty, so you get NoSuchElementException.
Instead of going in blind like this:
String format = scanner1.nextLine();
Replace that line with this:
String format = null;
while(scanner1.hasNext())
{
format = scanner1.nextLine();
}
Then make sure you generate an input file that actually has one or more lines in it.
I Have a simple program where I just prompt to enter an item and the while loop will continue to ask until I enter the word "end" then it will end the program. When I enter a word like so:
it looks fine, But when I enter 2 words for an item as such I get this output:
notice how when i entered "green yellow" It prompted me after that to enter an item twice?
I can't figure out why it is doing so?
import java.util.Scanner;
public class ToDoListapp {
public static void main(String[] args) /*throws IOException*/ {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Welome to your TodoList");
boolean keepAdd = true;
String item;
//file
//PrintWriter writeFile = new PrintWriter("TodoList.txt", "UTF-8");
// File file = new File("ToDo.txt");
// BufferedWriter writeTo = new BufferedWriter(new FileWriter(file));
while (keepAdd)
{
System.out.println("Enter an item: ");
item = sc.next();
if (item.equals("end"))
{
keepAdd = false;
}
// writeTo.write(item + "\n");
}
//writeTo.close();
}
}
The default behavior of Scanner is to use whitespace as a delimiter which will be used to break input into tokens. If you just want to use the newline character as a delimiter, try to set the delimiter explicitly.
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
System.out.println("Welome to your TodoList");
boolean keepAdd = true;
String item;
// The rest of your code
see http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html.
By default it uses any whitespace as the delimiter. So, the call to sc.next() already has its answer with the input green yellow.
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.
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();