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];
}
Related
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 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);
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.
i have this assignment :
File input scores.txt contains matric number and marks for six quizzes. Maximum mark for each quiz is 15. Write a program that reads matric number and marks from the input file. Calculate total and average for each student and write into output file. Scores are separated by blanks. Using the calculated average mark, convert it to percentage and set a grade based on UTM grading scheme.
i do this coding but i have problem when i press run there is errors
import java.io.PrintWriter;
import java.util.*;
public class Q1 {
public static int number,number1,number2;
public static double sum,sum1,sum2,average,average1,average2;
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
java.io.File file=new java.io.File("input.txt");
Scanner input=new Scanner(file);
while(input.hasNext()){
number=input.nextInt();
int q1=input.nextInt();
int q2=input.nextInt();
int q3=input.nextInt();
int q4=input.nextInt();
int q5=input.nextInt();
sum=q1+q2+q3+q4+q5;
average=sum/5;
number1=input.nextInt();
int q21=input.nextInt();
int q22=input.nextInt();
int q23=input.nextInt();
int q24=input.nextInt();
int q25=input.nextInt();
sum1=q21+q22+q23+q24+q25;
average1=sum/5;
number2=input.nextInt();
int q31=input.nextInt();
int q32=input.nextInt();
int q33=input.nextInt();
int q34=input.nextInt();
int q35=input.nextInt();
sum2=q31+q32+q33+q34+q35;
average2=sum/5;
input.close();
}
PrintWriter output=new java.io.PrintWriter("file1.txt");
output.print(number);
output.print(sum);
output.println(average);
output.print(number1);
output.print(sum1);
output.println(average1);
output.print(number2);
output.print(sum2);
output.println(average2);
output.close();
PrintWriter output1=new java.io.PrintWriter("file2.txt");
output.print(number);
output.print(sum);
output.println(check(average));
output.print(number1);
output.print(sum1);
output.println(check(average1));
output.print(number2);
output.print(sum2);
output.println(check(average2));
output.close();
}
public static double check(double a){
if(a>=80){
System.out.print("A");
}
else if((a<80)&&(a>=70)){
System.out.print("B");
}
else if((a>=60)&&(a<70)){
System.out.print("C");
}
else
System.out.print("D");
return a;
}
}
You do have a typo regarding the output:
PrintWriter output1=new java.io.PrintWriter("file2.txt");
output.print(number);
output.print(sum);
output.println(check(average));
output.print(number1);
output.print(sum1);
output.println(check(average1));
output.print(number2);
output.print(sum2);
output.println(check(average2));
output.close();
You forgot to change it to output1.
This is a school project:
Objective:
Ask the user to input 2 number
A random number will be print to the user.
Must catch if input isn't Integer.
I have check online source, which i copied the code and use it.
Min + (int)(Math.random() * ((Max - Min) + 1))
The code work fine except if I input any integer less than 10. The Program will consider it as a letter and says "ERROR"
My Program:
import java.lang.StringBuffer;
import java.io.IOException;
import java.util.Random;
class RandomInput2
{
public static void main(String args[])
{
System.out.println("Programe Begins");
Random seed = new Random();
int n1 , n2, rand ;
System.out.println("What is your name?");
String InputString = GCS();
while(true)
{
try
{
System.out.println("What is your First number?");
n1 = Integer.parseInt(GCS());
System.out.println("What is your second number");
n2 = Integer.parseInt(GCS());
rand = n2+ (int)(seed.nextDouble()*((n1-n2)+1));
System.out.println(InputString+" Your number is "+rand);
}
catch(NumberFormatException NFE) //catch if integer's not number
{
System.err.println("ERROR");
System.err.println("Type in Integer only");
}
catch(Exception E) //catch General Error
{
System.err.println("ERROR");
}
;
}
}
public static String GCS() //Get Console String
{
int noMoreInput =-1; //set int
char enterKeyHit= '\n'; //set char
int InputChar;
StringBuffer InputBuffer = new StringBuffer(100);
try
{
InputChar=System.in.read();
while(InputChar != noMoreInput)
{
if((char)InputChar!=enterKeyHit)
{
InputBuffer.append((char)InputChar);
}
else
{
InputBuffer.setLength(InputBuffer.length()-1);
break;
}
InputChar = System.in.read();
}//ends while loop
}
catch(IOException IOX)
{
System.err.println(IOX);
}
return InputBuffer.toString();
}
}
Look at the GSC code -- if I enter 1 character and then hit enter, what's the length of the InputBuffer when I do hit enter?
Since you want to read a whole line, consider using an InputStreamReader to read System.in, and then a BufferedReader to wrap that reader (so that you can call readLine).