Printing out student averages with file input using string tokenizer and scanner - java

I am trying to get the averages of values in a text file. The content of the file is:
Agnes 56 82 95 100 68 52
Bufford 87 92 97 100 96 85 93 77 98 86
Julie 99 100 100 89 96 100 92 99 68
Alice 40 36 85 16 0 22 72
Bobby 100 98 92 86 88
I have to skip the names, and try to sum the values of the integers of each line. The ouput should be something like this:
Agnes, average = 76
Bufford, average = 91
Julie, average = 94
Alice, average = 39
Bobby, average = 93
My problem is that i am unable to sum the values (using sum+=sc1.nextInt()). I also cant count the number of tokens of just the integers. For example, for the first line I need countTokens to equal 6, but i get 7, even after I skip the name.
import java.io.*;
import java.util.*;
public class studentAverages
{
public static void main() throws IOException
{
Scanner sf = new Scanner(new File("C:\\temp_Name\\StudentScores.in"));
int maxIndex = -1;
String text[] = new String[100];
while(sf.hasNext( ))
{
maxIndex++;
text[maxIndex] = sf.nextLine();
}
sf.close();
int sum=0;
int avg=0;
int divisor=0;
for (int i=0;i<=maxIndex; i++)
{
StringTokenizer sc= new StringTokenizer(text[i]);
Scanner sc1= new Scanner (text[i]);
while (sc1.hasNext())
{
sc1.useDelimiter(" ");
sc1.skip("\\D*");
System.out.print(sc1.nextInt());
System.out.println(sc1.nextLine());
sum+=sc1.nextInt(); // trying to sum all the numbers in each line, tried putting this line everywhere
avg=sum/divisor;
break;
}
System.out.println(avg);
while (sc.hasMoreTokens())
{
divisor=sc.countTokens()-1; //Not able to count tokens of just the numbers, thats why I am using -1
//System.out.println(divisor);
break;
}
}
//this is for the output
/*for (int i=0; i<=maxIndex; i++)
{
String theNames="";
Scanner sc= new Scanner (text[i]);
theNames=sc.findInLine("\\w*");
System.out.println(theNames + ", average = ");
}*/
}
}

I would recommend splitting each line using the split method and then looping through those values while ignoring the first, because you know that is the title.
public static void main() throws IOException {
Scanner sf = new Scanner(new File("C:\\temp_Name\\StudentScores.in"));
int maxIndex = -1;
String text[] = new String[100];
while(sf.hasNext( )) {
maxIndex++;
text[maxIndex] = sf.nextLine();
}
sf.close();
for(int i = 0; i < maxIndex; i ++) {
String[] values = text[i].split(" ");
String title = values[0];
int sum = 0;
for(int j = 1; i < values.length; j ++) {
sum += Integer.parseInt(values[j]);
}
double average = sum / (values.length - 1);
System.out.println(title + ": " + average);
}
}
Notice that the inner loop's index begins at 1 and not 0, and that when calculating the average, we subtract one from the size of the values array because we want to ignore the title.

