This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 7 years ago.
I am trying to find the average number of students per class but when I test my program, it only prints 1 or 0 everytime. Any help would be appreciated.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the number of Students: ");
int s = reader.nextInt();
System.out.println("Please enter the number of classes: ");
int c = reader.nextInt();
int numbStud1 = 0;
int numbClass1 = 0;
double averages =calcAverage (numbStud1 + c,numbClass1 + s) ;
System.out.println("The average is: " + averages);
}
public static double calcAverage(int numbStud, int numbClass){
double average1;
average1 = numbStud / numbClass;
return average1;
}
}
The issue is this:
double averages =calcAverage (numbStud1 + c,numbClass1 + s) ;
Replace it with exchanging c with s:
double averages =calcAverage (numbStud1 + s,numbClass1 + c) ;
And if you want avrage more precision use :
average1 = (numbStud*1.0 / numbClass*1.0);
Related
This question already has answers here:
Convert a number to 2 decimal places in Java
(4 answers)
Closed 4 months ago.
I was given a task to calculate the average mark of unknown number of tests in JAVA, I was able to solve the problem but not thoroughly because my output has more than 2 decimal point. May I please be helped to only show my output rounded off to two decimal places. (I am a first year students and I don't know much in JAVA). Here's a snippet of my code.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class number2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number_Of_Tests = 0;
int total_marks = 0;
int mark;
System.out.print("Enter the test mark: ");
mark = scan.nextInt();
while (mark >= 0) {
number_Of_Tests = number_Of_Tests + 1;
total_marks = total_marks + mark;
System.out.print("Enter the test mark: ");
mark = scan.nextInt();
}
float average = total_marks / (float) number_Of_Tests;
JOptionPane.showMessageDialog(null, "The average is: " + average, "AVERAGE",1);
scan.close();
}
}
let's say my input is: 25 , 26 and 28 then 0, my output should be 26.34 but instead I get 26.333334
import java.util.Scanner;
import javax.swing.JOptionPane;
public class number2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number_Of_Tests = 0;
int total_marks = 0;
int mark;
System.out.print("Enter the test mark: ");
mark = scan.nextInt();
while (mark >= 0) {
number_Of_Tests = number_Of_Tests + 1;
total_marks = total_marks + mark;
System.out.print("Enter the test mark: ");
mark = scan.nextInt();
}
float average = total_marks / (float) number_Of_Tests;
JOptionPane.showMessageDialog(null, "The average is: " +"% .2f" + average, "AVERAGE",1);
scan.close();
}
}
The first example is a formatter that always produces two decimal places. The second one only produces as many decimal places (up to 2) as needed. Usage: DF_TWOPLACES.format(average);
final private static DecimalFormat DF_TWOPLACES = new DecimalFormat("0.00", DecimalFormatSymbols.getInstance(Locale.US));
final private static DecimalFormat DF_TWOPLACES = new DecimalFormat("0.##", DecimalFormatSymbols.getInstance(Locale.US));
I'm trying to use recursion to take the output of an Array. I've been able to create the input where the input takes the array data but no matter what I input, the array continuously returns 0.0. I did a test print of the array and it appears the data is going to the array so I'm not sure where I'm going wrong.
import java.util.Arrays;
import java.util.Scanner;
public class AverageGradeCourtney {
public static void main(String args[])
{
int i = 0;
int sum = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
double average = findAverage(newClassSize);
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
//System.out.println(average);
}
System.out.println("The average for the class is: " + average);
}
public static double findAverage(int array[])
{
if (array.length==0)
{
return 0;
}
return findAverageHelper(array,0,0);
}
public static double findAverageHelper(int[] array, int index, int sum)
{
if (index==array.length)
{
return (double) sum/array.length;
}
return findAverageHelper(array, index+1, sum+=array[index]);
}
}
The output continues to look like this:
Please enter the class size:
2
Please enter the grade of the user at: 1
12
Please enter the grade of the user at: 2
5
The average for the class is: 0.0
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 5 years ago.
New to java. Do not understand error. Basically trying to return value to then determine output but error "Cannot make static reference to non static field appears on line 13" in the class bosscalc. Return values from operators class.Please help. I have indicated line 13 in the class bosscalc. Thanks
package calculator;
import java.util.Scanner;
public class bosscalc {
Scanner input = new Scanner(System.in);
public static void main(String args[]) {
operators operatorobjects=new operators();
String answer;
System.out.println("What would you like to do? ");
answer =input.nextLine(); -------------------------LINE 13
if (answer=="a"){
double adding = operatorobjects.add();
}
if (answer=="s") {
double subtrat = operatorobjects.sub();
}
if (answer=="m") {
double multiply = operatorobjects.sub();
}
}
}
Class operators:
package calculator;
import java.util.Scanner;
public class operators {
double add() {
double n1,n2,a;
Scanner input=new Scanner(System.in);
System.out.print("Enter number 1 ");
n1=input.nextDouble();
System.out.print("Enter number 2 ");
n2=input.nextDouble();;
a=n1+ n2;
return a;
}
double sub() {
double n1,n2,d;
Scanner input=new Scanner(System.in);
System.out.print("Enter number 1 ");
n1=input.nextDouble();
System.out.print("Enter number 2 ");
n2=input.nextDouble();;
d=n1 - n2;
return d;
}
double m() {
double n1,n2,m;
Scanner input=new Scanner(System.in);
System.out.print("Enter number 1 ");
n1=input.nextDouble();
System.out.print("Enter number 2 ");
n2=input.nextDouble();;
m=n1/n2;
return m;
}
}
As the error message says: From a static context (your static main function) you cannot reference a non-static variable (input).
You can fix it by making input static, i. e. declare it as follows:
static Scanner input = new Scanner(System.in);
I have spent five minutes changing (refactoring) your code. There were a few simple errors. I have moved everything into a single class, and added some comments.
There are lots of improvements which can be made. But this is all down to practice and experience:
import java.util.Scanner;
public class Operators {
/**
* add numbers
* #return n1 + n2
*/
double add() {
double n1, n2, a;
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1 ");
n1 = input.nextDouble();
System.out.print("Enter number 2 ");
n2 = input.nextDouble();
a = n1 + n2;
return a;
}
/**
* subtract numbers
* #return n1 - n2
*/
double sub() {
double n1, n2, d;
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1 ");
n1 = input.nextDouble();
System.out.print("Enter number 2 ");
n2 = input.nextDouble();
d = n1 - n2;
return d;
}
/**
* multiply numbers
* #return n1 * n2
*/
double multiply() {
double n1, n2, m;
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1 ");
n1 = input.nextDouble();
System.out.print("Enter number 2 ");
n2 = input.nextDouble();
m = n1 * n2;
return m;
}
/**
* divide numbers
* #return n1 / n2
*/
double divide() {
double n1, n2, m;
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1 ");
n1 = input.nextDouble();
System.out.print("Enter number 2 ");
n2 = input.nextDouble();
m = n1 / n2;
return m;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Operators operatorobjects = new Operators();
String answer;
System.out.println("What would you like to do? ");
answer = input.nextLine();
/**
* String equality use String.equals()
*/
if (answer.equals("a")) {
double adding = operatorobjects.add();
/**
* Debug output println
*/
System.out.println("adding = " + adding);
} else if (answer.equals("s")) {
double subtract = operatorobjects.sub();
System.out.println("subtract = " + subtract);
} else if (answer.equals("m")) {
double multiply = operatorobjects.multiply();
System.out.println("multiply = " + multiply);
} else if (answer.equals("d")) {
double divide = operatorobjects.divide();
System.out.println("divide = " + divide);
}
/**
* More debug exiting
*/
System.out.println("exiting");
}
}
I have added a divide method, and renamed to multiply. The output from running is:
What would you like to do?
a
Enter number 1 10
Enter number 2 10
adding = 20.0
exiting
What would you like to do?
s
Enter number 1 10
Enter number 2 2
subtract = 8.0
exiting
What would you like to do?
m
Enter number 1 2
Enter number 2 5
multiply = 10.0
exiting
What would you like to do?
d
Enter number 1 6
Enter number 2 3
divide = 2.0
exiting
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 7 years ago.
i am mking a program where the computer guesses your number. and it has to guess a random num. but how do i make the random line be lower or higher num than the perviously num guessed?
package compguse;
import java.util.*;
public class Compguse {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String a;
String b;
String c;
String ans;
String d;
int input =1;
System.out.println("do u have your number?");
a = scan.nextLine();
while (a.equalsIgnoreCase("yes"))
{
int ran = (int) Math.floor(Math.random()*100)+1;
System.out.println(" is" +ran +" your num?");
a = scan.nextLine();
if(a.equalsIgnoreCase("no"))
{
System.out.println("Was i too high or low?");
b = scan.nextLine();
if(b.equalsIgnoreCase("high"))
{
int ran1 = (int) Math.floor(Math.random() < (int) ran);
}
}
}
}
Just make a while loop which implements this pseudocode:
For example if you want it to be less than the guess:
while random is greater than guess
random = new random number
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 7 years ago.
Improve this question
I looked and could not find anything like what I am wanting to do. I have a method with 3 parameters that I need to call from my main method. I've tried everything I have leaned in class so far, but I cannot fig this out. this is for my Programming in Java Course. Here is what I need to call from my main method:
import java.util.*;// for scanner
import java.text.DecimalFormat;
public class Grades {
//Homework, exam1, and exam2 weights
static double homeworkWeight;
static double examOneWeight;
static double examTwoWeight;
//Homework
static int homeworkNumberOfAssignments;
static int homeworkAssignment1Score;
static int homeworkAssignment1Max;
static int homeworkAssignment2Score;
static int homeworkAssignment2Max;
static int homeworkAssignment3Score;
static int homeworkAssignment3Max;
static int homeworkSectionsAttended;
static int homeworkSectionsAttendedTotal;
static int homeworkSectionsAttendedMax;
double homeworkTotalPoints;
double homeworkMaxPoints;
double homeworkWeightedScore;
//Exam1
static int examOneScore;
static int examOneCurve;
static double examOneMaxPointsAvailable;
double examOneWeightedScore;
//Exam2
static int examTwoScore;
static int examTwoCurve;
static double examTwoMaxPointsAvailable;
double examTwoWeightedScore;
//Grades
static double courseGrade;
static double grade;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
showIntro();
System.out.println("");
System.out.print("Homework and Exam 1 weights? ");
homeworkWeight = console.nextInt();
examOneWeight = console.nextInt();
examTwoWeight = 100 - homeworkWeight + examOneWeight;
System.out.println("Using weights of " + homeworkWeight + " " + examOneWeight + " " + examTwoWeight);
homework();
System.out.println("");
exam1();
//System.out.println("");
//exam2();
//System.out.println("");
//courseGrade(courseGrade; double homeworkWeightedScore; double examOneWeightedScore; double examTwoWeightedScore;);
double d = courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
System.out.println("");
}//
//Shows the intro to the program to the user.
public static void showIntro() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grades in the course.");
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.println("");
System.out.println("Homework:");
System.out.print("Number of assignments? ");
homeworkNumberOfAssignments = console.nextInt();
System.out.print("Assignment 1 score and max? ");
homeworkAssignment1Score = console.nextInt();
homeworkAssignment1Max = console.nextInt();
System.out.print("Assignment 2 score and max? ");
homeworkAssignment2Score = console.nextInt();
homeworkAssignment2Max = console.nextInt();
System.out.print("Assignment 3 score and max? ");
homeworkAssignment3Score = console.nextInt();
homeworkAssignment3Max = console.nextInt();
System.out.print("Sections attended? ");
homeworkSectionsAttended = console.nextInt();
homeworkSectionsAttendedTotal = homeworkSectionsAttended * 4;
homeworkSectionsAttendedMax = 20;
//Calculating total points earned
double totalPoints = homeworkAssignment1Score + homeworkAssignment2Score + homeworkAssignment3Score + homeworkSectionsAttendedTotal;
//Calutaing the max points available to be earned
double maxPoints = homeworkAssignment1Max + homeworkAssignment2Max + homeworkAssignment3Max + homeworkSectionsAttendedMax;
//Formatting with DecimalFormat to remove the decimal and 0 when displaying
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(("Total points = ") + df.format(totalPoints) + " / " + df.format(maxPoints));
//Calculating the weighted score by dividing totalPoints by maxPoints and then multiplying times homeworkWeight
double homeworkWeightedScore = ((totalPoints / maxPoints) * homeworkWeight);
//Printing out weighted score and rounding to the nearest hundreth with Math.round
System.out.println("Weighted score = " + Math.round(homeworkWeightedScore * 100.0) / 100.0);
}
public static void exam1() {
Scanner console = new Scanner(System.in);
System.out.println("Exam 1:");
System.out.print("Score? ");
examOneScore = console.nextInt();
System.out.print("Curve? ");
examOneCurve = console.nextInt();
System.out.println("Total points = " + examOneScore + " / " + examOneCurve);
examOneMaxPointsAvailable = 100;
double examOneWeightedScore = ((examOneScore / examOneMaxPointsAvailable) * examOneWeight);
System.out.println("weighted score = " + Math.round(examOneWeightedScore * 100.0) / 100.0);
}
public static void exam2() {
Scanner console = new Scanner(System.in);
System.out.print("Exam 2:");
System.out.print("Score? ");
examTwoScore = console.nextInt();
System.out.print("Curve? ");
examTwoCurve = console.nextInt();
System.out.print("Total points = ");
System.out.println("weighted score = ");
}
public double courseGrade(double homeworkWeightedScore, double examOneWeightedScore, double examTwoWeightedScore) {
return homeworkWeightedScore + examOneWeightedScore + examTwoWeightedScore;
}
}
There's a couple factors missing from your question that makes me unable to completely answer them, but:
Is the courseGrade method in a separate class or in the same class as your public static void main method?
Yes: Create a new instance of the separate class by doing: public SeparateClass instance = new SeparateClass(); inside of public static void main
After that, call this from your main method: double grade = instance.courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
No: Make the courseGrade method static, you can't call a non-static method from a static method (replace public double courseGrade with public static double courseGrade). After that, inside of your main method, do this: double d = courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
I hope this helps.