Averaging grades math not displaying correctly - java

Can not for the life of me figure out why my average is not displaying correctly I've looked at it for like 2 hours.
import java.util.Scanner;
public class midterm
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int examScore =0;
int averageExamScore = 0;
int numStudent=0;
int sum=0;
while(examScore >= 0)
{
System.out.println("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
numStudent++;
sum = sum + examScore;
}
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
}
else
{
System.out.println("No scores to average");
}
}
}

The issue here is integer division.
averageExamScore = sum/numStudent;
All three of these arguments are integers, which means:
If you cast a part of your quotient to double, you'd lose precision (and fail compilation)
Example:
averageExamScore = (double)sum/numStudent; // wouldn't compile
The floor of the quotient sum/numStudent is provided instead of the whole number (so for a number like 4.9 you'd get 4).
You can fix this in a few ways:
Declare averageExamScore to be a double. This is required.
Either cast sum or numStudent to a double, or change their type to double.

You have defined averageExamScore as an integer, so integer arithmetic will be applied.
e.g.
5 / 2 == 2
1 / 2 == 0
Make averageExamScore into a double, and also cast your other integers to doubles.
Edit
To print out
do
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
System.out.println ("average score is " + averageExamScore );
}

Go through the following code,
public class MidTerm {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int examScore = 0;
double averageExamScore = 0;
int numStudent = 0;
int sum = 0;
while (true) {
System.out.print("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
if (examScore >= 0) {
numStudent++;
sum += examScore;
} else break;
}
if (numStudent > 0) {
averageExamScore = sum / numStudent;
System.out.println("Avarage score is : " + averageExamScore);
} else System.out.println("No scores to average");
}
}
averageExamScore variable should be a double otherwise it can not stored floating point values
Good Luck !!!

Related

Mooc.fi Exercise: Average of positive numbers fail

I've spent all day but couldn't find a solution. Could someone please help and tell me what the error is? 75% of the code is correct, mooc says. But it fails because:
Fail: When input was: 0, output shouldn't contain: 0.
In other words, when I input 0 alone, it calculates the average of that one 0. However, the exercise calls for all non-positive numbers to be excluded from the average calculation.
This contradictory output is what I get when I enter a zero:
Give a number:
0
Cannot calculate the average
Average of the numbers: 0.0
Here is my code. I'm a beginner in Java and perhaps you guys can see something I can't. All help much appreciated
import java.util.Scanner;
public class AverageOfPositiveNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberofinputs = 0;
double sumofinputs = 0;
double average = 0;
double negative = 0;
double positive = 0;
// For repeatedly asking for numbers
while (true) {
System.out.println("Give a number: ");
// For reading user input
int numberFromUser = Integer.valueOf(scanner.nextLine());
if (numberFromUser <= 0) {
negative = numberFromUser;
} else {
positive = numberFromUser;
}
if (positive == 0){
System.out.println("Cannot calculate the average");
}
if (numberFromUser == 0){
break;
}
if (positive == numberFromUser){
numberofinputs = numberofinputs + 1;
sumofinputs = (sumofinputs + positive);
average = (double) sumofinputs/numberofinputs;
}
}
System.out.println("Average of the numbers: " + average);
}
}

A Java program with a loop that allows the user to enter a series of integers, then displays the smallest and largest numbers + the average

