For each student read from the file, output the following information:
Student Number (line number from the file, 1 to N)
Student Name (last name, a comma, and first name)
Student Athlete
Output Yes or No(Athlete Flag (Y = is an athlete, N = is not an athlete)
Eligibility-- Output either Yes or No --(Rule: If student is an athlete, their letter grade must be a “C” or higher to be eligible to play in the big game)
**this is how the text file looks:
Smith Richard N 87 98 59 77 77 92 86
Johnson Daniel Y 73 56 83 82 69 72 61
Williams David N 60 70 91 56 70 71 77
Jones Carol N 88 85 76 68 61 84 98
Brown James Y 67 91 62 73 74 83 94
Davis Dorothy N 96 60 97 58 82 100 89
Miller Jeff N 80 74 74 68 64 90 87
Wilson William N 61 83 96 59 67 68 60
Moore Betty N 65 59 93 86 72 80 73
Taylor Helen N 94 77 83 68 80 60 73
Anderson Sandra N 78 94 91 95 88 70 75
Each Row of the Text File Contains:
• Student Last Name
• Student First Name
• Athlete Flag (Y = is an athlete, N = is not an athlete)
• Grade on Quiz 1
• Grade on Quiz 2
• Grade on Quiz 3
• Grade on Quiz 4
• Grade on Quiz 5
• Grade on Test 1
• Grade on Test 2
This is i have written so far,
import java.io.*;
import java.util.*;
public class Assignment3
{
public static final void main(String args[]) throws FileNotFoundException
{
System.out.println("my name!");
Scanner myScanner = new Scanner(new File("students.txt"));
String firstName = myScanner.next();
String lastName = myScanner.next();
String athlete=myScanner.next();
int lineNumber =1;
while (myScanner.hasNextLine())
{
if(myScanner.hasNextLine())
{
myScanner.nextLine();
}
System.out.println(lineNumber + " "+ lastName + ", "+ firstName +
athlete);
String firstName = myScanner.next();
String lastName = myScanner.next();
String athlete=myScanner.next();
lineNumber++;
}
}
}
I am really new to java. can anyone help please?
You can try for this code snippet, I didn’t get your question properly. But it's better to use BufferedReader instead of Scanner
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Assignment3 {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\students.txt"))) {
String line;
int lineNumber = 1;
while ((line = br.readLine()) != null) {
System.out.println(line);
String[] words = line.split(" ");
if (words.length <= 1) {
continue;
}
String studentNumber = ""+ lineNumber++;
String studentName = words[1]+","+words[0];
String studentAthlete = words[2];
boolean eligibility = false;
if(studentAthlete.equals("Y")){
int totalMarks = 0;
int subject = words.length-3;
for (int i = 3; i < subject; i++) {
totalMarks+= Integer.parseInt(words[i]);
}
int marksGrade = totalMarks/subject;
// now you can check the grade
if(marksGrade<50){
eligibility = true;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
This question already has answers here:
Reading only the integers from a txt file and adding the value up for each found
(5 answers)
Closed 5 years ago.
I'm working on a project that reads in grades from a file but the file contains student names and the class they are in as well, some have 3 grades and some have 4. I'm struggling with getting a divide by 0 error when I try to run the program and cant figure it out after much googling, beginner with java. I'm fine with opening the file but I'm struggling with how to get it to read the average of the first line then continue to all the other ones as well returning the value in the println.
File contents(with three grades):
//Happy CS145 81 85 91
//Sneezy CS145 67 75 75
//Doc CS145 92 97 89
//Dopey CS111
//Grumpy CS145 75 65 66
//Bashful CS145 81 82 81
//Sleepy CS145 71 74 71
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]){
int numTestScores = 0;
int sum = 0;
int average = 0;
Scanner input = null;
try {
input = new Scanner(new File("PA2data2.txt"));
} catch (FileNotFoundException ex) {
System.out.println("Cannot open file - " + ex);
}
while (input.hasNext()) {
while (input.hasNextInt()){
sum += input.nextInt();
numTestScores++;
}
average = sum / numTestScores;
System.out.println(average);
}
System.out.println("Average is " + sum / numTestScores);
input.close();
}
}
You should use nextLine() rather than nextInt()
while (input.hasNext()) {
String line = input.nextLine();
String[] brokenLine = line.split(" ");
//do stuff with your array of {Happy, CS145, 81, 85, 91}
...
...
}
Also, your also going to want to use doubles rather than int for average, you will get average of 0 otherwise.
Just keep your division operation inside an if statement:
if(numTestScores > 0) {
average = sum / numTestScores;
System.out.println(average);
}
The method returns some null skipping some objects.The goal of the method is to return sorterd list of people according to their 'midterm' and 'final' ('midterm' of a person is immediately followed by his 'final') Could smb please help to fix it? Here's the code
public static Exam[] collateExams(Exam[] exams)
{
Exam[] r = new Exam[exams.length];
int index = 0;
for (int i = 0; (i < exams.length) && (index < exams.length/2); i++)
{
if (exams[i].getExamType() == 'm')
{
r[index*2] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), "midterm", exams[i].getScore());
for(int j = 0; (j < exams.length) && (index < exams.length/2); j++)
{
if((exams[j].getExamType() == 'f') && (exams[i].getID() == exams[j].getID()))
{
r[index*2 + 1] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), "final", exams[i].getScore());
}
}
}
index++;
}
return r;
here's the output:
null
null
Bill Gates 6 midterm 90
Bill Gates 6 final 90
James Gosling 3 midterm 100
James Gosling 3 final 100
Sergey Brin 22 midterm 98
null
Dennis Ritchie 5 midterm 94
Dennis Ritchie 5 final 94
Steve Jobs 9 midterm 95
Steve Jobs 9 final 95
Here's the unsorted list which is passed as a parameter:
Steve Jobs 9 final 91
Bill Gates 6 midterm 90
James Gosling 3 midterm 100
Sergey Brin 22 midterm 98
Dennis Ritchie 5 midterm 94
Steve Jobs 9 midterm 95
Dennis Ritchie 5 final 100
Jeff Dean 7 midterm 100
Bill Gates 6 final 96
Jeff Dean 7 final 100
Sergey Brin 27 final 97
James Gosling 3 final 100
Either your entire class is posting the same question, or you are Joshua mark II. Now, other variations said only one for loop and other restrictions, so I am going to ignore all of that and address the messed up double loop above. This will fix the loop above:
public static Exam[] collateExams(Exam[] exams)
{
Exam[] r = new Exam[exams.length];
int index = 0;
for (int i = 0; i < exams.length ; i++)
{
if (exams[i].getExamType() == 'm')
{
r[index*2] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), 'm', exams[i].getScore());
for(int j = 0; j < exams.length; j++)
{
if((exams[j].getExamType() == 'f') && (exams[i].getID() == exams[j].getID()))
{
r[index*2 + 1] = new Exam(exams[j].getFirstName(), exams[j].getLastName(), exams[j].getID(), 'f', exams[j].getScore());
}
}
index++;
}
}
return r;
}
Output:
Sorted list:
Exam [fn=Bill, ln=Gates, id=6, ex=m, score=90]
Exam [fn=Bill, ln=Gates, id=6, ex=f, score=96]
Exam [fn=James, ln=Gosling, id=3, ex=m, score=100]
Exam [fn=James, ln=Gosling, id=3, ex=f, score=100]
Exam [fn=Dennis, ln=Ritchie, id=5, ex=m, score=94]
Exam [fn=Dennis, ln=Ritchie, id=5, ex=f, score=100]
Exam [fn=Steve, ln=Jobs, id=9, ex=m, score=95]
Exam [fn=Steve, ln=Jobs, id=9, ex=f, score=91]
Exam [fn=Jeff, ln=Dean, id=7, ex=m, score=100]
Exam [fn=Jeff, ln=Dean, id=7, ex=f, score=100]
Exam [fn=Sergey, ln=Brin, id=22, ex=m, score=99]
Exam [fn=Sergey, ln=Brin, id=22, ex=f, score=97]
These items which show null are never initialized thats why..
public class Example2 {
String array[] = new String[15];
public Example2(){
for(int j=0; j<array.length-1; j++)
array[j]="j";
for(int j=0; j<array.length; j++)
System.out.println(array[j]);
}
public static void main(String[] args){
new Example2();
}
}
This example will print 14 ("J") and one null.Why? cause array[15] is not initialized.
So on your example with i am sure that these items show null cause are never initialized.
[EDITED] #Michael, your code is giving me this output with only one null:
Sorted list:
Bill Gates 6 midterm 90
Bill Gates 6 final 96
James Gosling 3 midterm 100
James Gosling 3 final 100
Sergey Brin 22 midterm 98
null
Dennis Ritchie 5 midterm 94
Dennis Ritchie 5 final 100
Steve Jobs 9 midterm 95
Steve Jobs 9 final 91
Jeff Dean 7 midterm 100
Jeff Dean 7 final 100
Here's the Exam class which has toString method:
class Exam {
private String firstName;
private String lastName;
private int ID;
private String examType;
private int score;
public Exam(String firstName, String lastName, int ID, String examType, int score)
{
this.firstName = firstName;
this.lastName = lastName;
this.ID = ID;
this.examType = examType;
this.score = score;
}
public String getFirstName()
{
return this.firstName;
}
public String getLastName()
{
return this.lastName;
}
public int getID()
{
return this.ID;
}
public char getExamType()
{
char examTypeCasted = 0;
examTypeCasted = examType.charAt(0);
return Character.toUpperCase(examTypeCasted);
}
public int getScore()
{
return this.score;
}
public String toString()
{
return this.firstName + " " + this.lastName + " " + this.ID + " " + this.examType + " " + this.score;
}
public boolean equals(Exam e)
{
if(this.equals(e))
return true;
else
return false;
}
}
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
I keep getting this error when reading from a text file it gets the first few numbers but then does this there also shouldnt be 0's in there, tried a lot of things not sure what to do. I have to be able to read the file numbers and then multiply specific ones could use some help thanks. (I was using the final println to check what numbers it was getting). Sorry forgot the error is this output
4
32
0
38
0
38
0
16
0
Error: For input string: ""
Here is my file:
Unit One
4
32 8
38 6
38 6
16 7
Unit Two
0
Unit Three
2
36 7
36 7
Unit Four
6
32 6.5
32 6.5
36 6.5
36 6.5
38 6.5
38 6.5
Unit Five
4
32 6.5
32 8
32 7
32 8
Unit Six
5
38 7
30 6.5
24 8
24 8
24 8
Unit Seven
0
Unit Eight
1
40 12
Unit Nine
5
24 8
24 6.5
30 6.5
24 7
32 7
And here is my code:
package question;
import java.io.*;
import java.util.Scanner;
public class Weight
{
public static void main(String[] args)//main method
{
try
{
Scanner input = new Scanner(System.in);
//System.out.print("Please enter proposed weight of stock : ");
// int proposedWeight = input.nextInt();
File file = new File("MathUnits.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null)
{ int i = 0;
if (strline.contains("Unit"))
{
continue;
}
else {
String[] numstrs = strline.split("\\s+"); // split by white space
int[] nums = new int[numstrs.length];
nums[i] = Integer.parseInt(numstrs[i]);
for(int f = 0; f <numstrs.length; f++)
{
System.out.println(""+ nums[f]);
}
}
i ++;
}
//int x = Integer.parseInt(numstrs[0]);
// int m = Integer.parseInt(numstrs[1]);
// int b = Integer.parseInt(numstrs[2]);
// int a = Integer.parseInt(numstrs[3]);
int a = 0;
// System.out.println("this >>" + x + "," + m +"," + b + "," + a);
// if(proposedWeight < a)
// {
// System.out.println("Stock is lighter than proposed and can hold easily");
// System.exit(0);
// }
// else if ( a == proposedWeight)
// {
// System.out.println("Stock is equal to max");
// System.exit(0);
// }
// else
// {
// System.out.println("stock is too heavy");
// System.exit(0);
// }
in.close();
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
One probable error I see
You're not taking newlines into consideration, especially when you're doing a nums[i] = Integer.parseInt(numstrs[i]); on an empty string
Also, I don't think you're getting the numbers into the array correct since you're getting only one int from each line, when some lines have two
Thank you all very much for your help both answers work Perfectly.
I have a Lab assigment for Java that I need some help with please.
The assignemnt is to Read a txt that has 28 ints and then place them into a 2D Array.
Here is what I have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextFileExample {
public static void main(String[] args) {
String fileName = "TemperatureData.txt";
Scanner inputStream = null;
System.out.println("The file " + fileName + "\ncontains the following lines:\n");
try
{
inputStream = new Scanner(new File("C:\\Users\\username\\Documents\\TemperatureData.txt"));//The txt file is being read correctly.
String line = inputStream.nextLine();
String[] numbers = line.split("");
int[][] temperatures = new int[4][7];
for (int row = 0; row < 4; row++) {
for (int column = 0; column < 7; column++) {
temperatures[row][column] = temperatures.parseInt(temperatures[row][column]);//Is this correct?
}
}
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine();
System.out.println(line);
}
inputStream.close();
}
}
I need some help as to Getting the data from the txt file into the array temperatures[4][7].
Then printout the temperatures array showing the data. The output should be as follow:
Temperature Data
Week 1: 73 71 68 69 75 77 78
Week 2: 76 73 72 72 75 79 76
Week 3: 79 82 84 84 81 78 78
Week 4: 75 72 68 69 65 63 65
He does not required the txt file to be an output.
The txt file is this:
73
71
68
69
75
77
78
76
73
72
72
75
79
76
79
82
84
84
81
78
78
75
72
68
69
65
63
65
temperatures[row][column] = temperatures.parseInt(temperatures[row][column]);
Should be
temperatures[row][column] = Integer.parseInt(line);
Also, delete String[] numbers = line.split(""); as it is not used.
You need to reorder a few more things for this to work. The logic is:
Open file
if filenotfound, quit
loop through your arrays
Parse the string in the file, put it in your array
Now you can do something with the array. Note this does not elegantly handle the case where the file isn't long enough.
String fileName = "TemperatureData.txt";
Scanner inputStream = null;
System.out.println("The file " + fileName + "\ncontains the following lines:\n");
try
{
inputStream = new Scanner(new File("C:\\Users\\username\\Documents\\TemperatureData.txt"));//The txt file is being read correctly.
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
for (int row = 0; row < 4; row++) {
for (int column = 0; column < 7; column++) {
String line = inputStream.nextLine();
int[][] temperatures = new int[4][7];
temperatures[row][column] = Integer.parseInt(line);
}
}
inputStream.close();
Here is a solution:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TxtTo2DArray {
public static void main(String[] args) throws FileNotFoundException, IOException {
String filename = ""; //Here you must write the path to the file f.exp "//folder//file.txt"
try{
FileReader readConnectionToFile = new FileReader(filename);
BufferedReader reads = new BufferedReader(readConnectionToFile);
Scanner scan = new Scanner(reads);
int[][] temperatures = new int[4][7];
int counter = 0;
try{
while(scan.hasNext() && counter < 5){
for(int i = 0; i < 4; i++){
counter = counter + 1;
for(int m = 0; m < 7; m++){
temperatures[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 4; i++){
System.out.println("Temperature at week:" + (i + 1) + " is: " + temperatures[i][0] + ", " + temperatures[i][1] + ", " + temperatures[i][2] + ", " + temperatures[i][3] + ", " + temperatures[i][4] + ", " + temperatures[i][5] + ", " + temperatures[i][6]);
}
} catch(InputMismatchException e){
System.out.println("Error converting number");
}
scan.close();
reads.close();
} catch (FileNotFoundException e){
System.out.println("File not found" + filename);
} catch (IOException e){
System.out.println("IO-Error open/close of file" + filename);
}
}
}
With your file gave this results:
Temperature at week:1 is: 73, 71, 68, 69, 75, 77, 78
Temperature at week:2 is: 76, 73, 72, 72, 75, 79, 76
Temperature at week:3 is: 79, 82, 84, 84, 81, 78, 78
Temperature at week:4 is: 75, 72, 68, 69, 65, 63, 65