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

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.

Related

Java can't find symbol defined in a try-catch block in a do while loop [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 12 months ago.
I keep running into this error when compiling this code here:
TryTryAgain.java:52: error: cannot find symbol
if (file.hasNextInt()) {
^
symbol: variable file
location: class TryTryAgain
It's not picking up the file symbol I defined in the try-catch block within that do-while loop while compiling. I'm not really sure how to fix this as it has to be in there or else I wouldn't be able to throw the exception and repeat until a valid file name is given.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
import java.io.IOException;
import java.util.InputMismatchException;
public class TryTryAgain {
public static void main(String[] args) {
Scanner userInp = new Scanner(System.in);
System.out.print("Please enter the name of the file: ");
String userFile = userInp.next();
boolean fileAccepted = false;
do {
try {
Scanner file = new Scanner(new File(userFile));
fileAccepted = true;
} catch (FileNotFoundException e) {
System.out.println(userFile + " (The system cannot find the file specified)");
System.out.print("Please enter a valid file name: ");
userFile = userInp.next();
}
} while (fileAccepted == false);
int currentHighest = 0;
int currentLowest = 2147483647;
int totalOf = 0;
double totalNums = 0.0;
int currentNum;
//Making these to make the output look like the example ones
String total = "Total";
String min = "Min";
String max = "Max";
String average = "Average";
do {
if (file.hasNextInt()) {
totalNums++;
currentNum = file.nextInt();
totalOf += currentNum;
if (currentHighest < currentNum) {
currentHighest = currentNum;
}
if (currentLowest > currentNum) {
currentLowest = currentNum;
}
} else if (file.hasNextLine()) {
System.out.println("Skipping over invalid input: " + file.nextLine());
} else if (file.hasNextDouble()) {
System.out.println("Skipping over invalid input: " + file.nextDouble());
}
} while (file.hasNextInt() || file.hasNextLine() || file.hasNextDouble());
file.close();
if (totalNums > 0) {
double averageVal = (totalOf / totalNums);
System.out.printf("%7s: %d", total, totalOf);
System.out.printf("%7s: %d", min, currentLowest);
System.out.printf("%7s: %d", max, currentHighest);
System.out.printf("%7s: %d", average, averageVal);
} else {
System.out.println("No valid data found. No stats available.");
}
} //end main
}
I would suggest using a try-with-resources statement and moving the processing logic and perhaps the display logic to their own separate methods. The try-with-resources means you don't need to explicitly call file.close() and you cannot forget, nor can it be missed if some RuntimeException occurs in your code due to a null pointer, input mismatch, or any other unexpected problem. Some people would frown on the while (true) here and exiting the loop with break; but I think it's cleaner than using the separate condition variable and is all right as long as the loop body is kept simple, which it is if you extract the processing and display logic to their own methods. But if you prefer the condition variable on the loop, that is of course always an option.
public static void main(String[] args) {
Scanner userInp = new Scanner(System.in);
System.out.print("Please enter the name of the file: ");
String userFile = userInp.next();
while (true) {
try (Scanner file = new Scanner(new File(userFile))) {
process(file);
break;
} catch (FileNotFoundException e) {
System.out.println(userFile + " (The system cannot find the file specified)");
System.out.print("Please enter a valid file name: ");
userFile = userInp.next();
}
}
}
public static void process(Scanner file) {
int currentHighest = 0;
int currentLowest = 2147483647;
int totalOf = 0;
double totalNums = 0.0;
int currentNum;
do {
if (file.hasNextInt()) {
totalNums++;
currentNum = file.nextInt();
totalOf += currentNum;
if (currentHighest < currentNum) {
currentHighest = currentNum;
}
if (currentLowest > currentNum) {
currentLowest = currentNum;
}
} else if (file.hasNextLine()) {
System.out.println("Skipping over invalid input: " + file.nextLine());
} else if (file.hasNextDouble()) {
System.out.println("Skipping over invalid input: " + file.nextDouble());
}
} while (file.hasNextInt() || file.hasNextLine() || file.hasNextDouble());
display(totalNums, totalOf, currentLowest, currentHighest);
}
public static void display(int totalNums, int totalOf, int lowest, int highest) {
String total = "Total";
String min = "Min";
String max = "Max";
String average = "Average";
if (totalNums > 0) {
double averageVal = (totalOf / totalNums);
System.out.printf("%7s: %d", total, totalOf);
System.out.printf("%7s: %d", min, lowest);
System.out.printf("%7s: %d", max, highest);
System.out.printf("%7s: %d", average, averageVal);
} else {
System.out.println("No valid data found. No stats available.");
}
}
You are referring to file that doesn't exist in the context of the do-while loop. You create and establish the file inside a try catch at the beginning of your class. Move the logic for opening/closing the file into a single try catch, and the try section should contain the logic for reading the file.
try
{
// logic for opening file
// log for reading (the do/while that processes the file)
}catch(FileNotFound){

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!

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

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

Categories