for loop not iterating through all increments - java

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.

Related

Need to get a line from a file onto queue and not the whole file text

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.

read from one file, modify and output to another file in java

The assignment is to read a file, create a new file that matches the input file but has numbers lines added
I have several examples to copy from. I have tried new File(), new FileReader() and BufferedReader(). I can't seem to get any data out of the input file
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Hw1_43 {
public static void main(String[] args) throws FileNotFoundException
{
// Prompt user for input file name
Scanner in = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputFileName = in.next(); // instantiate input file name for later use
Scanner inputFile = new Scanner(new FileReader(inputFileName));
//ArrayList<String> line = new ArrayList();
int counter = 0;
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
System.out.println(counter + line);
counter ++;
}
System.out.println(inputFileName);
}
}
Also after I get the input file to read and write it into an output file, where is the output file so I can look at it to make sure it is correct?
FileReader only reads from a file. You need to create a FileWriter, which writes to a file (e.g. FileWriter outputFile = new FileWriter ("C:/tmp/output_file.txt")). As you read from the FileWriter, prepend the line numbers to each line, then write to the FileWriter.
I recommend using BufferedReader instead of Scanner. You can then use then uses the .readLine() or .lines() methods, the latter can be streamed into a BufferedWriter.

The user must get out of while loop when he/she press enter in a new line. but it does not work and it keeps going to new lines

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");
}
}

Append text to the beginning of every line in a file

Please note, this is a homework assignment.
Can anybody help me figure out how to append text to the beginning of every line of a text file? This is what I have so far:
package addStr;
import java.util.*;
import java.io.*;
public class AddStr {
public static void main(String args[]) throws FileNotFoundException, IOException{
Scanner con = new Scanner(System.in);
System.out.print("Enter input file: ");
String fileIn = con.next();
System.out.print("Enter output file: ");
String fileOut = con.next();
File in = new File(fileIn);
Scanner sc = new Scanner(in);
FileWriter out = new FileWriter(in, true);
PrintWriter print = new PrintWriter(out);
print.print("hello");
print.close();
}
}
I only printed "hello" as a test to see where in the file it would append. It appends at the end of the very last line. I need it to append to the beginning of the first line, and then use a loop to append it to the beginning of each subsequent line.
Also, the program prompts the user to input the file name.
The simplest way to change the content of a file is to open it for reading, read it into a structure, re-open the file for writing then write from the structure back to file. Unless the file is large then the performance will be perfectly acceptable.
If you are using Java 8 then this can be quite trivial. Assuming you have a Path to the file:
List<String> lines = Files.lines(path).map(s -> "Prefix" + s).collect(Collectors.toList());
Files.write(path, lines);

Java scanner not starting from beginning of file

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.

Categories

Resources