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

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

Related

Ask the user for the specific filename

import java.util.Scanner;
import java.nio.file.Paths;
import java.io.*;
public class Chupapi{
public static void main(String [ ] args)throws FileNotFoundException{
new Chupapi().getLongestWords();
}
public String getLongestWords() throws FileNotFoundException{
String longWord = "";
String current;
Scanner scan = new Scanner(new File("/Users/user/Documents/PROGRAMMINGTXT/LongestWord.txt"));
while (scan.hasNext()){
current = scan.next();
if ((current.length() > longWord.length()) && (!current.matches(".*\\d.*"))) {
longWord = current;
}
}
System.out.println("Longest word: "+longWord);
longWord.replaceAll("[^a-zA-Z ]", "").split("\\s+");
return longWord;
}
}
I want to add a line where the User will need to enter the specific file name like
"Enter the file name: LongestWord.txt" then outputs the LongestWord but if the user didn't enter the specific file name it will be like "Filename incorrect!" what loop should I use?
You could use an if() else loop.
A possible implementation in your main function would then look like
public static void main(String[] args) throws FileNotFoundException {
final String correctFileName = "LongestWord.txt";
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file name: " + correctFileName);
String s = scan.nextLine();
if (s.equals(correctFileName)) {
new Chupapi().getLongestWords();
} else {
System.out.println("Filename incorrect!");
}
}
Note:
To make the file name dynamic you could set it as a variable outside the main function and use the name in the getLongestWords() function.
final String correctFileName = "LongestWord.txt";
main (){}
getLongestWords (){
...
Scanner scan = new Scanner(new File("/Users/user/Documents/PROGRAMMINGTXT/" + correctFileName));
...
}
Also, this assumes the file is always is the path /Users/user/Documents/PROGRAMMINGTXT/
I used the if() else loop and it somehow got what I wanted to do with it. Thank you guys #OneCricketeer and #Tcheutchoua Steve
import java.util.Scanner;
import java.io.*;
public class Chupapi{
public static void main(String [ ] args)throws FileNotFoundException{
new Chupapi().getLongestWords();
}
public String getLongestWords() throws FileNotFoundException{
Scanner scanner = new Scanner (System.in);
System.out.print("Enter the specific filename: ");
String filename = scanner.next();
String longWord = "";
String current;
Scanner scan = new Scanner(new File("/Users/glenn/Documents/PROGRAMMINGTXT/LongestWord.txt"));
while (scan.hasNext()) {
current = scan.next();
if ((current.length() > longWord.length()) && (!current.matches(".*\\d.*"))) {
longWord = current;
}
}
if (filename.equals("LongestWord.txt")) {
System.out.println("Pinakamahabang salita: " + longWord);
longWord.replaceAll("[^a-zA-Z ]", "").split("\\s+");
return longWord;
}
else {
System.out.println("Incorrect filename!");
return filename;
}
}
}

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

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

Adding up from a text file and ignoring syntax errors

I am writing a code that adds up numbers from a text file and displays the total. But i want to make it so that if the user enters a word or a decimal number then it ignores it and carries on adding up the next number?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Task1 {
public static void main(String [] args) throws FileNotFoundException {
File myFile = new File("Numbers.txt");
Scanner scan = new Scanner(myFile);
int sum=0;
while (scan.hasNext()) {
sum+= scan.nextInt( );
}
System.out.println(sum);
scan.close();
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Task1 {
public static void main(String [] args) throws FileNotFoundException {
File myFile = new File("Numbers.txt");
Scanner scan = new Scanner(myFile);
String sum="";
int number = 0;
int total = 0;
while (scan.hasNext()) {
try {
sum = scan.next();
number = Integer.parseInt(sum);
total += number;
} catch(Exception e) {
System.out.println("Unable to parse string !! + " + sum);
}
}
System.out.println("The total is : " + total);
scan.close();
}
}
Use scan.next() instead, and wrap a Integer.parseInt() around it. Then add a try-catch to catch the NumberFormatExceptions that will occur if Integer.parseInt() tries to parse a non integer:
while (scan.hasNext()) {
try {
sum += Integer.parseInt(scan.next());
}
catch (NumberFormatException e) {
//If there was a NumberFormatException, do nothing.
}
}
System.out.println(sum);

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

BufferReader to write new file with previous info

This is the basis of my code. It prints students grades on the console, but how do I use a Buffereader to put all the students grade on a new file.
import java.io.*;
import java.util.InputMismatchException;
import java.lang.*;
import java.util.*;
public class WorkSpace {
private Scanner x;
public void openFile(){
try{
x = new Scanner (new File ("grades.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}}
public void createFile()throws IOException {
try{
File file = new File("grades.txt");
Scanner s = new Scanner(file);
while(s.hasNext()){
{
String [] split = s.nextLine().split(", ");
String fname = split[0];
Double q1 = Double.parseDouble (split[1]);
Double q2 = Double.parseDouble (split[2]);
Double q3 = Double.parseDouble (split[3]);
Double q4 = Double.parseDouble (split[4]);
Double proji = Double.parseDouble (split[5]);
Double projii = Double.parseDouble (split[6]);
Double projiii = Double.parseDouble (split[7]);
double studentgrade = (q1 *0.1) + (q2 *0.1) +(q3 *0.1) + (q4 *0.1) +(proji*0.15) + (projii * 0.2) + (projiii *0.25);
if(studentgrade>90)
System.out.printf("%s got an A\n", fname);
else if(studentgrade>80)
System.out.printf("%s got a B\n", fname);
else if(studentgrade>70)
System.out.printf("%s got a C\n", fname);
else if(studentgrade>60)
System.out.printf("%s got a D\n", fname);
else if(studentgrade>50)
System.out.printf("%s got a F\n", fname);
}}}catch(Exception e){
e.printStackTrace();
}
}
public void closeFile(){
x.close();
}
Scanner.nextInt() returns next integer value read from source (not source length or something). You open the file and try to read integer in the beginning, but the file doesn't start with integer so you get an exception.
How you are reading your file is incorrect. The most common way to read files with scanner:
try{
File file = new File("Your/File/Path");
Scanner s = new Scanner(file);
s.useDelimiter("\n");//splits the whole file's text by "\n"
while(s.hasNext()){
String next = s.next();
//parse your stuff
}
s.close();
}catch(Exception e){}
Also, scanner.nextInt() doesn't return the file's length. That was the problem. Use file.length to get the file's length.
Your question doesn't make sense. BufferedReader doesn't write files. It, err, reads files. What you want is, err, a BufferedWriter.

Categories