How to read from a text file and move onto next line - java

I am making a program that will scan a text file to find all the ints, and then print them out, and move onto the next line
Ive tried turning if statements into while loops to try to improve, but my code runs through the text file, writes out all the numbers, but fails at the end where it runs into a java.util.NoSuchElementException. If I have a text file with the numbers
1 2 3
fifty 5,
then it prints out
1
2
3
5
But it crashes right at the end everytime
import java.util.Scanner;
import java.io.*;
public class filterSort
{
public static void main()
{
container();
}
public static void run()
{
}
public static void container()
{ Scanner console = new Scanner(System.in);
int count = 0;
int temp;
try
{
System.out.print("Please enter a file name: ");
String fileName = console.nextLine();
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
while(file.hasNextInt())
{
temp = file.nextInt();
System.out.println(temp);
}
file.next();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
}
}

Replace
file.next();
with
if(file.hasNextLine())
file.nextLine();
Every time you try to advance on a scanner, you must check if it has the token.

Below is the program which is working for me . Also it is good practice to close all the resources once done and class name should be camel case. It's all good practice and standards
package com.ros.employees;
import java.util.Scanner;
import java.io.*;
public class FileTest
{
public static void main(String[] args) {
container();
}
public static void container()
{ Scanner console = new Scanner(System.in);
int count = 0;
int temp;
try
{
System.out.print("Please enter a file name: ");
String fileName = console.nextLine();
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
while(file.hasNextInt())
{
temp = file.nextInt();
System.out.println(temp);
}
if(file.hasNextLine())
file.next();
}
file.close();
console.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
}
}

Related

I need help reading a text file to print to the console

I having trouble figuring this out it supposed to print the contents of the txt file but i cant get it print.
This is the output im supposed to get.
Ingredient __________Amount Needed ______ Amount In Stock
baking soda_________4.50 ________________4.00
sugar ______________6.50________________3.20
import java.util.Scanner;
import java.lang.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.*;
public class Lab8b {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter file name : ");
String filename = scan.nextLine();
Scanner fileScan = new Scanner(new File(filename));
while (fileScan.hasNext()) {
String name = fileScan.nextLine();
String ingredientName = fileScan.nextLine();
double amountNeeded = Double.parseDouble(fileScan.nextLine());
double amountInStock = Double.parseDouble(fileScan.nextLine());
if (amountNeeded > amountInStock) {
System.out.printf("Ingredient \t Amount Needed \t Amount in Stock");
System.out.println();
System.out.printf("%10s", ingredientName);
System.out.printf("%8.2f", amountNeeded);
System.out.printf("%16.2f", amountInStock);
} //end if
if (amountNeeded <= amountInStock) {
System.out.println("Nothing");
} //end while
} //end if
} //end main
} //end class
Here are the problems I found with your code:
You created a while loop to read the contents of the file, but you don't do anything with it.
Need to wrap the code in a try-catch since FileNotFoundException might be thrown.
You attempt to call readLine() from filename instead of fileScan
I've assumed that you need amountNeeded and amountInStock to be doubles even though you don't do any calculations with them. If this isn't the case, you can simply leave them as strings instead of parsing.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter file name : ");
String filename = scan.nextLine();
scan.close();
Scanner fileScan = null;
try {
fileScan = new Scanner(new File(filename));
while (fileScan.hasNext()) {
String ingredientName = fileScan.nextLine();
double amountNeeded = Double.parseDouble(fileScan.nextLine());
double amountInStock = Double.parseDouble(fileScan.nextLine());
System.out.printf("Ingredient \t Amount Needed \t Amount in Stock\n");
System.out.printf("%10s", ingredientName);
System.out.printf("%8.2f", amountNeeded);
System.out.printf("%16.2f", amountInStock);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Java: Array Average calculator - Read & Write to and from textfile

my instructions go as followed: "Write a Java program that prompts the user to enter 10 integers. The program must then save the 10 integers into a text file called numbers.txt. The program must then read back in the 10 numbers from the file and display the average of the numbers. HINT: you should save the integers as strings and then convert them back into Integers after reading them back in from the file. Your program must utilize proper exception handling for the case that there is an error writing or reading the file. Also your program needs to include proper javadoc comments."
UPDATE: sorry for not being specific i was rushing to work, I'm having problem conceptualizing how my write and read to file should look. i think most of my code is right. i just need help calling read file to show average and help placing how my write to file should look
excuse the slop i was gonna tidy it up a bit i currently have:
package average;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import javax.swing.JOptionPane;
public class average {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
String prompt = JOptionPane.showInputDialog("Enter 10 numbers to average ");
switch(prompt) {
case "read": openFileRead(); readFromFile(); closeFileRead();
break;
case "write": openFileWrite(); writeToFile(); closeFile();
break;
default: System.out.println("Input not recognized.");
}
}
public static void openFileRead() { // gets file for "read"
try {
input = new Scanner(Paths.get("Numbers.txt"));
}
catch (IOException e) {
System.out.println("Unable to read file");
}
}
public static void openFileWrite() { // gets file for "write"
try {
output = new Formatter("Numbers.txt");
}
catch (FileNotFoundException e) {
System.out.println("Unable to open file");
}
}
public static void readFromFile() {
System.out.print(average);
}
public static void writeToFile() {
Scanner input = new Scanner (System.in);
int num[] = new int[10];
int average = 0;
int i = 0;
int sum = 0;
for (i=0;i<num.length;i++) {
System.out.println("enter a number");
num[i] = input.nextInt();
sum=sum+num[i];
}
average=sum/10;
System.out.println("Average="+average);
}
//required to close file for write
public static void closeFile() {
output.close();
}
//required to close file for read
public static void closeFileRead() {
input.close();
}
}
for (i=0; i<num.length; i++)
{
System.out.println("enter a number");
num[i] = input.nextInt();
sum += num[i];
}

Reading x lines of text at a time from a text file in Java

I'm trying to write a method for a school project for displaying a list of contacts from a text file. Only four contacts are supposed to display at a time and then re-entering "d" should display the next 4 until all have been displayed. Does anyone have any advice in how I could achieve this? Right now I just have it so it reads all of the lines of text.
import java.util.Scanner; import java.io.*;
public class Contacts
{
public static void main(String [] args) throws IOException
{
File aFile = new File("contacts.txt");
if (!aFile.exists())
System.out.println("Cannot find file");
else
{
Scanner in = new Scanner(aFile);
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
if (input.contains("d"))
{
String aLineFromFile;
while(in.hasNext())
{
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
}
in.close();
}
}
}
}
As MadProgrammer said, use a counter to track groups of 4.
else {
Scanner in = new Scanner(aFile);
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
while(input.contains("d")) {
int limit = 4;
String aLineFromFile;
while(in.hasNext() && limit > 0) {
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
limit--;
}
if(in.hasNext()) {
input = keyboard.nextLine();
}
else {
break;
}
}
}

read from text file using try/catch blocks

so im trying to read from a file the number of words and adding them up to give and int answer? And help and or suggestions would be nice, and i can only use a try/catch while for loop and if/else/if.... Thanks!
Here what i got so far:
package filereadingexercise2;
import java.io.*;
import java.util.Scanner;
/**
*
* #author theGreggstar
*/
public class FileReadingExercise2
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner keys = new Scanner(System.in);
String nameOfFile;
System.out.print("Please Enter The Name Of A File Or Directory, or Type Quit To Exit: ");
nameOfFile = keys.nextLine();
Scanner input = null;
try
{
input = new Scanner(new File(nameOfFile));
}
catch(FileNotFoundException s)
{
System.out.println("File does Not Exist Please Try Again: ");
}
while(input.hasNext())
{
String contents = input.next();
int length;
System.out.print(contents);
}
}
}
If I understand you correctly, you want something like this -
public static void main(String[] args) {
Scanner keys = new Scanner(System.in);
for (;;) { // Loop forever.
System.out.print("Please Enter The Name Of A File Or "
+ "Directory, or Type Quit To Exit: ");
String nameOfFile = keys.nextLine().trim(); // get the User input.
if (nameOfFile.equalsIgnoreCase("quit")) { // check for exit condition.
break;
}
File f = new File(nameOfFile); // Construct a File.
if (f.exists()) { // Does it exist?
if (f.isFile() && f.canRead()) { // is it a File and can I read it?
Scanner input = null;
try {
input = new Scanner(f); // The Scanner!
while (input.hasNextLine()) {
String contents = input.nextLine();
System.out.println(contents); // Print the lines.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (input != null) {
input.close(); // Close the file scanner.
}
}
} else if (f.isDirectory()) { // No, it's a directory!
try {
System.out.println("File "
+ f.getCanonicalPath()
+ " is a directory");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Outputting to a text file in Java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This is a homework assignment, I have to write a program that reads a "input.txt" file and sees how many times to print a salutation (ex: Donald Duck, 4 so it prints Hello Donald Duck four times)
The problem I'm having is with outputting the salutation into a text file called "output.txt"
For some reason it only prints out the salutation for the last line in the input.txt instead of all of them.. Here's what I have so far:
import java.util.*;
import java.io.*;
public class Driver0 {
public static void main (String [] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Would you like the output to be written to a file?");
Scanner read;
String input = userInput.nextLine(); //user input
if(input.equals("yes")) {
System.out.println("Writing to \"output.txt\" now..");
}
else {
System.out.println("Printing to screen:");
}
try {
read = new Scanner(new File("input.txt")); //scanner reading file
}
catch (FileNotFoundException e){
System.out.println("File not found.");
return;
}
while(read.hasNextLine()) {
String newInput = read.nextLine();
String [] inputArray = newInput.split(","); //spliting
int num = 0;
num = Integer.parseInt(inputArray[2].trim());
for(int i = 0; i < num; i++) {
if(input.equals("yes")) { //writing to file
Driver0.outputting(inputArray);
}
else { //writing to screen
System.out.println("Hello" + inputArray[1] + inputArray[0]);
}
}
}
}
public static void outputting (String [] inputArray) {
PrintWriter output = null;
String fileName = "output.txt";
try {
output = new PrintWriter(new FileWriter(fileName));
}
catch(IOException error){
System.out.println("Sorry, can't open for writing.");
return;
}
output.println("Hello" + inputArray[1] + inputArray[0]);
output.close();
}
}
My problem is most likely within the outputting method or where it has a comment that says writing to file next to it
Every time through the while loop you're creating a new PrintWriter, writing one line to it, then closing it. This is just overwriting the file each time. You probably should only create one PrintWriter that you keep open and append to it instead.
The FileWriter class has a second constructor that takes a boolean argument to tell it to append to the end of the existing file rather than overwrite it from the start.
output = new PrintWriter(new FileWriter(fileName, true));
This is because you are creating each time a new file Using a new PrintWriter.
a minimally changed ,Quick fix for your sulution, will be (although there are yet many design problems in your code):
import java.util.*;
import java.io.*;
public class Driver0 {
public static void main (String [] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Would you like the output to be written to a file?");
Scanner read;
String input = userInput.nextLine(); //user input
if(input.equals("yes")) {
System.out.println("Writing to \"output.txt\" now..");
}
else {
System.out.println("Printing to screen:");
}
try {
read = new Scanner(new File("input.txt")); //scanner reading file
}
catch (FileNotFoundException e){
System.out.println("File not found.");
return;
}
////////////////////////
PrintWriter output;
String fileName = "output.txt";
try {
output = new PrintWriter(new FileWriter(fileName));
}
catch(IOException error){
System.out.println("Sorry, can't open for writing.");
return;
}
////////////////////////
while(read.hasNextLine()) {
String newInput = read.nextLine();
String [] inputArray = newInput.split(","); //spliting
int num = 0;
num = Integer.parseInt(inputArray[2].trim());
for(int i = 0; i < num; i++) {
if(input.equals("yes")) { //writing to file
Driver0.outputting(output,inputArray);
}
else { //writing to screen
System.out.println("Hello" + inputArray[1] + inputArray[0]);
}
}
}
///////////////////////////////
output.close();
///////////////////////////////
}
public static void outputting (PrintWriter output,String [] inputArray) {
output.println("Hello" + inputArray[1] + inputArray[0]);
}
}

Categories