Getting the Percentage of two variables - java

I have tried using casting with my variables as well as some of the other tips that I have read on here about getting percentages and its not working here is the code. There is a lot more to it, of course. I have tried all ways from casting, to what I have displayed.
(EDITED AGAIN 2nd time)
Here is the whole code. You were right is was working but in this, it is not! Even if the grade variables are float or int, still not working. Changed the grade variables so they don't display a decimal!. Output (BELOW) shows the grade but not the percentage. Thanks for the feedback.
OUTPUT:
Please enter a grade from 0 - 100! Enter -1 to end the program! 99
Please enter a grade from 0 - 100! Enter -1 to end the program! -1
The total number of grades is 2
Number of A's = 1 which is %0.0
Number of B's = 0 which is %0.0
Number of C's = 0 which is %0.0
Number of D's = 0 which is %0.0
Number of F's = 0 which is %0.0
Code:
public class Main {
public static void main(String[] main) {
Scanner input = new Scanner(System.in) ;
int totalGrades = 1 ;
int gradeA = 0 ;
float gradeAPercentage = (gradeA * 100f) / totalGrades ;
int gradeB = 0 ;
float gradeBPercentage = gradeB / totalGrades ;
int gradeC = 0 ;
float gradeCPercentage = gradeC / totalGrades ;
int gradeD = 0 ;
float gradeDPercentage = gradeD / totalGrades ;
int gradeF = 0 ;
float gradeFPercentage = gradeF / totalGrades ;
int a = 0 ;
do{
System.out.println("Please enter a grade from 0 - 100! Enter -1 to end the program!") ;
int grade = input.nextInt() ;
if( (grade == -1) && (totalGrades == 0) ) {
System.out.println("You entered no grades!") ;
totalGrades--;
break ;
}
else if(grade == -1){
a++ ;
}
else if(grade <= 59){
gradeF++ ;
totalGrades++ ;
}
else if( (grade >= 60) && (grade <= 69) ){
gradeD++ ;
totalGrades++ ;
}
else if( (grade >= 70) && (grade <= 79) ){
gradeC++ ;
totalGrades++ ;
}
else if( (grade >= 80) && (grade <= 89) ){
gradeB++ ;
totalGrades++ ;
}
else if( (grade <= 100) && (grade >= 90) ){
gradeA++ ;
totalGrades++ ;
}
else{
System.out.println("Your input is Invalid") ;
continue ;
}
}while(a < 1 ) ;
System.out.println("The total number of grades is " + totalGrades) ;
System.out.println("Number of A's = " + gradeA + " which is %" + gradeAPercentage) ;
System.out.println("Number of B's = " + gradeB + " which is %" + gradeBPercentage) ;
System.out.println("Number of C's = " + gradeC + " which is %" + gradeCPercentage) ;
System.out.println("Number of D's = " + gradeD + " which is %" + gradeDPercentage) ;
System.out.println("Number of F's = " + gradeF + " which is %" + gradeFPercentage) ;
}
}

There is an implicit casting done, no additional casting to float is needed. The code you provided works fine. If you print the result with
System.out.println(gradeAPercentage);
you will get, what you have wanted to calculate.

Related

Error with validation with while loop

