First of all this is not a duplicate of other posts, because in my problem the scanner class does not recognize the beginning of the .txt file not the end, instead it starts approximately 1/2 way through the file.
Here is my code:
package Program;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws FileNotFoundException {
String filename = "C:\\Users\\vroy\\Programming\\Text documents\\P&P.txt";
File textFile = new File(filename);
Scanner reader = new Scanner(textFile);
// int value = reader.nextInt();
// System.out.println(value);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
}
}
Here is the .txt document that my program is reading:
http://www.goodreads.com/ebooks/download/1885.Pride_and_Prejudice?doc=2
My program starts printing out lines of text starting at: "with the ill-judged officiousness..."
It should start much further up the document.
Is this a problem with the scanner class?
Is this a problem with the scanner class?
Nope.
I just tested your code. The answer is pretty funny actually - I assume you are running this code in an IDE such as Eclipse. System.out.println() prints to the "Console". The console has a maximum number of lines it shows, and as your file is very long, it doesn't show the start.
It IS looping through all the lines. To prove this, make it increment a digit whenever it prints a line such as:
int counter = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
counter++;
}
You will see that counter is exactly the number of lines in the document.
Related
I'm having trouble properly getting one line of text at a time from a file onto a queue without taking the whole file into the queue. For example, I'd like only Write a program that reads a Java source file as an argument and produces an index of all identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity, we will consider each string consisting only of letters, numbers, and underscores an identifier.
Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+") Then each call to next returns an identifier.
public class Main { to get added to the queue but instead the whole file text is put into the queue instead of a line at a time. Sorry if my question is unclear
// Write a program that reads a Java source file as an argument and produces an index of all
// identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity,
// we will consider each string consisting only of letters, numbers, and underscores an identifier.
// Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+").
// Then each call to next returns an identifier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class E_15 {
public static void main(String[] args) throws FileNotFoundException
{
// get scanner input from file
Scanner fileInput = new Scanner(new File ("C:/Users/ramir/IdeaProjects/PA_7/src/Main.java"));
Queue<String> test = new LinkedList<String>();
ArrayList<String> phrase = new ArrayList<String>();
/*
List<String> result = new ArrayList<String>();
Scanner s = new Scanner(is);
s.useDelimiter(delimiter);
*/
// Iterates till end of file
while (fileInput.hasNextLine())
{
// Here is the issue. Data will end up
// containing the whole file instead of only that line
String data = fileInput.nextLine();
Scanner in = new Scanner(data);
in.useDelimiter("[^A-Za-z0-9_]+");
// I believe around here or before is the issue that I'm having.
// It adds all the file instead of only that line
// Also trying to figure out how to display each line that it's displayed on
// What the first one should look like for example
// 0: public occurs in:
// public class Main {
// public static void main(String[] args) {
//System.out.println(data);
test.add(data);
while(in.hasNext())
{
// Getting each phrase/word into ArrayList
String token = in.next();
phrase.add(token);
}
in.close();
}
int index = 0;
// This part works fine
for(String num : phrase)
{
// printing the key
System.out.println(index + ": " + num + " occurs in:");
// printing the values
// This to print out what
for(String line : test)
{
System.out.println(line);
}
System.out.println();
++index;
}
}
}
// Just java class get file front
// This is fine
public class Main {
public static void main(String[] args) {
int a_1 = 100;
System.out.println(a_1);``
}
}
I'd like it to only show System.out.println(a_1) because the line that's it's on See This
. I'm also have trouble printing it in all the lines that occur.
import java.io.*;
import java.util.Scanner;
public class ReadLineByLineExample2
{
public static void main(String args[])
{
try
{
//the file to be opened for reading
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
while(sc.hasNextLine())
{
System.out.println(sc.nextLine()); //returns the line that was skipped
}
sc.close(); //closes the scanner
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Try studying the above code. I hope it will help. Otherwise, you might need to open this link for more detail.
I need to do the following exercise:
a) Make a new text file
b) Put the user's input into that text file
c) we must save all user's input while user keeps typing but as soon as user pressing Enter in a new line (When an empty string is sent) the user must get out of the program.
For coding this issue I have write the following codes, but when
I try it by myself so I am stuck at while loop, cant get out when I sending empty string.
So could anyone help with a solution for this issue?
Thanks
I have tried some of the solutions I have found on youtube like making if statement inside the while loop or adding the code that takes the input of the user inside the loop's condition.
So I do not know what to do at the next stage.
I tried to see the console window via the Eclipse output.
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
while (true) {
Scanner input = new Scanner(System.in);
str = input.next();
pw.println();
if (str.equals(null)) {
break;
}
}
pw.close();
System.out.println("Done");
}
}
The user must get out of the loop when he/she sends an empty string. and the writing to the file must be finished.
First the code, then the explanation...
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lesson {
public static void main(String[] args) {
File file = new File("mytext.txt");
try (Scanner input = new Scanner(System.in);
PrintWriter pw = new PrintWriter(file)) {
System.out.println("Enter a text here: ");
String str = input.nextLine();
while (str.length() > 0) {
pw.println(str);
pw.flush();
str = input.nextLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
System.out.println("Done");
}
}
The above code requires at least Java 7 since it uses try-with-resources. Scanner should be closed, just like PrintWriter should be closed. The try-with-resources ensures that they are closed. Note that if file mytext.txt doesn't exist, creating a new PrintWriter will also create the file and if the file already exists, its contents will be removed and replaced with the text that you enter.
After that the prompt is displayed, i.e. Enter a text here, and the user enters a line of text. Method nextLine() will get all the text entered until the user presses Enter. I read your question again and the program should exit when the user presses Enter without typing any text. When the user does this, str is an empty string, i.e. it has zero length. That means I need to assign a value to str before the while loop, hence the first call to method nextLine() before the while loop.
Inside the while loop I write the value entered by the user to the file mytext.txt and then wait for the user to enter another line of text. If the user presses Enter without typing any text, str will have zero length and the while loop will exit.
Written and tested using JDK 12 on Windows 10 using Eclipse for Java Developers, version 2019-03.
To achieve this, we check is length of input is >0:
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
Scanner input = new Scanner(System.in);
while ((str = input.nextLine()).length() > 0) {
//str = input.next();
pw.println(str);
}
pw.close();
System.out.println("Done");
}
}
I've created a basic notepad text file (e.g., text-file.txt) and have tried placing this file in multiple file paths for my code to retrieve, but I can't seem to get this to work. Basically, I'm wanting to take the content of text-file.txt and create a second file where everything is in all caps.
Here is my code:
package abc123;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class abc123
{
public static void main (String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Please provide the name of your input file: ");
String inFileName = in.nextLine();
System.out.print("Please indicate what you'd like to name your output file: ");
String outFileName = in.nextLine();
FileReader reader = new FileReader(inFileName);
PrintWriter writer = new PrintWriter(outFileName);
Scanner fileReader = new Scanner(reader);
while(fileReader.hasNext())
{
String line = fileReader.nextLine();
line = line.toUpperCase();
writer.println(line);
}
fileReader.close();
writer.close();
System.out.println("The process is now complete. Please check your output file. Thank you.");
}
}
I'm a Java newbie, so a simple solution (and comments, as always) that I can grasp at this point would be super helpful. Thanks!
if the file isn't in the same folder as your java class, you have to give java full-path to find the file. be sure you also type the extension of the file, like ".txt".
I am having trouble finding an efficient way to pick out specific data from a text file in this format, with numerous lines.
<"Name" "double" "double" "double" [...]>
The amount of doubles varies on every line of the txt file,
I am only interested to pick out the first double of every line in the txt file.
The way I am trying to do it is with:
Scanner doubleScan = new Scanner(System.in).useDelimiter("(\\w)(\\s+)");
String[] columnOne = elementScan.next().split(" ");
Trying to make the scanner expect with regex but does not really work if unknown amount of doubles in a line. Then trying to store all the picked out (1st of every line) doubles in an array
Would appreciate any suggestions, with Scanner only.
You can use scanner.nextLine() to read line by line and then use plit method and take second element from the array. Alternatively if you are so partcular about using only scanners you can create another scanner for each line and check for double using nextDouble() method. Example.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
try {
File file = new File("test.txt");
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNext()) {
Scanner lineScanner = new Scanner(fileScanner.nextLine());
while (lineScanner.hasNext()) {
if (lineScanner.hasNextDouble()) {
System.out.println("First Double :" + lineScanner.nextDouble());
break;
} else {
lineScanner.next();
}
}
lineScanner.close();
}
fileScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I'm writing a program for a lab task at uni, the code will make is fairly obvious what is does, but when it asks for the first line, ie number one 1 in the loop, and you insert a string and hit enter, it automatically jumps straight to the last increment in the loop (5) any ideas?
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class limmerickWriter {
public static void main(String[] args)throws Exception {
Scanner limScan = new Scanner(System.in); //scanner to read user input
System.out.println("please enter the name of the file");
String fileName;
fileName = limScan.next(); //filename for the text file
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); //declaring a new file writer
for (int i = 1; i <= 5; i++) //loop to get 5 seperate lines from the user
{
System.out.println("please enter line " + i );
out.println(limScan.next()); //writes the contents of the scanner to the file
}
out.flush();
out.close();
}
}
While reading with scanner.next() white space gets used as default delimiter. Which means that if your file name is inserted with several words separated by spaces,they will be read with continuous next() call first.
For example, while reading the filename using scanner.next(), if you insert:
test ATest BTest CTest DTest ETest
And hit Enter, you will see that a file with name test gets created in your relevant class path, containing text data ATest BTest CTest DTest ETest.
Try using nextLine() instead inside the for loop.