unable to print decimal value when trying to find average - java

I'm trying to print the average marks of each subject.
When I try to do that i'm unable to get the output in decimal value.
It is rounding to nearest value.
package cube;
import java.io.*;
import java.util.Scanner;
import java.util.Scanner;
public class ReportCard
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
double DB[][],nos=0;
String S="";
double total1=0, total2=0, total3=0, total4=0, total5=0;
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 double[(int) (nos+1)][20];
String arrayOfNames[] = new String[(int) 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());
total1=total1+DB[i][0];
System.out.print("Enter "+arrayOfNames[i]+"'s Science Score : ");
DB[i][1]=Integer.parseInt(br.readLine());
total2=total2+DB[i][1];
System.out.print("Enter "+arrayOfNames[i]+"'s Maths Score : ");
DB[i][2]=Integer.parseInt(br.readLine());
total3=total3+DB[i][2];
DB[i][3]=(int)(DB[i][0]+DB[i][1]+DB[i][2]);
total4=total4+DB[i][3];
DB[i][4]=((int)((DB[i][3])*100)/300);
total5=total5+DB[i][4];
}
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\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="";
}
//System.out.println(total);
int j=0;
DB[j][0]=(int) (total1/nos);
DB[j][1]=(int) (total2/nos);
DB[j][2]=(int) (total3/nos);
DB[j][3]=(int) (total4/nos);
DB[j][4]=(int) (total5/nos);
System.out.println(DB[j][0]);
System.out.println(DB[j][1]);
System.out.println(DB[j][2]);
System.out.println(DB[j][3]);
System.out.println(DB[j][4]);
System.out.print("\nAverage ");
Padd("English ",DB[j][0]);Padd("Science ",DB[j][1]);Padd("Maths ",DB[j][2]);Padd("Total ",DB[j][3]);Padd("Percentage ",DB[j][4]);
}
void Padd(String S,double dB2)
{
double N=dB2;
int Pad=0,size=S.length();
while(dB2!=0)
{
dB2/=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();
}
}
When I try to change the data type of the j to double it gives me the error "Type mismatch: cannot convert from double to int"
2 quick fixes available
1) Add cast to int
2) Change j to int
could anyone help me fix this please.
Thank you.