im having some trouble with my validation. Here is my code
int a = keyboard.nextInt();
int b = keyboard.nextInt();
while(x < -50 || x > 50 && y < -50 || y > 50)
{
System.out.println("Error " + a + " is out of range");
System.out.println("Error " + b + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
while( x < -50 || x > 50)
{
System.out.println("Error " + a + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
while( y < -50 || y > 50)
{
System.out.println("Error " + b + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
My problem, is that the user input needs to be a & b from [-50, 50]
But when i input -100 and 100 I only get a is out of range or b is out of range not both.
Input: a= -100 b = 100
Output:
System.out.println("Error " + -100 + " is out of range"); // CORRECT
System.out.println("Error " + 23 + " is out of range"); // ? INCORRECT
What am i doing wrong
You're being naughty with your operator precedence.
x <= -50 || x >= 50 && y <= -50 || y > 50
is evaluated as
x <= -50 || (x >= 50 && y <= -50) || y > 50
You need to put in some parentheses:
(x <= -50 || x >= 50) && (y <= -50 || y > 50)
Also, check the precise relationship between a, b, x, and y. Why do you assign to a and b, yet then immediately test x and y?
Use absolute values, remember |a| < x means -x < a < x
so both a and b must meet the criteria, or another way, you will ask as long as **a > 50** or **b > 50**
int a = -100;
int b = -100;
Scanner scan = new Scanner(System.in);
while (Math.abs(a) > 50 || Math.abs(b) > 50) {
System.out.println("need a:");
a = scan.nextInt();
System.out.println("need b:");
b = scan.nextInt();
}
scan.close();
System.out.println("am gone!");
check the while loop.
while( x <= -50 || x >= 50 && y <= -50 || y > 50)
both conditions need to be true to execute succesfully.check the &&
As explained in the comments, you are testing x and y but reading a and b.
Additionally, your code can be simplified:
boolean valid = true;
do {
System.out.print("Input two integers in the range [-50, + 50]: ");
int a = keyboard.nextInt();
int b = keyboard.nextInt();
if ( (a < -50) || (a > 50) ) {
valid = false;
System.out.println("Error " + a + " is out of range");
}
if ( (b < -50) || (b > 50) ) {
valid = false;
System.out.println("Error " + b + " is out of range");
}
} while (!valid);
while( x <= -50 || x >= 50 && y <= -50 || y > 50) Java uses "short circuit evaluation" of logical operators. So if x = -100 and y = 0, the loop will be entered because -100 <= -50 and no other conditions matter because true || anything is always true. Use parentheses to control how logical operations are processed. I suggest putting the Boolean condition controlling the while loop into a nicely named method.
private boolean bothParamsAreOutOfRange(int x, int y) {
boolean rtn = false;
if ((x <= -50 || x >= 50) && (y <= -50 || y > 50)) {
rtn = true;
}
return rtn;
}
while(bothParamsAreOutOfRange(x, y)) {
... as before ...
}

unable to get the difference between two numbers AND keep getting invalid amount when entering [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 7 years ago.
Improve this question
This program will generate a random number and ask user to disperse
the correct amount of change. If user has entered the wrong amount
the program will say Incorrect by : +difference...
mine refuses to work...
*/
// ---------1---------2---------3---------4---------5---------6---------7
// 1234567890123456789012345678901234567890123456789012345678901234567890
import java.util.Scanner;
import java.util.Random;
public class ChangeGame9
{
public static void main(String[] args)
{
int low = 1;
int max = 10000;
int twentyDollars = 0;
int tenDollars = 0;
int fiveDollars = 0;
int oneDollar = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
Random random = new Random();
int randomNumber = random.nextInt(max - low + 1);
double randomNumber1 = (randomNumber /100.0);
double userAmount = twentyDollars * 20 + tenDollars * 10 +
fiveDollars * 5 + oneDollar * 1 + quarters * 0.25
+ dimes * 0.10 + nickels * 0.05 + pennies * 0.01;
double difference = Math.abs( randomNumber1 - userAmount);
double differenceOne = (int)(difference*100 + 0.5) / 100.0;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter the change for " + randomNumber1);
System.out.println("Twenties: ");
twentyDollars = keyboard.nextInt();
while( twentyDollars <= 0 );
{
System.out.println( "** Invalid Amount **\n" +
"Twenties: " );
twentyDollars = keyboard.nextInt();
}
System.out.println("Tens: ");
tenDollars = keyboard.nextInt();
while( tenDollars < 0 || tenDollars > 1 )
{
System.out.println( "** Invalid Amount **\n" +
"Tens: " );
tenDollars = keyboard.nextInt();
}
System.out.println("Fives: ");
fiveDollars = keyboard.nextInt();
while( fiveDollars < 0 || fiveDollars > 1 )
{
System.out.println( "** Invalid Amount **\n" +
"Fives: " );
fiveDollars = keyboard.nextInt();
}
System.out.println("Ones: ");
oneDollar = keyboard.nextInt();
while( oneDollar > 4 || oneDollar < 0 )
{
System.out.println( "** Invalid Amount **\n" +
"Ones: " );
oneDollar = keyboard.nextInt();
}
System.out.println("Quarters: ");
quarters = keyboard.nextInt();
while( quarters < 0 || quarters > 3 )
{
System.out.println( "** Invalid Amount **\n" +
"Quarters: " );
quarters = keyboard.nextInt();
}
System.out.println("Dimes: ");
dimes = keyboard.nextInt();
while( dimes < 0 || dimes > 2 )
{
System.out.println( "** Invalid Amount **\n" +
"Dimes: " );
dimes = keyboard.nextInt();
}
System.out.println("Nickels: ");
nickels = keyboard.nextInt();
while( nickels < 0 || nickels > 1 )
{
System.out.println( "** Invalid Amount **\n" +
"Nickels: " );
nickels = keyboard.nextInt();
}
System.out.println("Pennies: ");
pennies = keyboard.nextInt();
while( pennies < 0 || pennies > 4 )
{
System.out.println( "** Invalid Amount **\n" +
"Pennies: " );
pennies = keyboard.nextInt();
}
while ( differenceOne == 0)
{
System.out.println("Correct!");
}
}
while( differenceOne != 0);
{
System.out.println("Incorrect by: " + differenceOne);
}
}
}
----jGRASP exec: java ChangeGame9
Enter the change for 52.38
Twenties:
2
** Invalid Amount **
Twenties:
2
Tens:
1
Fives:
0
Ones:
2
Quarters:
1
Dimes:
1
Nickels:
0
Pennies:
3
Enter the change for 52.38
Twenties:
this is what is happening when I run my code...I don't understand what the problem is...
while( twentyDollars <= 0 );
{
System.out.println( "** Invalid Amount **\n" +
"Twenties: " );
twentyDollars = keyboard.nextInt();
}
You have a semicolon after your while loop. This is interpreted as the body of your while loop being an empty statement, followed by the code that says invalid input.
If you notice, you can enter actual invalid input the second time it asks and it will accept it and continue onto the tens. Likewise if you enter invalid input at the first opportunity your program will freeze as it enters an infinite loop.

Read and print from a text file

Ok so I'm supposed to be reading and printing from a text file with the code yet every time I run I get a "java.utilNoSuchElementException" on line 31 "grade = in.nextInt();". The current text file is
2 80 97
5 69 79 89 99 58
7 60 70 80 90 100 0 59
where the first number is the number of scores in each section, each section is supposed to be counted (ie. 1, 2, 3) Anyways one problem at a time. here's the current code.
import java.util.Scanner;
import java.io.*;
public class Prog2
{
public static void main (String args []) throws IOException
{
Scanner in = new Scanner (new File ("test1.txt"));
int Lowest, Highest, grade = 0;
float section_average, class_average;
int count = 0, A = 0, B = 0, C = 0, D = 0, F = 0, total_number_of_sections = 0, total_number_of_scores = 0, number = 0;
while (in.hasNextInt())
{
number = in.nextInt();
System.out.println (in.nextInt());
number ++;
while (count < number)
{
grade = in.nextInt();
total_number_of_sections += number;
total_number_of_scores += grade;
total_number_of_scores ++;
count++;
}
}
if (number > 0)
{
System.out.println ("Scores for section "+count);
}
else
{
System.out.println ("Scores for section 0");
}
if (grade >= 90)
{
A ++;
}
if (grade >= 80 && grade < 90)
{
B ++;
}
if (grade >= 70 && grade < 80)
{
C ++;
}
if (grade >= 60 && grade < 70)
{
D ++;
}
if (grade < 60)
{
F ++;
}
System.out.println (" ");
System.out.println ("Scores for section "+count);
System.out.println ("A's" + A);
System.out.println ("B's" + B);
System.out.println ("C's" + C);
System.out.println ("D's" + D);
System.out.println ("F's" + F);
System.out.println ("Lowest Score: ");
System.out.println ("Highest Score: ");
System.out.println (" ");
System.out.println (" ");
System.out.println ("Total number of sections: " + total_number_of_sections);
System.out.println ("Total number of scores: " + total_number_of_scores);
System.out.println ("Class Average: ");
}
}
try this
while (in.hasNextInt())
{
count = 0;
number = in.nextInt();
System.out.println (in.nextInt());
while (in.hasNextInt())
{
grade = in.nextInt();
total_number_of_sections += number;
total_number_of_scores += grade;
total_number_of_scores ++;
if(++count == number ){ break;}
}
}

Stuck on Java program that tallies grades and shows results

I'm taking a beginners course in Java and they asked us to:
Write a program to tally the number of A's, B's, C's, D's and F's based upon a list of scores entered by a user.
After all the scores are entered, the program must display a
horizontal bar graph of the number tallied for each grade like that shown in the Operation section.
The tally graph must display a single '*' for each unit tallied.
When a user enters a -1, the program must display the final graph and
exit.
The output of your program must display prompts and a tally graph
like that shown in the Operation section above.
You may assume that a user will enter numbers only.
Operation:
The program starts and prompts you to either enter a test score or end
the program by entering a -1. Like the following:
Number of A's: 0
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: 90
As you enter each score, the application decides whether the score is
an A, B, C, D or F and adds one to the letter-grade tally. Like the
following:
Number of A's: 1
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: 95
Each time you enter a score, the program updates the tally. Like the following:
Number of A's: 2
Number of B's: 0
Number of C's: 0
Number of D's: 0
Number of F's: 0
Enter a score (%) or -1 to end: -1
When you are done entering scores, the program displays a horizontal
bar graph of the tally for A's, B's, C's, D's and F's. Like the
following:
A's: **
B's:
C's:
D's:
F's:
Specifications:
Numerical Grade Letter Grade
greater than or equal to 90 A
less than 90 but greater than or equal to 80 B
less than 80 but greater than or equal to 70 C
less than 70 but greater than or equal to 60 D
less than 60 F
When the program ends, display the number of scores, average score, and best score.
Example:
Number of scores: 2
Average score: 92.5
Best score: 95.0
We have also been instructed to code in at least two methods : one that has a void and one that returns something.
So far I have only been able to tally up the scores entered, but I don't seem to be able to wrap my head around recording all the inputs and calculating the average and picking out the best score
This is what I have so far :
import java.util.*;
public class ScoreTally {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
double score = 0;
while (score != -1) {
if (score >= 90)
aCount++;
else if ((score < 90) && (score >= 80))
bCount++;
else if ((score < 80) && (score >= 70))
cCount++;
else if ((score < 70) && (score >= 60))
dCount++;
else if ((score < 60) && (score > 0))
fCount++;
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
scoreCount++;
}
if (score == -1)
System.out.println("Number of scores: " + scoreCount);
}
}
Use a function to return the greatest number to get your best score.
And another function to print the final graph.
That should take care of the two function requirement.
Also, make the loop an exit-controlled one, as it has to run atleast once.
As a coding practice, you should not be using star imports(import java.util.*) instead use only what you need.
Also, good work on setting the scoreCount to -1 in the beginning.
import java.util.Scanner;
public class ScoreTally {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
double score;
double totalScore = 0;
double bestScore = -1;
do {
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
if (score >= 90) {
aCount++;
} else if ((score < 90) && (score >= 80)) {
bCount++;
} else if ((score < 80) && (score >= 70)) {
cCount++;
} else if ((score < 70) && (score >= 60)) {
dCount++;
} else if ((score < 60) && (score > 0)) {
fCount++;
}
scoreCount++;
totalScore = totalScore + score;
bestScore = greaterNumber(bestScore, score);
} while (score != -1);
printGraph('A', aCount);
printGraph('B', bCount);
printGraph('C', cCount);
printGraph('D', dCount);
printGraph('F', fCount);
System.out.println("Number of scores: " + scoreCount);
System.out.println("Average scores: " + totalScore / scoreCount);
System.out.println("Best scores: " + bestScore);
}
public static void printGraph(char grade, int count) {
System.out.print("Number of " + grade + "'s: ");
for (int i = 0; i < count; i++) {
System.out.print("*");
}
System.out.println();
}
public static double greaterNumber(double firstNum, double secondNum) {
if (firstNum >= secondNum) {
return firstNum;
} else {
return secondNum;
}
}
}
To begin with you already have the code to tally the results.
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
int scoreCount = -1;
What you need is another field that will hold the total score i.e.
int totalScore = 0;
You need to prompt for the first score before you enter the while loop otherwise it won't run properly the first iteration. At the end (or the beginning) you need to update totalScore with whatever was the input for that round, and not update it if the input was -1.
The average score will just be the totalScore/scoreCount you should compute that after you finish the while loop.
For the best score you can have another field for int = maxScore
you can update it every iteration of the loop with
maxScore = Math.max(maxScore, score);
Math.max returns the maximum of the two numbers.
It's rather simple. Declare 2 variables, one for having avgScore, one for in beginning of your program.
double bestScore = 0.0;
double avgScore = 0.0;
double totalScore = 0.0;
while (score != -1) {
totalScore = totalScore + score;
if(score > bestScore)
bestScore = score;
if (score >= 90)
aCount++;
else if ((score < 90) && (score >= 80))
bCount++;
else if ((score < 80) && (score >= 70))
cCount++;
else if ((score < 70) && (score >= 60))
dCount++;
else if ((score < 60) && (score > 0))
fCount++;
System.out.println("Number of A's: " + aCount);
System.out.println("Number of B's: " + bCount);
System.out.println("Number of C's: " + cCount);
System.out.println("Number of D's: " + dCount);
System.out.println("Number of F's: " + fCount);
System.out.print("Enter a score (%) or -1 to end: ");
score = input.nextDouble();
scoreCount++;
}
if (score == -1){
System.out.println("Number of scores: " + scoreCount);
avgScore = totalScore/scoreCount;
System.out.println("Best Score: " + bestScore);
System.out.println("Avg Score: " + avgScore);
}
Also for displaying the chart you can use your final tallies.

Java basic loop

I have no idea why my second for loop won't execute.. It compiles but when I run this it does not work ~_~
import java.util.Scanner;
public class ranges
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int size;
int input;
int count = 0;
int occurence = 0;
System.out.print ("Please enter the size of your array: ");
size = scan.nextInt();
int[] list = new int[size];
for (int index = 0 ; index < list.length ; index++)
{
System.out.print ("Please enter an integer between 0 to 50: ");
input = scan.nextInt();
if ( input >= 0 && input <= 50 )
{
list[index] = input;
}
else
{
System.out.println ("Invalid output, please try again");
index--;
}
}
int right = (list.length)-1;
int left = 0;
for (int counter = left ; counter < list.length ; counter++)
{
while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;
right--;
}
}
right = (list.length)-1;
System.out.println ("The number " + list[left] + " was added " + occurence + "4 times");
}
for (int value : list)
{
System.out.print (value + " ");
}
;
}
}
My updated for loop to evaulate occurences
for (int left = 0 ; left < list.length ; left++)
{
while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;
}
right--;
}
System.out.println ("The number " + list[left] + " was added " + occurence + " times");
right = (list.length)-1;
occurence = 0;
}
I have cleaned it up a bit, and now occurences are same as the inputs
You second for is also working. The problem is in while loop condition i.e. while ( right >= left ). If list[left] == list[right] is not equal, it goes in infinite loop as neigther right nor left changing in that case.
I think, you need to change your while as below(move right-- outside the if condition):
while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;
}
right--;
}
Two more issues:
Please re-initialize occurence =0; before the while loop so that it counts occurence of each number and remove 4 from your System.out.println() e.g. below:
for (int counter = left ; counter < list.length ; counter++)
{
occurence = 0; //< initialize to 0
while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;
}
right--;
}
right = (list.length)-1;
//remove 4 after "occurance +"
System.out.println ("The number " + list[left] +
" was added " + occurence + " times");
}
EDIT: working sample with HashMap:
Map<Integer, Integer> scannedNums = new HashMap<Integer, Integer>();
for (int counter = left ; counter < list.length ; counter++)
{
if(scannedNums.get(list[counter]) == null){
scannedNums.put(list[counter], 1);
}else{
int currentCount = scannedNums.get(list[counter]);
scannedNums.put(list[counter], currentCount+1);
}
}
Set<Integer> nums = scannedNums.keySet();
Iterator<Integer> numIter = nums.iterator();
while(numIter.hasNext()){
int number = numIter.next();
System.out.println ("The number " + number +
" was added " + scannedNums.get(number) + " times");
}
Just a quick look, and suggestion for the future.
This code:
while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;
right--;
}
}
suggests that if list[left] != list[right], yet right is still >= left, this loop will never stop. You might want to move the right-- OUTSIDE of the if statement, if all you want is a count of how many occurrences are found.
Finally, when you say "the loop doesn't work", that's a little less than helpful. Perhaps showing your output, or the WAY in which it doesn't work would be better.
What error does it give?
One immediate problem I see is that if there are no occurrences, the while loop will run for ever. Also the first for loop could give index out of bounds.
For the first loop, instead of:
for (int index = 0 ; index < list.length ; index++)
{
System.out.print ("Please enter an integer between 0 to 50: ");
input = scan.nextInt();
if ( input >= 0 && input <= 50 )
{
list[index] = input;
}
else
{
System.out.println ("Invalid output, please try again");
index--;
}
}
I would do:
for (int index = 0 ; index < list.length ; ++index)
{
while(true)
{
System.out.print ("Please enter an integer between 0 to 50: ");
input = scan.nextInt();
if ( input >= 0 && input <= 50 )
{
list[index] = input;
break;
}
System.out.println ("Invalid output, please try again");
}
}
And for the second loop:
for (int counter = left ; counter < list.length ; counter++)
{
occurence = 0;
for( int i = counter; i <= right; ++i)
{
if( list[left] == list[i] )
++occurence;
}
System.out.println ("The number " + list[left] + " was added " + occurence + " times");
}

Categories