Adding up from a text file and ignoring syntax errors - java

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

Related

Why is my parser.next scanner picking up on a parenthesis and number instead of the string that comes before i despite having a delimiter

The document I'm scanning says "enter(10);add;(45.76)" on a single line. It's supposed to read over the parenthesis and semicolons and just get the numbers and strings, as well as read the word "enter" before running the code. It manages to read enter correctly and the first number, but after that when scanning for "equation" it instead grabs 45.67) with the parenthesis. If i remove the (45.67) and leave just add; it works and grabs the add. I'm not sure what's going on wrong here. Any help would be appreciated, as well as any advice on how to get this program to scan the next line in the file if there was another one.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class CPLParser {
public double parseScript(String inputFile) throws CPLException{
File file = new File(inputFile);
try (Scanner Filereader = new Scanner(file)){
String line = Filereader.nextLine();
Scanner parser = new Scanner(line);
parser.useDelimiter("\\(|\\)\\;");
String enter = parser.next();
double number = 0;
String equation = " ";
double numberTwo = 0;
double total = 0;
if (!enter.equals("enter")){
throw new InvalidProgramStartException("");
}
while (parser.hasNext()) {
if (parser.hasNextDouble()){
number = parser.nextDouble();
}
if (parser.hasNext()){
equation = parser.next();
}
if (parser.hasNextDouble()){
numberTwo = parser.nextDouble();
}
if (equation == "add") {
double thistotal = number + numberTwo;
total += thistotal;
}
}
System.out.println(equation);
} catch (FileNotFoundException ex) {
System.out.println("Could not find the file");
} catch (InputMismatchException e) {
}
return 0;
}
}
There are few issues in your sample code:
Firstly in java you can not compare string with == you should use Equals method to check equality.
Secondly operation should be done after reading entire line,
also there were blank chars were read by scanner we need to handle that
Please have look into below working code and verify the output.
import java.net.MalformedURLException;
import java.net.URL;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
try {
Scanner parser = new Scanner("enter(10);add;(45.76)");
parser.useDelimiter("\\(|\\)|\\;");
String enter = parser.next();
System.out.println("enter "+enter);
double number = 0;
String equation = " ";
double numberTwo = 0;
double total = 0;
if (!enter.equals("enter")){
// new InvalidProgramStartException("");
System.out.println("InvalidProgramStartException");
}
while (parser.hasNext()) {
if (parser.hasNextDouble()){
number = parser.nextDouble();
System.out.println("number "+ number);
}
if (parser.hasNext()){
String text= parser.next();
// only set equation if its not blank
if ("".equals(text))
{ System.out.println("equation is Blank "+ equation +"...");}
else
{equation = text;
System.out.println("Setting equation "+ equation);}
}
if (parser.hasNextDouble()){
numberTwo = parser.nextDouble();
System.out.println("numberTwo "+ numberTwo);
}
}
if (equation.equals("add")) {
double thistotal = number + numberTwo;
System.out.println("thistotal "+ thistotal);
System.out.println("total "+ total);
total += thistotal;
System.out.println("total "+ total);
}
System.out.println(equation);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hope this helps!

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

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

I can't seem to get Java to read my text document

import java.util.Scanner;
public class Average
{
public void Average()
{
Scanner in = (new Scanner("J:\\AP Comptuter Science\\Semester 2\\Exeptions\\13.1\\numbers.txt"));
try{
String test = in.nextLine();
} catch(NullPointerException i) {
System.out.println("Error: " + i.getMessage());
}
int total = 0;
int counter = 0;
while(in.hasNextInt()){
total = total + in.nextInt();
counter++;
}
total = total / counter;
System.out.println(total);
}
}
I have a project for my AP Comp class and i did the work according to the notes, but the file "numbers" isn't being read and i get the answer 0 when it should be some huge number.
new Scanner("J:\\AP Comptuter Science\\Semester 2\\Exeptions\\13.1\\numbers.txt")
You are calling Scanner(String source), which does not read the file; it scans the string itself.
What you need is probably public Scanner(File source), as follows:
new Scanner(new File("J:\\AP Comptuter Science\\Semester 2\\Exeptions\\13.1\\numbers.txt"))
You also need to check the path, there almost certainly aren't 5 spaces between "Semester" and "2"
Overall I would strongly urge you to step through your code in a debugger instead of just running. If you had done that, you would have seen that after executing
String test = in.nextLine();
The string test contains the name of the file rather than its contents.
There are other improvements possible, consider posting in the codereview stackexchange after you are able to make it work
Firstly you should correct your path, and probably put it in the same directory as your class files. And instead of providing a path to the scanner you should also give it a file. It should look something like this.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Average
{
public void printAverage(){
File file = new File(""J:\\AP Comptuter Science\\Semester 2\\Exeptions\\13.1\\numbers.txt"");
Scanner scan;
try {
scan = new Scanner(file);
int total = 0, counter = 0;
while(scan.hasNextInt()){
System.out.println("loop");
total = total + scan.nextInt();
counter++;
}
if(counter != 0)
total = total/counter;
System.out.println(total);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
As mentioned earlier, the code has several issues:
a) new Scanner(String) reads the string instead of the file
b) path seems to be incorrect
c) handling of DivideByZero and FileNotFound exceptions
Please see the following code:
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class Average{
public void average(){
Scanner in = null;
try{
in = (new Scanner(new File("J:\\AP Comptuter Science\\Semester 2\\Exeptions\\13.1\\numbers.txt")));
String test = in.nextLine();
}
catch(NullPointerException | FileNotFoundException i){
System.out.println("Error: " + i.getMessage());
}
int total = 0;
int counter = 0;
while(in != null && in.hasNextInt())
{
total = total + in.nextInt();
counter++;
}
Float average = null;
if (counter > 0) { //to avoid divide by zero error
average = (float)total / counter;
System.out.println("Average: "+average);
}
}
public static void main(String args[]){
new Average().average();
}
}
This works for only numbers.txt which has integers separated by space as required by the nextInt() method of Scanner class.

How to find and print the repeated words in a text file from user input java

When I run the program, I would like to enter a word thats in the text file and have it print out how many times the word is stored in the text. For Example:
Enter a word from the text: eric
The word eric is stored 5 times in the text file.
My code below already reads the text file, but I am stuck on the wordCount method. I don't know how to start.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class WordSet {
private static Scanner file;
private static ArrayList<String> words = new ArrayList<String>();
//private static Map<String, Integer> occurences = new HashMap<String, Integer>();
//private static Set<String> uniqueWords = new HashSet<String>(words);
//private static int tWords = 0;
//private static int uWords = 0;
//private static String [] word1 = new String[10];
//private static String [] word2 = new String[10];
public static void openFile() throws IOException {
try {
file = new Scanner(new File("words.txt"));
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
e.printStackTrace();
} catch (Exception e) {
System.out.println("IOException");
}
}
public static String wordCount() throws IOException {
Random r = new Random();
while(file.hasNext()) {
words.add(file.next());
}
String wordCount = words.get(r.nextInt(words.size()));
return wordCount;
}
public static void main(String[] args) throws IOException {
System.out.println("Enter a word from the text: ");
openFile();
Scanner scan = new Scanner(System.in);
String pickWord = wordCount();
while(scan.hasNext()) {
String input = scan.nextLine();
if(input.equals(pickWord)) {
System.out.println(pickWord);
}
}
scan.close();
}
}
I would consider hashing and counting each word in file. The you just hash user input as well and if it's in the table return the count. It looks like you already were planning that.
I have added taken input from command line and read ArrayList to give freq below is snippet
public static void main(String[] args) throws IOException {
System.out.println("Enter a word from the text: ");
openFile();
Scanner scan = new Scanner(System.in);
String inputStr = scan.next();
Collections.frequency(words, inputStr);
String pickWord = wordCount();
System.out.println("You have entered '" + inputStr
+ "' frequency in text file is :"
+ Collections.frequency(words, inputStr));
/*
* while(scan.hasNext()) { String input = scan.nextLine();
*
* if(input.equals(pickWord)) { System.out.println(pickWord); } }
*/
scan.close();
}
Bu using Collections.frequency() u can count easily with less code... :)

Categories