Using integer calculations, or casting to an integer, will result in an integer output.
So DB[j][0]=(int) (total1/nos); is going to be an integer value.
DB[j][0] = (total1 / nos); should result in the expected value.
The issue is not with the j variable (which is an index into an array), but the calculation.
However, you'd make your code more readable by defining some constants to use:
private static final int ENG = 0;
private static final int SCI = 1;
private static final int MAT = 2;
private static final int AVG = 3;
DB[i][ENG] = Integer.parseInt(br.readLine());
...
Or better yet make a class for a Student. For example:
class Student
{
final String name;
int englishScore = 0;
int scienceScore = 0;
int mathScore = 0;
public int getEnglishScore()
{
return englishScore;
}
public Student setEnglishScore(int englishScore)
{
this.englishScore = englishScore;
return this;
}
public int getScienceScore()
{
return scienceScore;
}
public Student setScienceScore(int scienceScore)
{
this.scienceScore = scienceScore;
return this;
}
public int getMathScore()
{
return mathScore;
}
public Student setMathScore(int mathScore)
{
this.mathScore = mathScore;
return this;
}
public String getName()
{
return name;
}
Student(String name)
{
this.name = name;
}
}
Also, for testing, always separate input (which could change -- perhaps you'd like to read from a file?), the data handling, and the data output.

Related

Encountered Issues Using Multiple Methods on the Same Code

I am a fairly new programmer in Java and am currently learning about how to incorporate multiple methods in one code. The goal of this practice activity is to use several different methods to:
-Create two arrays (one for employee names and another for how much that employee sold)
-Find the average of total sales
-Find the highest sale number
-Find the name of the Employee(s) with the highest sale count (and print "hooray" for every employee that had the highest sale count)
import java.util.*;
public class MethodActivity{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] names={"Employee A", "Employee B", "Employee C", "Employee D", "Employee E", "Employee F", "Employee G", "Employee H", "Employee I", "Employee J"};
System.out.print("Enter the sales numbers, in dollars, for each employee: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
int num4 = sc.nextInt();
int num5 = sc.nextInt();
int num6 = sc.nextInt();
int num7 = sc.nextInt();
int num8 = sc.nextInt();
int num9 = sc.nextInt();
int num10 = sc.nextInt();
double[] sales={num1, num2, num3, num4, num5, num6, num7, num8, num9, num10};
return double[] sales;
return String[] names;
}
public static double getAverage(double[] sales){
double average=(num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10;
return average;
}
public static int getHighestSale(double[] sales){
double highest = sales[0];
int locationOfHighest=0;
if(sales[1]>highest){
highest=sales[1];
locationOfHighest=1;
}else if(sales[2]>highest){
highest=sales[2];
locationOfHighest=2;
}else if(sales[3]>highest){
highest=sales[3];
locationOfHighest=3;
}else if(sales[4]>highest){
highest=sales[4];
locationOfHighest=4;
}else if(sales[5]>highest){
highest=sales[5];
locationOfHighest=5;
}else if(sales[6]>highest){
highest=sales[6];
locationOfHighest=6;
}else if(sales[7]>highest){
highest=sales[7];
locationOfHighest=7;
}else if(sales[8]>highest){
highest=sales[8];
locationOfHighest=8;
}else{
highest=sales[9];
locationOfHighest=9;
}
return highest;
}
public static String showName(String[] names){
String nameOfHighest = "";
String hooray = "";
for (int i = 0; i<names.length; i++){
if (i=locationOfHighest){
nameOfHighest=nameOfHighest+names[i]+", ";
hooray = ""+"hooray ";
}else{
nameOfHighest=nameOfHighest;
}
}
return nameOfHighest;
}
public static void (String[] args){
System.out.println("The average sales for today was: "+average);
System.out.println(nameOfHighest+" made the highest sales of "+highest);
System.out.println(hooray);
}
}
However, when I run the program, I got these errors. The thing is, I don't really understand what they mean:
MethodActivity.java:20: error: '.class' expected
return double[] sales;
^
MethodActivity.java:21: error: '.class' expected
return String[] names;
^
MethodActivity.java:75: error: <identifier> expected
public static void (String[] args){
I would really appreciate if someone could clarify what these mean, since I'm still quite confused by the concept of a multi method code. And, if you could, maybe point out any other issues or fixable elements in my code (since I know my code might look pretty sloppy to someone with programming experience and I could really use some pointers). Thank you for your time.
You need to remove this both returns.
There are two problem in your code:
1) java method can have only one return statement.
2) it is main method and because of it returns void type. void means no return type.
Rather using separate method for printing "public static void (String[] args), print those in main method itself.
Also refer answer by iMBMT.
import java.util.Scanner;
public class MethodActivity {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of employees : ");
int totalEmployeeCount = sc.nextInt();
System.out.println("## totalEmployeeCount : " + totalEmployeeCount);
String[] employeeNames = new String[totalEmployeeCount];
int[] employeeSoldCount = new int[totalEmployeeCount];
String name;
int count;
for (int index = 0; index < totalEmployeeCount; index++) {
System.out.print("Enter employee name : ");
name = sc.next();
System.out.print("Enter employee sale count : ");
count = sc.nextInt();
employeeNames[index] = name;
employeeSoldCount[index] = count;
}
System.out.println("---------------- Pringting all info ----------------");
for (int i = 0; i < employeeNames.length; i++) {
System.out.println("name : " + employeeNames[i] + " & sale count : " + employeeSoldCount[i]);
}
findTheAverageOfTotalSales(employeeSoldCount);
findTheHighestSaleNumber(employeeSoldCount);
}
private static void findTheAverageOfTotalSales(int[] employeeSoldCount) {
for (int saleCount : employeeSoldCount) {
System.out.println("Write your own code ...");
}
}
private static void findTheHighestSaleNumber(int[] employeeSoldCount) {
for (int saleCount : employeeSoldCount) {
System.out.println("Write your own code ...");
}
}
}

How can I not specify any return type and yet print my arrays in a tabular form?