I've got an assignment that requires me to use a loop in a program that asks the user to enter a series of integers, then displays the smallest and largest numbers AND gives an average. I'm able to write the code that allows the user to enter however many integers they like, then displays the smallest and largest number entered. What stumps me is calculating the average based on their input. Can anyone help? I'm sorry if my code is a little janky. This is my first CS course and I'm by no means an expert.
import javax.swing.JOptionPane;
import java.io.*;
public class LargestSmallest
{
public static void main(String[] args)
{
int number, largestNumber, smallestNumber, amountOfNumbers;
double sum, average;
String inputString;
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
largestNumber = number;
smallestNumber = number;
sum = 0;
for (amountOfNumbers = 1; number != -99; amountOfNumbers++)
{
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
if (number == -99)
break;
if (number > largestNumber)
largestNumber = number;
if (number < smallestNumber)
smallestNumber = number;
sum += number;
}
average = sum / amountOfNumbers;
JOptionPane.showMessageDialog(null, "The smallest number is: " + smallestNumber + ".");
JOptionPane.showMessageDialog(null, "The largest number is: " + largestNumber + ".");
JOptionPane.showMessageDialog(null, "The average off all numbers is: " + average + ".");
}
}
The problem is that you do an extra
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
at the beginning. You don't count that in a sum. That's why you get unexpected results.
The fix would be:
replace the declarations line with:
int number = 0, largestNumber, smallestNumber, amountOfNumbers;
Remove
inputString = JOptionPane.showInputDialog("Enter an integer, or enter -99 to stop.");
number = Integer.parseInt(inputString);
That go before the loop
Replace for (amountOfNumbers = 0 with for (amountOfNumbers = 1
This is my first CS course
Then allow me to show you a different way to do your assignment.
Don't use JOptionPane to get input from the user. Use a Scanner instead.
Rather than use a for loop, use a do-while loop.
Usually you declare variables when you need to use them so no need to declare all the variables at the start of the method. However, be aware of variable scope.
(Notes after the code.)
import java.util.Scanner;
public class LargestSmallest {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int largestNumber = Integer.MIN_VALUE;
int smallestNumber = Integer.MAX_VALUE;
int number;
double sum = 0;
int amountOfNumbers = 0;
do {
System.out.print("Enter an integer, or enter -99 to stop: ");
number = stdin.nextInt();
if (number == -99) {
break;
}
if (number > largestNumber) {
largestNumber = number;
}
if (number < smallestNumber) {
smallestNumber = number;
}
sum += number;
amountOfNumbers++;
} while (number != -99);
if (amountOfNumbers > 0) {
double average = sum / amountOfNumbers;
System.out.printf("The smallest number is: %d.%n", smallestNumber);
System.out.printf("The largest number is: %d.%n", largestNumber);
System.out.printf("The average of all numbers is: %.4f.%n", average);
}
}
}
largestNumber is initialized to the smallest possible number so that it will be assigned the first entered number which must be larger than largestNumber.
Similarly, smallestNumber is initialized to the largest possible number.
If the first value entered is -99 then amountOfNumbers is zero and dividing by zero throws ArithmeticException (but maybe you haven't learned about exceptions yet). Hence, after the do-while loop, there is a check to see whether at least one number (that isn't -99) was entered.
You don't need to use printf to display the results. I'm just showing you that option.

Conversion from Base 10 to Base 2

I am trying to convert a number in base 10 to a number in base 2, but I have a problem. When I run the code, I get the base 2 number in the wrong order. For example, I input 54 and get 110110 instead of 011011, the correct value.
import java.util.Scanner;
public class DecimalToBinary
{
public static void main(String arg[]){
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
quotient = quotient / 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
System.out.print (remainder);
} while (quotient != 0);
}
}
Java has a built-in method to do this:
Integer.toString(int i, int radix);
where
i is your base ten number, and
radix is the base you want it in, in your case, 2.
It will return a string in binary.
Another inbuilt java function for this is
Integer.toBinaryString(int num)
where num is the base 10 number you want to convert
Base 10 to Base 2 should Reverse output,I think you can use array,then reverse output array
public static void main(String arg[]){
int quotient;
int remainder;
List<Integer> arrayList=new ArrayList<Integer>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
quotient = quotient / 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
// System.out.print (remainder);
arrayList.add(remainder);
} while (quotient != 0);
ListIterator<Integer> li;
for (li = arrayList.listIterator(); li.hasNext();) {// 将游标定位到列表结尾
li.next();
}
for (; li.hasPrevious();) {// 逆序输出列表中的元素
System.out.print(li.previous() + " ");
}
}
try this solution, its simple:
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
Stack<Integer> s=new Stack<Integer>();
do {
remainder = quotient % 2;
quotient = quotient / 2;
s.add(remainder);
// String x = String.valueOf(remainder);
// System.out.print(x);
//System.out.print (remainder);
} while (quotient != 0);
while(!s.isEmpty()){
System.out.print(s.pop());
}
I was able to fix your code
public class CustomDecimalToBinary {
public static void Dec2Bin() {
int quotient;
int remainder;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a decimal number:");
quotient = keyboard.nextInt();
do {
remainder = quotient % 2;
// String x = String.valueOf(remainder);
// System.out.print(x);
System.out.print (remainder);
} while ((quotient /= 2) != 0);
}
}
Example output:
Please enter a decimal number:
54
011011
EDIT: It appears I solved the problem to get your desired output but your code produces the correct output...

Java Input and Out put