Try this one:
Scanner scanner = new Scanner(new File("resources/abc.txt"));
//check for next line
while (scanner.hasNextLine()) {
//create new scanner for each line to read string and integers
Scanner scanner1 = new Scanner(scanner.nextLine());
//read name
String name = scanner1.next();
double total = 0;
int count = 0;
//read all the integers
while (scanner1.hasNextInt()) {
total += scanner1.nextInt();
count++;
}
System.out.println(name + ", average = " + (total / count));
}
scanner.close();
output:
Agnes, average = 75.5
Bufford, average = 91.1
Julie, average = 93.66666666666667
Alice, average = 38.714285714285715
Bobby, average = 92.8
--EDIT--
Here is the code as per your last comment (I have to use StringTokenizer`/string methods like useDelimiter, skip, etc to arrive at the answer)
Scanner sf = new Scanner(new File("resources/abc.txt"));
List<String> text = new ArrayList<String>();
while (sf.hasNext()) {
text.add(sf.nextLine());
}
sf.close();
for (String str : text) {
StringTokenizer sc = new StringTokenizer(str, " ");
double sum = 0;
int count = 0;
String name = sc.nextToken();
while (sc.hasMoreElements()) {
sum += Integer.valueOf(sc.nextToken());
count++;
}
System.out.println(name + ", average = " + (sum / count));
}
}
output
Agnes, average = 75.5
Bufford, average = 91.1
Julie, average = 93.66666666666667
Alice, average = 38.714285714285715
Bobby, average = 92.8

Related

File reader finding the average of the values from a txt file of the rows and columns without using arrays

I am given a txt file 7x3 grid of values and I'm supposed to find the average of each rows (7) and columns (3) without using arrays. The professor has guided us to printing the grid out but I'm not sure what to do next.
public static void main (String [] args){
try{
File file = new File("Cal.txt");
Scanner scanFile = new Scanner(file);
for (int i = 0; i < 7; i++){
String string = scanFile.nextLine();
System.out.println(string);
}
}catch(Exception e) {
System.out.println("Error occured...");
}
}
The grid:
40.0 30 10
25 76 1120
0 1301 1823
630 300 1000
102 1100 1900
982 200 239
200 720 100
You can use scanner.hasNextFloat() to check whether the next token is a float and scanner.nextFloat() to read the next float from the file. That way the average of all the values could be calculated like this:
public static void main (String [] args){
try{
File file = new File("Cal.txt");
Scanner scanner = new Scanner(file);
int count = 0;
float sum = 0.0f;
while(scanner.hasNextFloat()) {
float val = scanner.nextFloat();
count++;
sum += val;
}
float average = sum / count;
System.out.println("average: " + average);
scanner.close();
}catch(Exception e) {
System.out.println("Error occured...");
}
}

Receive average scores and check the number of scores in a range | Java

Write a java program that reads the grades of 10 students, which is from 1 to 100, from the entrance, specifying that the scores of some people are from 90 to 100, some people are from 60 to 89 and some people are from 1 to 59. The program should print the average scores at the end.
This is code for average, how can i add else and if or while to review how much numbers are in range 1 to 59 or 60 to 89 or 90 to 100?
import java.util.Scanner;
public class EhsanNp {
public EhsanNp() {
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new EhsanNp();
}
}
You can simply add three variables which store the number of grades between 1 to 59, 60 to 89 and 90 to 100 and increment them in the for loop. For example:
import java.util.Scanner;
public class EhsanNp {
int lowGrades;
int middleGrades;
int highGrades;
public EhsanNp() {
lowGrades = 0;
middleGrades = 0;
highGrades = 0;
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
if (Integer.parseInt(arr[i]) >= 1 && Integer.parseInt(arr[i]) <= 59) {
lowGrades++;
}
else if (Integer.parseInt(arr[i]) >= 60 && Integer.parseInt(arr[i]) <= 89) {
middleGrades++;
}
else {
highGrades++;
}
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new EhsanNp();
}
}
Then you can do whatever you want with the variables like displaying them for example.

How to get average of test scores organized into columns in a file?

The file contains the data in the following format:
Name|Test1|Test2|Test3|Test4|Test5|Test6|Test7|Test8|Test9|Test10
John Smith|82|89|90|78|89|96|75|88|90|96
Jane Doe|90|92|93|90|89|84|97|91|87|91
Joseph Cruz|68|74|78|81|79|86|80|81|82|87
Suzanne Nguyen|79|83|85|89|81|79|86|92|87|88
I am trying to find out how to get the sum of each column (Ex. Test 1 = 82 + 92 + 68 + ...) to ultimately calculate the average score for each test.
This is how I parsed the file and did the other calculations:
public class TestAverages
{
private static int[] grades;
private static int[] testTotal;
private static int N;
private static double classTotal;
public static void main(String[] args) throws FileNotFoundException
{
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException
{
TestAverages t = new TestAverages();
in.nextLine(); //skips the first line of text in file (labels)
double classAvg =0.0;
while(in.hasNextLine())
{
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
N = grades.length;
for(int i = 0; i < N; i++)
{
grades[i] = Integer.parseInt(data[i + 1]);
}
System.out.println(name);
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
classAvg = t.getClassAvg(grades);
System.out.println("Test Average: " + t.getTestAvg(grades) + "%\n");
}
System.out.printf("\nClass Average: %.2f%%\n", classAvg );
}
public double getStudentAvg(int[] grades)
{
double total = 0.0;
double avg = 0.0;
int N = grades.length;
for(int i = 0; i < N; i++){
total += grades[i];}
avg = total / N;
return avg;
}
public double getClassAvg(int[] grades)
{
double classTotal = getStudentAvg(grades) / N;
double classAvg =0.0;
classTotal += classTotal;
classAvg = classTotal;
return classTotal;
}
}
Please excuse my formatting if it's not up to par to the standard.
My main issue at the moment is how to extract the score for each test for each student and add everything up.
The test scores for each student are being calculated. What you need are the class average and the test average.
The test averages are the average scores on each test.
The student averages are the average test scores for each student
The class averages is how the overall class did on all the tests.
Consider three tests
test1 test2 test3 student average
student1 90 80 70 240/3
student2 100 90 90 280/3
student3 80 80 90 250/3
testAvg 270/3 250/3 250/3
class avg = (270 + 250 + 250)/9 or (240+280+250)/9
So you need to read in the values in such a way so as to facilitate making the other calculations. I would recommend either a Map<String,List<Integer>> for the data where the string is the students name and the list is the test scores for each student. Or you could use a 2D int array. But you need to save the scores so you can do the column average for the test scores. Most of the work is done.
Also, two problems I noticed. You call the method getTestAvg but don't declare it and you declare the method getClassAvg but never call it.
if you already know that there are 10 test total in the file , it should be easy .
you can let int[] testTotal = new int[10]; for testTotal[0] = sum-of-first-column , testTotal[1] = sum-of-second-column and so on . . .
you can read each line in and split them with "\\|" as regex
as you are cycling through lines , let testTotal[0] += data[1] , testTotal[1] += data[2] . . . testTotal[9] += data[10] since data[0] is the name of the student .

Fibonnaci sequence java with limit value

I need help with my java-program. This program is supposed to ask for the highest value fibonacci can have, and print out the number of series up to that value, but it doesn't work. Any suggestions?
import java.util.Scanner;
public class Fibonacci {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("The largest number fibonacci can be: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
}
int i;
int f0 = 0;
int f1 = 1;
int fn;
int value=0;
for (i = 0; i<=value; i++){
fn = f0 + f1;
System.out.println("Fibonacci-number " + i + " = " + f0);
f0 = f1;
f1 = fn;
value = number - f0;
}
}
}
If i put in number = 12, the program is supposed to print:
fibonacci-number 0 = 0
...
fibonnaci-number 12 = 144
Just change the loop to compare value of increment-er (i) to 'number ' variable
for (i = 0; i<=number; i++){
//.........
}
Also use double instead of int if you want to print higher number in the series correctly.
There is no use of the 'value' variable.
Also, the phrase 'the highest value fibonacci can have' is misleading.You have mentioned number denotes number of terms in the series in your example.
If you want 'number' to be the highest value in the series, use following approach,
do{
fn = f0 + f1;
System.out.println("Fibonnaci-tall " + i + " = " + f0);
f0 = f1;
f1 = fn;
i++;
}while(f0<=number);
Is this what you are looking for?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int f0 = 0;
int f1 = 1;
int fn = 0;
System.out.println("The largest number fibonnaci can be: ");
System.out.println("Input your number: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
} else {
System.out.println(f0);
System.out.println(f1);
while (fn < number){
fn = f0 + f1;
f0 = f1;
f1 = fn;
if (fn < number){
System.out.println(fn);
}
}
}
}
enter image description here
Use this program, it will solve your query.
Try this...It works!
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("The largest number fibonacci can be: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
}
else{
int i=0;
int f0 = 0;
int f1 = 1;
int fn;
int value=0;
do{
//for (i = 0; i<=value; i++){
fn = f0 + f1;
System.out.println("Fibonacci-number " + i + " = " + f0);
f0 = f1;
f1 = fn;
value = number - f0;
i++;
}while(f0<=number);
}//else
}

Java Loop Confusion

I wrote this code that was intended to read a file with integer values. If the integer values are >= 0 and <=100 I need to give the average of the grades. If there are any values out of the specified range 0-100 then I need to count the incorrect integer grades, inform the user of the incorrect grades, and inform how many incorrect grades there were. I attempted the code but I keep getting the error code:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Project9.main(Project9.java:26)
Code sample:
public static void main(String[] args) throws IOException{
String file;
int readInts;
Scanner k = new Scanner(System.in);
System.out.println("Enter filename: ");
file = k.nextLine();
int counterWrong = 0;
int counterRight = 0;
int sum = 0;
double average = 1.0 * sum/counterRight;
File fileReader = new File(file);
if (fileReader.exists()) {
Scanner input = new Scanner(fileReader);
while (input.hasNext()) {
readInts = input.nextInt();
System.out.println(readInts);
String a = input.next();
int a2 = Integer.parseInt(a);
if (a2 <= 100 && a2 >= 0){
counterRight++;
sum = sum + a2;
System.out.println("Score " + a2 + " was counted.");
} else {
counterWrong++;
System.out.println("The test grade " + a2 + " was not scored as it was out of the range of valid scores.");
System.out.println("There were " + counterWrong + " invalid scores that were not counted.");
}
}
if (counterRight > 0){
System.out.println("The average of the correct grades on file is " + average + ".");
}
} else {
System.out.println("The file " + file + " does not exist. The program will now close.");
}
}
}
You are doing a single check hasNext but then you read twice from scanner using nextInt() and next().
There may be two issues with your code I see.
file = k.nextLine(); // Depending on how your file is set up k.nextLine() or k.next() or maybe k.nextInt() may be useful.
while (input.hasNext()) {
readInts = input.nextInt(); // input.hasNext() assumes the next value the scanner is reading has a string value which would make readInts = input.nextInt(); impossible to use without parsing (or some other method).
I thought it'd be fun to try out this exercise (didn't want to ruin it for you). Check out my code and hopefully you'll pick up on some of the concepts I was talking about.
Note: My program reads integer values like 95 185 23 13 90 93 37 125 172 99 54 148 53 36 181 127 85 122 195 45 79 14 19 88 34 73 92 97 200 167 126 48 109 38. Which uses hasNext() & next() to get every token listed. So using nextLine() wouldn't be useful for the given input.
package cs1410;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Grader {
public static void main(String[] args) throws IOException {
int count = 0;
int sum = 0;
double ave = 0;
int incorrectCount = 0;
String correctGrades = "";
String incorrectGrades = "";
// Read file input
JFileChooser chooser = new JFileChooser();
if (JFileChooser.APPROVE_OPTION != chooser.showOpenDialog(null)) {
return;
}
File file = chooser.getSelectedFile();
// Scan chosen document
Scanner s = new Scanner(file);
// While the document has an Int
while (s.hasNextInt()) {
// Convert our inputs into an int
int grade = Integer.parseInt(s.next());
if (grade >= 0 && grade <= 100) {
// adds sum
sum += grade;
// increments correct count
count++;
// displays valid grades
correctGrades += Integer.toString(grade) + "\n";
} else {
// increments incorrect count
incorrectCount++;
// displays invalid grades
incorrectGrades += Integer.toString(grade) + "\n";
}
}
// Created average variable
ave = sum / count;
// bada bing bada boom
System.out.println("The number of correct grades were " + correctGrades);
System.out.println("The average score on this test was " + ave + "\n");
System.out.println("The number of incorrect grades were " + incorrectCount + "\n");
System.out.println("The incorrect values for the grades were " + "\n" + incorrectGrades);
}
}
Use hasNextInt() instead of hasNext().
hasNext() only means there is another token, not necessarily that there is another integer which you are assuming when you wrote nextInt().
Here's the documentation for hasNext() and hasNextInt()
You also want to do a check before this line:
String a = input.next();

Categories

Resources