How do I calculate average of each subject - java

How do I calculate the average of each subject and average of the total value of 3 subjects and average of percentage and print them below the table.
I tried to find the average by dividing each array with number of students variable "DB" but it gives error
"The operator / is undefined for the argument type(s) int, int[][]".
And is there any way that I can get a perfect table structure for the output.
I'm using \t to create space between columns but they do not align properly.
package cube;
import java.io.*;
import java.util.Scanner;
public class ReportCard
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int DB[][],nos=0;
String S="";
Scanner s = new Scanner(System.in);
void Input()throws Exception
{
System.out.print("Enter The Number Of Students : ");
nos=Integer.parseInt(br.readLine());
DB=new int[nos+1][20];
String arrayOfNames[] = new String[nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter "+arrayOfNames[i]+"'s English Score : ");
DB[i][0]=Integer.parseInt(br.readLine());
System.out.print("Enter "+arrayOfNames[i]+"'s Science Score : ");
DB[i][1]=Integer.parseInt(br.readLine());
System.out.print("Enter "+arrayOfNames[i]+"'s Maths Score : ");
DB[i][2]=Integer.parseInt(br.readLine());
DB[i][3]=(int)(DB[i][0]+DB[i][1]+DB[i][2]);
DB[i][4]=((int)((DB[i][3])*100)/300);
DB[i][5]=(int)(DB[i][0])/DB;
Padd("Average\t",DB[i][5]);
if ((DB[i][0])< 50 | (DB[i][1])< 50 | (DB[i][2]) < 50) {
System.out.print("Fail");
}
else {
System.out.print("Pass");
}
}
System.out.println("\n\n\nStudent Name. English Science \t Maths Total Percentage Pass or Fail \n");
for(int i=0;i<nos;i++)
{
System.out.print(""+arrayOfNames[i]+"\t\t");Padd("English \t ",DB[i][0]);Padd("Science \t ",DB[i][1]);
Padd("Maths \t ",DB[i][2]);Padd("Total \t",DB[i][3]);Padd("Percentage\t",DB[i][4]);
if ((DB[i][0])< 50 | (DB[i][1])< 50 | (DB[i][2]) < 50) {
System.out.print("\t\tFail");
}
else {
System.out.print("\t\tPass");
}
System.out.println(S);
S="";
}
}
void Padd(String S,int n)
{
int N=n,Pad=0,size=S.length();
while(n!=0)
{
n/=10;
Pad++;
}
System.out.print(" "+N);
for(int i=0;i<size-Pad-4;i++)
System.out.print(" ");
}
public static void main(String args[])throws Exception
{
ReportCard obj=new ReportCard();
obj.Input();
}
}

Your problem is in this section of code
DB[i][5]=(int)(DB[i][0])/DB;
Padd("Average\t",DB[i][5]);
if ((DB[i][0])< 50 | (DB[i][1])< 50 | (DB[i][2]) < 50) {
System.out.print("Fail");
}
else {
System.out.print("Pass");
}
From what I can understand from your code index 5 is not needed. You already stored the average in array index 4 (DB[i][4]).
Either way the division is illegal. An int cannot be divided by an array. Perhaps you mean the length of DB (DB.length)

You are getting this error as you are doing arithmetic operations on the array object itself.
Array in java is a data structure to hold sequential collection of values/objects. You can do arithmetic operations on elements of the array by accessing them using the index.
Like below:
int result = array[i][0] / 3;
But in your code you are passing entire array as an operand in the expression.
DB[i][5]=(int)(DB[i][0])/DB;
Above line of code is causing the issue. Instead of providing any entire DB array, provide it's corresponding index according to your requirement
I hope this answers your question

Related

How can I get the system output value after the whole loop is done?

this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);

User Input to determine the length of an array in Java

I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.
For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.

Java file io calculating average and storing in another file