The goal of this program is to declare three separate arrays and then write a function to display them in a tabular form. Here's my code:
import java.util.Scanner;
public class MultiDArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("How many rows?");
int length = input.nextInt();
int [] ID = new int[length];
for(int counter = 0; counter<length; counter++) {
System.out.println("Enter ID number "+(counter+1));
ID[counter] = input.nextInt();
}
Scanner scan = new Scanner(System.in);
System.out.println("How many names?");
int words = scan.nextInt();
String [] Name = new String[words];
for(int counter = 0; counter<words; counter++) {
System.out.println("Enter Name "+(counter+1));
Name[counter] = scan.next();
}
Scanner figure = new Scanner(System.in);
System.out.println("How many Salaries?");
int sal = figure.nextInt();
int []Salary = new int[sal];
for(int counter = 0; counter<sal; counter++) {
System.out.println("Enter Salary "+(counter+1));
Salary[counter] = figure.nextInt();
}
input.close();
scan.close();
figure.close();
System.out.println("ID"+" "+"Name"+" "+"Salary");
System.out.println("Content of Array: " + (display(ID, Name, Salary)));
}
public static String display(int x[], String y[], int z[]) {
for (int i = 0; i<x.length; i++) {
System.out.println(x[i]+" "+y[i]+" "+z[i]);
}
return null;
}
}
Which prints out my system input in this way:
ID Name Salary
1 JK 3000
2 MK 4000
3 CK 5000
null
However, what I would like to see instead is the same without the "null" part.
ID Name Salary
1 JK 3000
2 MK 4000
3 CK 5000
If I do not specify any return type, I get errors.
You are returning null and then concatenating it in your calling println statement
System.out.println("Content of Array: " + (display(ID, Name, Salary)));
You could do something like
System.out.print("Content of Array: ");
String ret = display(ID, Name, Salary);
If you are trying to write a method without a return type, use void. You shouldn't be concatenating a void return to a string though.
public static void display(int x[], String y[], int z[]) {
for (int i = 0; i<x.length; i++) {
System.out.println(x[i]+" "+y[i]+" "+z[i]);
}
}

Sorting student test scores in an array

I am given an integer, N, which is the number of test scores that will be inputted. For each line, N, there will be a student name followed their test score. I need to compute the sum of their test scores & print the the second-smallest student's name.
So, what I would do is create an array of classes for the students. The class would have two instance variables for the name and score. Then when all the input is done, all you need to do is get them. Here is the code that I came up with for that exact thing.
import java.util.*;
public class testScores {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Student[] students = new Student[n];
for(int i = 0; i < n; i++){
students[i] = new Student();
System.out.print("Enter the student's name");
students[i].setName(scan.next());
scan.nextLine();
System.out.print("Enter the student's score");
students[i].setScore(scan.nextInt());
scan.nextLine();
}
int total = 0;
int smallest_name = 0;
for(int i = 0; i < n; i++){
total+=students[i].getScore();
if(students[i].getName().length() < students[smallest_name].getName().length())
smallest_name = i;
}
int second_smallest = 0;
for(int i = 0; i < n; i++){
if(students[i].getName().length() > students[smallest_name].getName().length() && students[i].getName().length() < students[second_smallest].getName().length())
second_smallest = i;
}
System.out.println("The sum of the scores is: " + total);
System.out.println("The second smallest name is: " + students[second_smallest].getName());
}
}
class Student{
private String name;
private int score;
public Student(){}
public void setScore(int n){
score = n;
}
public void setName(String n){
name = n;
}
public int getScore(){
return score;
}
public String getName(){
return name;
}
}

Issue with trying to fix my printf statement

