I am stuck when writing a Java program. I have to calculate the grade of 121 students and store them in an array for later use. But the array I created does not have the values from the for loop.
public class GradeCalculator{
public static void main(String[] args){
File grade = fileName();
int lines = getNumEntries(grade);
print(grade, lines);
}
public static File fileName(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the name of the grade file");
String fileName = scan.nextLine();
File file = new File(fileName);
while(!file.exists()){
System.out.println("your input file does not exist");
fileName = scan.nextLine();
file = new File(fileName);
}return file;
}
public static int getNumEntries(File fln){
File file = fln;
int count = 0;
try{
Scanner input = new Scanner (fln);
while(input.hasNextLine()){
count++;
input.nextLine();
}
}catch(FileNotFoundException e) {
System.out.println("File not found");
System.exit(0);
}return count;
}
public static void print(File fln, int values)throws NoSuchElementException{
File file = fln;
int []a = new int [values];
try{
Scanner input = new Scanner(file);
for(int i=0; i<=a.length; i++){
while(input.hasNextDouble()){
double Lab = input.nextDouble();
double A1 = input.nextDouble()/10*4;
double A2 = input.nextDouble()/10*4;
double A3 = input.nextDouble()/10*4;
double A4 = input.nextDouble()/10*4;
double A5 = input.nextDouble()/10*4;
double A6 = input.nextDouble()/10*4;
double A7 = input.nextDouble()/10*4;
double Midterm1 = input.nextDouble()/20*15;
double Midterm2 = input.nextDouble()/35*15;
double Final = input.nextDouble()/110*37;
a[i]= (int)(Lab+A1+A2+A3+A4+A5+A6+A7+Midterm1+Midterm2+Final);
System.out.println(a[i]); //If I put the println here the values are correct
}
}
}catch(FileNotFoundException e){
System.out.println("File not found");
}System.out.println(a[i]); //If I put the println here the values are different
}
}
You consume all of your input in the inner while loop on the first iteration of the outer for loop. Also, you are repeatedly setting a[0] to the grade instead of each and every index possible within the array. Then your for loop finishes and you have an array like:
{lastGrade, 0, 0, 0, ..., 0}
Basically, you need to get rid of the while loop. There may be other problems as well.
Related
so i just fixed an error then following that i got the exception error and not sure what to change to fix it.
i've looked at similar issues but none of them seemed to pertain to my specific problem.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class AAAAAA {
public static void main (String[] args)throws IOException {
final String fileName = "classQuizzes.txt";
//1)
Scanner sc = new Scanner(new File(fileName));
//declarations
String input;
double total = 0;
double num = 0;
double count = 0;
double average = 0;
String lastname;
String firstname;
double minimum;
double max;
//2) process rows
while (sc.hasNextLine()) {
input = sc.nextLine();
System.out.println(input);
//find total
total += Double.parseDouble(input); //compile error on using input
count++;
System.out.println(count); //test delete later
//find average (decimal 2 points)
System.out.println("hi"); //test
average = (double)total / count;
System.out.println("Average = " + average);
//3) class statistics
}
}
}
It's actually a runtime exception not a compile error.
The reason is because your Scanner is reading through the whole file, line by line, and is hitting something that cannot be parsed as a double.
// for each line in the file
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
// split the line into pieces of data separated by the spaces
String[] data = line.split();
String firstName = null;
String lastName = null;
// get the name from data[]
// if the array length is greater than or equal to 1
// then it's safe to try to get something from the 1st index (0)
if(data.length >= 1)
firstName = data[0];
if(data.length >= 2)
lastName = data[1];
// what is the meaning of the numbers?
// get numbers
Double d1 = null;
if(data.length >= 3){
try {
d1 = Double.valueOf(data[2]);
} catch (NumberFormatException e){
// couldn't parse the 3rd piece of data into a double
}
}
Double d2 = null;
// do the same...
// do something with 'firstName', 'lastName', and your numbers ...
}
My Issue is that this code does not return and values when I call it.
I need to to read a set of values from another txt file and print out the answers.
Then I need to be able to have it print to another empty text file.
The values in the txt file is (without space in-between lines):
1 2 3 4 5 6
4 5 6
7.5 8.5 9
8.1 9.2 10.3
The source code as follows:
public class Lab5d {
public static void main(String args[]) {
// Scan the input
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
Scanner lineScan = new Scanner(line);
// Process each line separately
// If the next token is a double, assume there is an input line
while (scan.hasNextDouble()) {
processLine(line);
}
}
public static void processLine(String line) {
Scanner scan = new Scanner(System.in);
Scanner lineScan = new Scanner(line);
double a = lineScan.nextDouble();
double sum;
double product;
double count;
double average;
sum = 0;
count = 0;
product = 1;
while (lineScan.hasNext()) {
sum = sum + a;
product = product * a;
++count;
}
double ave = sum / count;
System.out.printf("sum= %.1f, product= %.1f, ave= %.1f, count= %.1f%n", sum, product, ave, count);
}
}
Can anyone help?
You're not reading the file in. Use the file path as a parameter for the Scanner object.
It can be two cases, you can either read values from a file or values from a command line.
First a main method look:
public static void main(String args[]) {
// Scan the input
processSystemIn();
// San the file
processFile("resource/values.txt");
}
The values.txt is following the format you presented in your question.
And read a value line by line using a hasNextLine method of a Scanner class then, use an another scanner instance for the each number from the line input.
case 1: A processSystemIn method with System.in
private static void processSystemIn() {
Scanner scanner = new Scanner(System.in);
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine(line);
}
scanner.close();
}
case 2: A processFile method with file.
private static void processFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
The processLine method is a little bit different with yours.
With a hasNextDouble method, you can get a value.
See the method as follows:
public static void processLine(String line) {
Scanner lineScan = new Scanner(line);
double a;;
double sum;
double product;
double count;
double average;
sum = 0;
count = 0;
while(lineScan.hasNextDouble())
{
a = lineScan.nextDouble();
product = 1;
sum += a;
product *= a;
++count;
average = sum / count;
System.out.printf("sum= %.1f, product= %.1f, ave= %.1f, count= %.1f%n", sum, product, average, count);
}
lineScan.close();
}
The result is here:
Does this result meet your expectation?
I hope this helps.
I am trying to create the below method to read the "studentmarks.txt" file. However, I cannot get students marks to be read as an int such as 65 60 52 and stored into an Array. It keeps outputing the error "java.util.InputMismatchException null". How would I go about fixing this without altering the format of the "studentmarks.txt" file? Thank you!
public void readMarksData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
String nameOfCohort = scanner.nextLine(); //1
System.out.println(nameOfCohort);
int noOfMarks = scanner.nextInt(); //2
System.out.println(noOfMarks);
scanner.nextLine();
while( scanner.hasNext() )
{
scanner.useDelimiter("[,\n]");
String name = scanner.next(); //3
System.out.println(name);
// int marks[] = new int[3];
// for(int i = 0 ; i <= 3 ; i++)
// {
// marks[i] = scanner.nextInt();
// }
int marks[] = new int[100];
int markOne = scanner.nextInt(); //4 java.util.InputMismatchException null
marks = new int[markOne];
System.out.println(markOne);
scanner.nextLine();
int markTwo = scanner.nextInt(); //5
marks = new int[markTwo];
scanner.nextLine();
int markThree = scanner.nextInt(); //6
marks = new int[markThree];
scanner.nextLine();
//
//System.out.println(markOne + " " + markTwo + " " + markThree);
}
scanner.close();
}
studentmarks.txt:
CS1 Group 2
3
Andreas Antoniades
65 85 77
Charlotte Brocklebank
87 93 81
suzanne dawson
0 55 42
StudentRecord Class:
public class StudentRecord
{
private String name;
private String noOfMarks;
private int[] marks;
public StudentRecord(String name)
{
marks = new int[24];
this.name = name;
}
int result = Integer.parseInt(number);
You can use the parseInt(String val) method to parse a string value of 65 to an integer value and the store that in an array
I'm trying to read integers from a .txt file and I get this error directly after input even though the while loop contains hasNextInt to make sure there is another integer in the file to read.
import java.util.Scanner;
import java.io.*;
public class Part2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String prompt = ("Please input the name of the file to be opened: ");
System.out.print(prompt);
String fileName = input.nextLine();
input.close();
Scanner reader = null;
try{
reader = new Scanner(new File(fileName));
}
catch(FileNotFoundException e){
System.out.println("--- File Not Found! Exit program! ---");
}
int num = 0;
while(reader.hasNextInt()){
reader.nextInt();
num++;
}
int[] list = new int[num];
for(int i = 0; i<num; i++){
list[i] = reader.nextInt();
}
reader.close();
System.out.println("The list size is: " + num);
System.out.println("The list is:");
print(list);//Method to print out
}//main
}//Part2
This is because in while loop , you have reached the end of the file.
while(reader.hasNextInt()){
reader.nextInt();
num++;
}
try to reinitialize it again after the while loop.
reader = new Scanner(new File(fileName));
I think it's better to use List like
List list = new ArrayList();
int num = 0;
while(reader.hasNextInt()){
list.add(reader.nextInt());
num++;
}
/* this part is unnecessary
int[] list = new int[num];
for(int i = 0; i<num; i++){
list[i] = reader.nextInt();
}
*/
//then
System.out.print(list);
I have to write a program that reads in a sequence of integers until 'stop' is entered, store the integers in an array and then display the average of the numbers entered. I'm getting an input mismatch exception when entering 'stop' so it doesn't really work, but I have no idea why. Help would be greatly appreciated.
import java.util.Scanner;
public class MeanUsingList {
public void mean() {
String s;
int n = 0;
int i = 1;
int[] array = { n };
do {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt();
s = in.nextLine();
} while (s != "stop");
{
System.out.println("Enter an integer");
Scanner in2 = new Scanner(System.in);
int x = in2.nextInt();
array[i] = x;
i++;
}
int av = 0;
for (int y = 0; y < array.length; y++) {
av += array[y];
}
System.out.println(av);
}
public static void main(String[] args) {
MeanUsingList obj = new MeanUsingList();
obj.mean();
}
}
First int[] array = { n }; just creates an array with 0 as the element in it.
the logic inside it will never execute while (s != "stop");
You want something like this
List list = new ArrayList();
//instead of array used arraylist because of dynamic size
do {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt(); //get the input
list.add(n); // add to the list
Scanner ina = new Scanner(System.in); // need new scanner object
s = ina.nextLine(); //ask if want to stop
} while (!s.equals("stop")); // if input matches stop exit the loop
System.out.println(list); // print the list
I recommend you to learn the basics