I would appreciate knowing how to tackle this type of problems. Thank you in advance.
Here is the question.
The first line of the files contains two integer numbers ;
number-of-records exam-grade
number-of-records : indicates number of the records in the file.
exam-grade : indicates the grade of the exam.
The file follows by students name and their grades.
Sample File: test1.txt
Contains four records, and the exam is out of 80. The file follows by the name and grade of the students:
4 80
Mary 65.5
Jack 43.25
Harry 79.0
Mike 32.5
You have to develop the body of following method:
public static void readWrite(String srcfileName, String dstFileName)
That reads grades of each student from srcFileName, calculates their grade percent, indicates that if student passed or failed, and finally reports the class average, number of the students passed, and number of the students failed the exam and saves the result in dstFileName.
The output file for the previous test file should be:
Mary 81.88 passed
Jack 54.06 passed
Harry 98.75 passed
Mike 40.63 failed
class average:68.83
passed: 3
failed: 1
here is the code I wrote for it,
import java.util.*;
import java.io.*;
public class Lab10Quiz {
public static void main(String[] args) throws FileNotFoundException
{
// Test cases
readWrite("test1.txt", "out1.txt");
readWrite("test2.txt", "out2.txt");
}
/** copies the content of the srcFileName into dstFileName, and add the average of the number to the end of the dstFileName
#param srcFileName : souce file name contains double numbers
#param dstFileName : destination file name
*/
public static void readWrite(String srcFileName, String
dstFileName) throws FileNotFoundException {
// Your code goes here
File output = new File(dstFileName);
PrintWriter outPut = new PrintWriter(output);
double avg = 0;
int count = 0;
double tmp = 0;
Scanner in = new Scanner(new File(srcFileName));
while (in.hasNextDouble()) {
tmp = in.nextDouble();
avg += tmp;
outPut.println(tmp);
count ++;
}
avg = avg / count;
outPut.println("Average = " + avg);
outPut.close();
}
}
This code achieves what you want
double avg = 0;
int failCounter = 0;
String[] keywords = in.nextLine().split(" ");
int studentNumber = Integer.parseInt(keywords[0]);
double examValue = Double.parseDouble(keywords[1]);
for (int i = 0; i < studentNumber; i++) {
keywords = in.nextLine().split(" ");
String studentName = keywords[0];
double studentMark = Double.parseDouble(keywords[1]);
double grade = calculateTotalGrade(studentMark, examValue);
failCounter += (hasFailed(grade) ? 1 : 0);
avg += grade;
outPut.println(String.format("%s \t\t %.2f \t\t %s", studentName, grade, hasFailed(grade) ? "failed" : "passed"));
}
avg = avg / studentNumber;
outPut.println("class average: " + avg);
outPut.println("passed: " + (studentNumber - failCounter));
outPut.println("failed: " + failCounter);
And I extracted some of the logic to below methods.
private static double calculateTotalGrade(double grade, double examValue) {
return grade * 100 / examValue;
}
private static boolean hasFailed(double grade) {
return grade < 50;
}
To answer how to tackle this type of questions:
Look for the simplest way. In this case looping for a finite iterations was easier. So I went with the for loop.
The counter is already given, No need to re-calculate it.
If you are working on a computer, write a little code and test it.
Do more questions like these. (if you go through the first chapters of this book these questions will be easy)

Average of an array and associate with name

Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result

Counter won't work to end loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on an assignment and it is working well so far. But several aspects aren't working. For starters, my counters for int total and int counter won't work. Also my if statements don't seem to be working. I have been scratching my head for several days now.
The assignment calls for a program to input the order number and will loop based on how many orders the customer has. It also calls for customer name, sign type(wood or plastic), the number of characters,and color of characters.
Some more information:
The base price for all signs is $20.
If sign is wood, add $10. If it is plastic add $5.
The first 5 letters/numbers are included in base price, and $2 for each additional character.
Black or white characters are included in base price, there is an additional $8 for colored letters.
If the total charge is more than $100 give 25% discount on total price.
Here is my code right now:
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
System.out.println("Enter your order number");
orderNumber = sc.nextInt();
counter=orderNumber;
counter--;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
do{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
if(signType == "wood") {
i+=10;
}
if(signType == "plastic") {
i+=5;
}
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
if(color != "white" || color != "black") {
i += 8;
}
total= i;
System.out.println("Total is: $" + total);
if( total > 100 ) {
total = (total * 0.25);
System.out.println("The total is " + total );
}
}
while(counter <= orderNumber);
}
}
I added comments to guide you through the changes I made. Also, remember to call the sc.NextLine() function after you get user input so that they can input something different next time (this is called 'flushing' the buffer).
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
//I changed the phrasing just because it is a little confusing
System.out.println("Enter your number of orders");
orderNumber = sc.nextInt();
counter = orderNumber;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
sc.nextLine();
//When you know how many times you want to repeat something (like when a user tells you how many) I prefer using a for-loop, a do while loop works as well though
for(int x=0; x<counter;x++)
{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
//When comparing Strings, there is a function that you can use to compare them rather than using '=='
// It is also good to use the 'equalsIgnoreCase()' function to be more user friendly and robust
if(signType.equalsIgnoreCase("wood")) {
i+=10;
}
if(signType.equalsIgnoreCase("plastic")) {
i+=5;
}
//Flush the buffer (I haven't tested if this is necessary or not, it is good practice though)
sc.nextLine();
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
//Same concept as above, the differene is the ! before the function to test if it is false or not
if(!color.equalsIgnoreCase("white") || !color.equalsIgnoreCase("black")) {
i += 8;
}
}
total = i;
//You will not want to print this out until the end due to the possibility of it being over $100
// System.out.println("Total is: $" + total);
if( total > 100 ) {
//Mathematically speaking, you are making your total a quarter of what the original is, rather than taking a quarter off. You want 75% rather than 25%
// total = (total * 0.25);
total = (total * 0.75);
}
System.out.println("Total is: $" + total);
}
}
You should set counter to the correct starting value (which is presumably 1 in your case):
orderNumber = sc.nextInt();
counter=1;
//counter=orderNumber;
//counter--;
Then at the end of the loop, you should increment your counter:
do{
//code
counter++;
}
while(counter <= orderNumber);

Categories

Resources