I need to fix my addQuiz() in my student class. Then, with that class, I pull all the info into my main of prog2. I have everything working except two things. I need to get the formula fixed for my addQuiz() so it totals the amount of points entered, and fix the while statement in my main so that I can enter a word to tell the program that I am done entering my quizzes.
Here is my main file.
import java.util.Scanner;
public class Prog2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Student student = new Student();
//creates array for quizzes
double[] grades = new double[99];
//counter for total number of quizzes
int num = 0;
//requests user to enter students name
System.out.print("Enter name of student: ");
String name = in .nextLine();
//requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in .nextInt();
while (quiz >= 1) {
System.out.print("Enter students quiz grades: ");
quiz = in .nextInt();
grades[num] = quiz;
num++;
}
//prints the name, total, and average of students grades
System.out.println();
System.out.println(name);
System.out.printf("\nTotal: ", student.addQuiz(grades, num));
System.out.printf("\nAverage: %1.2f", student.Average(grades, num));
}
}
here is my student file:
public class Student {
private String name;
private int total;
private int quiz;
static int num;
public Student() {
super();
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getQuiz() {
return quiz;
}
public void setQuiz(int quiz) {
this.quiz = quiz;
}
public static double addQuiz( double[] grades, int num){
int totalQuiz = 0;
for( int x = 0; x < num; x++){
totalQuiz += grades[x];
}
return totalQuiz;
}
public static double Average( double[] grades, int num){
double sum = 0;
for( int x = 0; x < num; x++){
sum += grades [x];
}
return (double) sum / num;
}
}
Any help would be much appreciated!
Your requirement is not clear but as I guess it should be something like this.
Prog2 class:
public static void main(String[] args) {
// requests user to enter students name
System.out.print("Enter name of student: ");
Scanner in = new Scanner(System.in);
String name = in.nextLine();
Student student = new Student(name);
System.out.print("Enter number of quiz: ");
int count = in.nextInt();
for (int i = 0; i < count; i++) {
// requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in.nextInt();
student.addGrade(quiz);
}
// prints the name, total, and average of students grades
System.out.println(name);
System.out.println("Total: " + student.getTotal());
System.out.println("Average: " + student.getAverage());
}
Student class:
private String name;
private List<Double> grades = new ArrayList<Double>();
public Student(String name) {
super();
this.name= name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addGrade(double grade) {
this.grades.add(grade);
}
public double getTotal() {
double total = 0;
for (double grade : grades) {
total += grade;
}
return total;
}
public double getAverage() {
return (double) getTotal() / grades.size();
}
Accept the answer if it helps.
Well for the stop condition you could try something like this
String stopFrase="stop";
String userInput="";
int quiz;
//Other code
for(;;) //This basically means loop until I stop you
{
System.out.print("Enter students quiz grades type 'stop' to finish:");
userInput=in.nextLine();
if(userInput.equals(stopFrace))
{
break;//Stop the loop
}
quiz= Integer.parseInt(userInput);
//The rest of your code
}
Your addQuiz() method seems fine, if you are not getting the desired result please check your parameters, specifically make sure that number matches the number of quiz entered.

How to compare enum value to scanner input in java for switch statement

Im' trying to get user input if he presses "a", he can do the average, calls in average method if he types in "s", he uses the sum method.
Im new to enums so im experimenting. I made an enum that stores a,b and am trying to compare it's values to user input using scanner.
I could be using if statements and forget the whole enum thing but i want to know how it works.
thanks.
public enum RecursionEnum {
s, a
}
main class:
import java.util.*;
public class Recursion {
static RecursionEnum enumtest;
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (enumtest) {
case a:
average();
case s:
sums();
}
}
public static void main(String[] args) {
yn();
}
public static int sums() {
int i = 0;
int j = 0;
int sum = i + j;
return sum;
}
public static double average() {
Scanner avgs = new Scanner(System.in);
System.out.println("Enter total number of numbers; ");
double tnum = avgs.nextDouble();
double[] nums = new double[(int) tnum];
double sum = 0;
for (int i = 0; i < tnum; i++) {
System.out.println("Enter number " + (i + 1) + " : ");
nums[i] = avgs.nextDouble();
sum += nums[i];
}
System.out.println(" ");
double avg = sum / tnum;
return avg;
}
}
This is the output:
Enter a for average or s for sum
a
Exception in thread "main" java.lang.NullPointerException
at com.towerdef.shit.Recursion.yn(Recursion.java:14)
at com.towerdef.shit.Recursion.main(Recursion.java:26)
Enumerable types have a synthetic static method, namely valueOf(String), which will return an enum instance matching the input, if it exists. Note that the input is case-sensitive in this case. Trim is used to deal with potential extraneous whitespace.
You can switch on that:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (RecursionEnum.valueOf(answer.trim())) {
case a:
average();
case s:
sums();
}
}
Of course, on Java 7 and higher, you can switching on strings. You may thus use:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (answer.trim()) {
case "a":
average();
break;
case "s":
sums();
break;
}
}

Categories