Hi my code should do this instruction below but am not getting it at all
The user can enter as many positive floating-point numbers on the console as desired. Zero (or a
negative numbers) signals end of input (no more numbers can be entered). After input the program
displays
 the smallest number entered (min)
 the largest number entered (max)
 the mean of all numbers entered (mean)
Do NOT use arrays for this assignment, even if you know them.
Sample should look like this
enter numbers: \n
1 2 3 4 5 6 0 \n
numbers entered: 6 \n
minimum: 1.00 \n
maximum:6.00 \n
mean: 3.50\n
enter numbers: \n
0 \n
no number entered.
public class LoopStatistics {
public static void main(String[] args) {
double max, min, sum=0, input, mean=0;
int counter = 0;
TextIO.putln("enter numbers:");
do
{
input = TextIO.getDouble();
min = input;
max = input;
counter++;
if (input > max)
max = input;
if ( input < min)
min = input;
sum = sum + input;
} while( input != 0);
mean = sum / counter;
TextIO.putf("numbers entered:%d\n", counter);
TextIO.putf("minimum:%f\n", min);
TextIO.putf("maximum:%f\n", max);
TextIO.putf("mean:%f", mean);
}
}
You assign your max and min before you test whether they are greater/less than the current max/min:
min = input;
max = input;
This means that they both equal whatever the person entered last.
Tidying up your code and removing those calls yields:
public static void main(String[] args) throws Exception {
final Scanner scanner = new Scanner(System.in);
double max = 0;
double min = Double.POSITIVE_INFINITY;
double sum = 0;
int counter = 0;
while (true) {
final double d = scanner.nextDouble();
if (d <= 0) {
break;
}
sum += d;
max = Math.max(max, d);
min = Math.min(min, d);
++counter;
}
System.out.println("Max=" + max);
System.out.println("Min=" + min);
System.out.println("Ave=" + sum / counter);
}

Number of digits in a number?

i have written a program to find out the number of digit in a given number in java. Is it a good way to do it and what is the time complexity of the program:
import java.util.*;
public class Inst {
/**
* #param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
for(int n=0;n<200000;n++)
{
double b=Math.pow(10, n);
double d=a/b;
if(d>=0 & d<=9)
{
System.out.println("The number has "+(n+1)+" DIGITS");
break;
}
}
}
}
How about this?
double input = Input;
int length = (input + "").length();
import java.util.*;
public class JavaLength {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Double d = sc.nextDouble();
String dString = d.toString();
System.out.println(d);
if(dString.contains(".")){
System.out.println("Total Characters: " + (dString.length() -1 ));
}else{
System.out.println("Total Characters: " + (dString.length()));
} /*-1 for the '.' in between, if it exists!*/
}
FWIW, the most efficient way to test the number of (decimal) digits needed to represent an integer will be a tree of if / else tests. The complexity will be O(1), but the code will be UGLY (but portable); e.g.
int num = ...
if (num >= 0)
if (num < 1000000)
if (num < 10000)
if (num < 100)
if (num < 10)
return 1
else
return 2
else
...
else
...
else
...
else
...
Using pow / log is not generally a good solution, as there may be a number close to a power of ten that rounds to the next integer. In double precision one should be able to precisely store all 15 digit numbers for which log10 should be absolutely < 15. In reality log10(10^15 - 100) still rounds to 15.
One will be stuck with the same algorithms, that are internally used in decimal to string conversions:
trial division:
while (i > 0) { i=i/10; count++; }
trial multiplication:
j=10; while (i >= j) { j*=10; count++; }
trial division from msb to lsb converting to string;
j=10000000; while (i>0) {
while (i>=j) { digit++;i-=j;};
j/=10; *str++=digit+'0'; digit=0:
}
Binary to bcd conversion using double dabble algorithm where each digit is represented by reduced set of hexadecimal digits (omitting a-f).
This logic was originally written in c++, but i believe is the best way to find number of digits, store them in reverse order and find sum of digits.
int n;
int count=0, sum=0;
int j=0;
int ar[10]; //array to store digits
cin>> n; //input number
do{
if((n/10)==0){
count++;
ar[j]=n;
break;
}
else{
count++;
ar[j]= (n%10);
j++;
n=int(n/10);
}
}
`
while((n/10)!=0||(n%10)!=0);
cout<<"The number of digits is: "<<count<<"\n"<<"The reverse number is: ";
for(int u=0;u<count;u++){
cout<<ar[u];
sum+=ar[u];
}
cout<<"\n"<< "Sum of digits is: "<< sum;
}`

Categories

Resources