import java.io.*;
import java.util.*;
public class Exercise3_2
{
public static void main(String[] args) throws FileNotFoundException
{
String firstName;
String lastName;
double score1, score2, score3, score4, score5;
double avg;
Scanner inFile = new Scanner(new FileReader("test.txt"));
PrintWriter outFile = new PrintWriter ("testavg.out");
firstName = inFile.next();
lastName = inFile.next();
outFile.println("Student name : " + firstName + " " + lastName);
score1 = inFile.nextDouble();
score2 = inFile.nextDouble();
score3 = inFile.nextDouble();
score4 = inFile.nextDouble();
outFile.println("Test scores: " + score1 + " ," + score2 + " ," + score3
+ " ," + score4);
avg = (score1 + score2 + score3 + score4) / 4;
outFile.printf("Average test scores: %5.2f %n, avg");
inFile.close();
outFile.close();
}
}
Whenever I run this this is what I get :
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
......WHY!!!!
Related
I don't know why my code is not calculating the average. It is compiling and running, but gives 0% as average. Here are the instructions for the assignment
Average and Grade (Methods Program):
Write a program that asks the user to enter 5 test scores. Your program should then display a letter
grade for each test score, the average test score and the overall letter grade
for the average score. You can NOT use a for loop or an array (we haven't even covered that) in this
program - the point is to learn how to define methods and call them several
times if necessary.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework8{
static double average;
static char grade;
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;
System.out.println("Please enter the first score between 0 and 100: ");
score1 = keyboard.nextDouble();
System.out.println("Please enter the second score between 0 and 100: ");
score2 = keyboard.nextDouble();
System.out.println("Please enter the third score between 0 and 100: ");
score3 = keyboard.nextDouble();
System.out.println("Please enter the fourth score between 0 and 100: ");
score4 = keyboard.nextDouble();
System.out.println("Please enter the fifth score between 0 and 100: ");
score5 = keyboard.nextDouble();
//System.out.println("The average of your five tests was: " +
System.out.println(
"For TestA you scored: " + score1 + " giving you Grade: "
+ determineGrade(score1)
+ "\nFor TestB you scored: " + score2 + " giving you Grade: "
+ determineGrade(score2)
+ "\nFor TestC you scored: " + score3 + " giving you Grade: "
+ determineGrade(score3)
+ "\nFor TestD you scored: " + score4 + " giving you Grade: "
+ determineGrade(score4)
+ "\nFor TestF you scored: " + score5 + " giving you Grade: "
+ determineGrade(score5)
+ "\nBased on your average: " + average + " Your final Grade is: "
+ determineGrade((double)average));
}
public static double calcAverage(double score1, double score2, double score3, double score4, double score5) {
double average = (score1+score2+score3+score4+score5) / 5;
return average;
}
public static char determineGrade(double score)
{
if(score<=100 && score>=90)
{
return 'A';
}
else if(score>=80)
{
return 'B';
}
else if(score>=70)
{
return 'C';
}
else if(score>=60)
{
return 'D';
}
else
{
return 'F';
}
}
}
you define the method calcAverage but you didn't call it.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework8{
static double average;
static char grade;
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;
System.out.println("Please enter the first score between 0 and 100: ");
score1 = keyboard.nextDouble();
System.out.println("Please enter the second score between 0 and 100: ");
score2 = keyboard.nextDouble();
System.out.println("Please enter the third score between 0 and 100: ");
score3 = keyboard.nextDouble();
System.out.println("Please enter the fourth score between 0 and 100: ");
score4 = keyboard.nextDouble();
System.out.println("Please enter the fifth score between 0 and 100: ");
score5 = keyboard.nextDouble();
double average = calcAverage(score1,score2,score3,score4,score5);
//System.out.println("The average of your five tests was: " +
System.out.println(
"For TestA you scored: " + score1 + " giving you Grade: "
+ determineGrade(score1)
+ "\nFor TestB you scored: " + score2 + " giving you Grade: "
+ determineGrade(score2)
+ "\nFor TestC you scored: " + score3 + " giving you Grade: "
+ determineGrade(score3)
+ "\nFor TestD you scored: " + score4 + " giving you Grade: "
+ determineGrade(score4)
+ "\nFor TestF you scored: " + score5 + " giving you Grade: "
+ determineGrade(score5)
+ "\nBased on your average: " + average + " Your final Grade is: "
+ determineGrade((double)average));
}
public static double calcAverage(double score1, double score2, double score3, double score4, double score5) {
double average = (score1+score2+score3+score4+score5) / 5.0;
return average;
}
public static char determineGrade(double score)
{
if(score<=100 && score>=90)
{
return 'A';
}
else if(score>=80)
{
return 'B';
}
else if(score>=70)
{
return 'C';
}
else if(score>=60)
{
return 'D';
}
else
{
return 'F';
}
}
}
I want to be able to have my catch request users to input the name of the file until the file name is valid, would anyone be able to give me a suggestion on how to arrange my code to do this?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Requierment2 {
public static void main(String[] args) {
String filename ="";
Scanner keyboard = new Scanner(System.in);
System.out.println ("Press K for keyboard or F to read expressions from a file");
String user_input=keyboard.nextLine();
String [] ui = user_input.split(" ");
if (ui[0].equals( "k") | ui[0].equals("K")) {
while (true){
System.out.println("Please Enter a Post-Fix Expression (eg: 5 2 *)");
String postfix=keyboard.nextLine();
String [] elements =postfix.split(" ");
if (postfix.equals("")){
System.out.println("Application Closed");
keyboard.close();
System.exit(0);
}
if (elements.length >=3){
try{
float num1, num2;
num1 = Float.parseFloat(elements[0]);
num2 = Float.parseFloat(elements[1]);
if(elements[2].equals("+")){
System.out.println("Total: "+(num1 + num2));
}
else if(elements[2].equals("*")){
System.out.println("Total: "+(num1 * num2));
}
else if(elements[2].equals("/")){
System.out.println("Total: "+(num1 / num2));
}
else if(elements[2].equals("-")){
System.out.println("Total: "+(num1 - num2));
}
else{
System.out.println("Error Invalid Expression: "+ postfix);
}
}
catch(NumberFormatException e){
System.out.println("Error Invalid Expresion: "+postfix);
}
}
else if (elements.length <3) {
System.out.println("Error Invalid Expression: "+ postfix);
}
}
}
else if (ui[0].equals( "f") | ui[0].equals("F"))
{
try{
System.out.println("Please enter file name eg: Demo.txt");
filename= keyboard.nextLine();
Scanner s = new Scanner(new File(filename));
System.out.println("Processing "+ filename);
System.out.println( );
String line= s.nextLine();
String array []= line.split(" ");
if (array.length >=3){
try{
float array1, array2, total1, total2, total3, total4, array3 , array5;
array1 = Float.parseFloat(array[0]);
array2 = Float.parseFloat(array[1]);
total1 = array1 + array2;
total2 = array1 * array2;
total3 = array1 / array2;
total4 = array1 - array2;
if(array[2].equals("+")){
System.out.println("Postfix Expression: " + line );
System.out.println(array1 + " " + array[2] + " " + array2 + " = " + total1);
System.out.println( );
}
else if(array[2].equals("*")){
System.out.println("Postfix Expression: " + line );
System.out.println(array1 + " " + array[2] + " " + array2 + " = " + total2);
System.out.println( );
}
else if(array[2].equals("/")){
System.out.println("Postfix Expression: " + line );
System.out.println(array1 + " " + array[2] + " " + array2 + " = " + total3);
System.out.println( );
}
else if(array[2].equals("-")){
System.out.println("Postfix Expression: " + line );
System.out.println(array1 + " " + array[2]+ " " + array2 + " = " + total4);
System.out.println( );
}
else{
System.out.println(" Error Invalid Expression: "+ line);
System.out.println( );
}
}
catch(NumberFormatException e){
System.out.println(" Error Invalid Expresion: "+ line);
System.out.println( );
}
}
else if (array.length <3) {
System.out.println(" Error Invalid Expression: "+ line);
System.out.println( );
}
while ( s.hasNext() ) {
String nl= s.nextLine();
String ar []= nl.split(" ");
if (ar.length >=3){
try{
float ar1, ar2, total1, total2, total3, total4;
ar1 = Float.parseFloat(ar[0]);
ar2 = Float.parseFloat(ar[1]);
total1 = ar1 + ar2;
total2 = ar1 * ar2;
total3 = ar1 / ar2;
total4 = ar1 - ar2;
if(ar[2].equals("+")){
System.out.println("Postfix Expression: " + nl );
System.out.println(ar1 + " " + ar[2] + " " + ar2 + " = " + total1);
System.out.println( );
}
else if(ar[2].equals("*")){
System.out.println("Postfix Expression: " + nl );
System.out.println(ar1 + " " + ar[2] + " " + ar2 + " = " + total2);
System.out.println( );
}
else if(ar[2].equals("/")){
System.out.println("Postfix Expression: " + nl );
System.out.println(ar1 + " " + ar[2] + " " + ar2 + " = " + total3);
System.out.println( );
}
else if(ar[2].equals("-")){
System.out.println("Postfix Expression: " + nl );
System.out.println(ar1 + " " + ar[2]+ " " + ar2 + " = " + total4);
System.out.println( );
}
else{
System.out.println(" Error Invalid Expression: "+ nl);
System.out.println( );
}
}
catch(NumberFormatException e){
System.out.println(" Error Invalid Expresion: "+ nl);
System.out.println( );
}
}
else if (array.length <3) {
System.out.println(" Error Invalid Expression: "+ nl);
System.out.println( );
}
}
}
catch (FileNotFoundException e){
System.out.println("Error: That file does not exist, please re-enter: ");
filename= keyboard.nextLine();
Scanner s ;
}
}
else{
System.out.println("Neither K or F have been entered");
System.out.println("System Terminated");
keyboard.close();
}
}
}
Print a more comprehensive example of the type of file name you require with the rules.
Use 'visitor' pattern to implement exception rules.
I would suggest not relying on exceptions at all, and instead look at the isFile() or exists() and isDirectory() methods of the File() class. So create a simple loop that keeps looping until a valid filename is entered, or while isFile() is false.
Example 1:
import java.io.File;
import java.util.Scanner;
public class Requirement2 {
public static void main(String[] args) {
String filename ="";
Scanner keyboard = new Scanner(System.in);
while (true) {
System.out.println("Please enter file name eg: Demo.txt");
filename= keyboard.nextLine();
File file = new File(filename);
if (!file.isFile()) {
System.out.println("File does not exist. Try again.");
}
else {
System.out.println("File exists. Proceeding.");
break;
}
}
keyboard.close();
}
}
Example 2:
import java.io.File;
import java.util.Scanner;
public class Requirement2v2 {
public static void main(String[] args) {
String filename ="";
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter file name eg: Demo.txt");
filename= keyboard.nextLine();
File file = new File(filename);
while (!file.isFile()) {
System.out.println("File does not exist. Try again.");
filename= keyboard.nextLine();
file = new File(filename);
}
System.out.println("File exists. Proceeding.");
keyboard.close();
}
}
I keep getting this error and i can't figure out why:
Glosor.java:102: error: variable språk1 might not have been initialized
JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
^
Glosor.java:102: error: variable språk2 might not have been initialized
JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
This is my code:
javax.swing.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.io.*;
public class Glosor {
public static void main(String[] args) throws IOException {
List<String> gloslista1 = new LinkedList<String>(Arrays.asList());
List<String> gloslista2 = new LinkedList<String>(Arrays.asList());
String inputStr1 = JOptionPane.showInputDialog(null,
"**********************************" + "\n\n" +
"1. Skapa glosövning" + "\n\n" +
"2. Starta glosövning" + "\n\n" +
"3. Avsluta" + "\n\n" +
"**********************************");
int input1 = Integer.parseInt(inputStr1);
switch (input1) {
case 1:
String övningsnamn = JOptionPane.showInputDialog(null, "Vad heter övningen?");
String språk1 = JOptionPane.showInputDialog(null, "Språk 1?");
String språk2 = JOptionPane.showInputDialog(null, "Språk 2?");
while (true) {
String glosa1 = JOptionPane.showInputDialog(null, "Skriv in glosa på " + språk1 + "\n\n" +
"När du är klar skriv klar i rutan");
if(glosa1.equals("klar")) {
break;
}
else {
String glosa2 = JOptionPane.showInputDialog(null, "Skriv in glosa på " + språk2);
gloslista1.add(glosa1);
gloslista2.add(glosa2);
}
}
String filnamn1 = "språk1ord.txt";
String filnamn2 = "språk2ord.txt";
PrintWriter utström1 = new PrintWriter
(new BufferedWriter
(new FileWriter(filnamn1)));
//Skapar en text fil för glosorna på svenska
PrintWriter utström2 = new PrintWriter
(new BufferedWriter
(new FileWriter(filnamn2)));
//Skapar en text fil för glosorna på franska
for(int i = 0; i<=gloslista1.size()-1; i++) {
utström1.println(gloslista1.get(i));
utström2.println(gloslista2.get(i));
//Skriver in glosor i text filerna
}
utström1.close();
utström2.close();
case 2:
String inputStr2 = JOptionPane.showInputDialog(null,
"**********************************" + "\n\n" +
"1. Starta glosövning" + "\n\n" +
"2. Avsluta" + "\n\n" +
"**********************************");
int input2 = Integer.parseInt(inputStr2);
if(input2 == 1) {
BufferedReader inström1 = new BufferedReader
(new FileReader("svenskaord.txt"));
String språk1glosor;
BufferedReader inström2 = new BufferedReader
(new FileReader("franskaord.txt"));
String språk2glosor;
int counter = 0;
while (true) {
counter++;
språk1glosor = inström1.readLine();
språk2glosor = inström2.readLine();
if(counter > gloslista1.size())
break;
String svar = JOptionPane.showInputDialog(null, språk1 + ":" + språk1glosor + "\n" + språk2 + ":");
}
}
You are initializing språk1 in your case 1 and referring to it in both case 1 and case 2. You need to move the initialization out of the case statement:
int input1 = Integer.parseInt(inputStr1);
String övningsnamn = JOptionPane.showInputDialog(null, "Vad heter övningen?");
String språk1 = JOptionPane.showInputDialog(null, "Språk 1?");
String språk2 = JOptionPane.showInputDialog(null, "Språk 2?");
switch (input1) {
Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}
but when I run the program using the command line. I get a run time error of "java.lang.NoClassDefFoundError". All I did was copy the code from Netbeans and paste it on a notepad file and then tried running it by command prompt. I am not sure what I am/ did wrong. Any feedback is greatly appreciated it! Here is my code BTW
package reader;
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class Reader{
public static final Scanner in = new Scanner( System.in);
static final int adult = 0; // The index representation numbers for the total and count arrays;
static final int child = 1;
static final int adultMale = 2;
static final int adultFemale = 3;
static final int childMale = 4;
static final int childFemale = 5;
static final int people = 6;
static final int family = 7;
public static void main(String[] arg){
if(arg.length > 2){ die("Too many arguments");}
else {System.out.println("Good");}
String inFileName;
if(arg.length > 0){ inFileName = arg[0];}
else {
inFileName = "population.txt";}
Scanner fin = openFile(inFileName);
int[] count = new int[8]; // adults,children,male adult, female adult, male child , female child, people, family
int[] total = new int[8]; //adults,children,male adult, female adult, male child , female child, people, family
for( ; fin.hasNextLine(); ){
String line = fin.nextLine();
String error = check(line);
if(error != null){die(error);}
else{ gather(line, count, total);}
}//loop
for(int i = 0; i< count.length; i++){ System.out.print(count[i] + " ");}
System.out.println();
for(int i = 0; i< total.length; i++){ System.out.print(total[i] + " ");}
System.out.println();
System.out.println((float)count[family]/count[people]);
fin.close();
String outFileName;
if( arg.length > 1){ outFileName = arg[1];}
else{outFileName = "output.txt";}
PrintStream fout = outFile(outFileName);
showCensus(fout,count,total);
}//main
public static void die(String message){
System.err.println("Error: " + message);
System.exit(1);
}//die
public static Scanner openFile(String fileName){
Scanner inputFile = null;
try{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e){ die("File not found: " + fileName);
}
return inputFile;
}// OpenFIle
public static PrintStream outFile(String fileName){
Scanner temp = null;
try{
temp = new Scanner(new File(fileName));
} catch(FileNotFoundException ei){
PrintStream result = null;
try{
result = new PrintStream( new File(fileName));
}catch(FileNotFoundException eo){die("Can't open " + fileName);}
return result;
}
die("The file " + fileName + " already exists!");
return null;
}
public static String check(String line){
int change = 0;
String sex;
int age;
Scanner sin = new Scanner(line);
if(!sin.hasNext()){return null;}
if(sin.next().equalsIgnoreCase("Comment")){return null;}
Scanner sin2 = new Scanner(line);
while(sin2.hasNext()){
change++;
if(change % 2 == 0){}
else{
sex = sin2.next();
if(!sex.equals("M")&& !sex.equals("F")){return "Gender must be 'M' or 'F', not " + sex;}
if(!sin2.hasNext()){return "No data after " + sex ;}
if(!sin2.hasNextInt()){return "age must be a number not " + sin2.next();}
age = sin2.nextInt();
//System.out.print(sex + " " + age + " ");
}
}
System.out.println();
return null;
}
public static void gather(String line, int[] count, int[] total){
int change = 0;
Scanner sin = new Scanner(line);
if(!sin.hasNext()){return ;}
if(sin.next().equalsIgnoreCase("Comment")){return;}
Scanner sin2 = new Scanner(line);
while(sin2.hasNext()){
change++;
if(change % 2 == 0){}
else{
String sex = sin2.next();
int age = sin2.nextInt();
if(sex.equals("M") && age > 17){
count[adultMale]++;
count[adult]++;
count[people]++;
total[adultMale]+= age;
total[adult]+= age;
total[people]+= age;}
else if(sex.equals("M") && age <= 17){
count[child]++;
count[people]++;
count[childMale]++;
total[child]+= age;
total[people]+= age;
total[childMale]+= age;}
else if(sex.equals("F") && age > 17 ){
count[adult]++;
count[adultFemale]++;
count[people]++;
total[adult]+= age;
total[adultFemale]+= age;
total[people]+= age;}
else if(sex.equals("F") && age <= 17){
count[childFemale]++;
count[child]++;
count[people]++;
total[childFemale]+= age;
total[child]+= age;
total[people]+= age;}
}
}// while
count[family]++;
}
public static void showCensus(PrintStream out, int[] count, int[] total){
out.println("The Family Statistics 2013 Report");
out.println();
out.println("People: " + count[people] + " Average Age: " + (float)total[people]/count[people]);
out.println(" Adults: " + count[adult] + " Average Age: " + (float)total[adult]/count[adult]);
out.println(" Males: " + count[adultMale] + " Average Age: " + (float)total[adultMale]/count[adultMale]);
out.println(" Females: " + count[adultFemale] + " Average Age: " + (float)total[adultFemale]/count[adultFemale]);
out.println(" Children: " + count[child] + " Average Age: " + (float)total[child]/count[child]);
out.println(" Males: " + count[childMale] + " Average Age: " + (float)total[childMale]/count[childMale]);
out.println(" Female: " + count[childFemale] + " Average Age: " + (float)total[childFemale]/count[childFemale]);
out.println("Families: " + count[family] + " Average Family Size " + (float)count[family]/count[people]);
}
}//Reader
Your class Reader is defined in the reader package. You need to give the JVM the proper class path. Create a folder called reader and place your class there. Then use the -classpath flag when call java.
c:\>javac reader\Reader.java
c:\>java -classpath . reader.Reader