Average Calculator Program Using Java - java

import java.util.Scanner;
public class AverageMark{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int mark[] = { 0, 0, 0, 0 };
System.out.printf("Enter integer mark %s between 0 and 100: ", i + 1);
}
System.out.println("Thanks for entering your marks.\n");
double average = (mark[0] + mark[1] + mark[2] + mark[3]) * 0.25;
String grade;
if (average >= 90) {
grade = "A+";
} else if (average >= 80) {
grade = "A";
} else if (average >= 70) {
grade = "B";
} else if (average >= 60) {
grade = "C";
} else if (average >= 50) {
grade = "D";
} else
grade = "F";
System.out.printf("Your average is: %.2f\n", average);
System.out.printf("Your average of %.2f has a letter grade of %s", average, grade);
}
}
//Hi sorry about the prior edit, I am new to this site. This is the code I wrote but I'm not sure why it won't run. It seems something might be missing but I'm
quite unclear. Please help thank you

Your code is almost there, just missing to store the values entered by user :
Store the marks in the array :
System.out.println("Enter the marks : ");
for (int i =0; i < mark.length; i ++) {
System.out.printf("Enter integer mark %s between 0 and 100: ", i + 1);
// assign each input to an index of the array
mark[i] = input.nextInt();
}
I would also advice you to declare the array like below rather than just initialing all the indexes to 0
int mark[] = new int[4];
The rest of your code works as it is.

There are some issues with the code.
The first error you see is:
AverageMark.java:13: error: <identifier> expected
System.out.println("Thanks for entering your marks.\n");
This is because you have a closing curly brace where it is not needed. The Java compiler is having difficulty interpreting the structure of your program. Remove line 11. You need to have matching curly braces to form a syntactically correct program. Did you mean to include a for loop ?
Once you correct that and recompile you'll find that:
AverageMark.java:10: error: cannot find symbol
System.out.printf("Enter integer mark %s between 0 and 100: ", i + 1);
symbol: variable i location: class AverageMark 1 error
Add the definition for int i=0 before the reference to i on line 10.
It should then compile and you can start debugging.

In below program , I am giving flexibility to user to enter number of subjects. Scanner allows the user to read values of various types. System.in: An InputStream which is typically connected to keyboard input of console program.
import java.util.Scanner;
class AverageMarks
{
public static void main(String args[])
{
int i;
System.out.println("Enter number of subjects");
Scanner sc=new Scanner(System.in);
//Here we are taking number of subjects from user
int n=sc.nextInt();
//Set array to no of subject
int[] a=new int[n];
double avg=0;
System.out.println("Enter marks");
// Taking marks from user for n no of subjects
for( i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
// Calculating total marks of subjects in avg variable
for( i=0;i<n;i++)
{
avg=avg+a[i];
System.out.println("Total marks of subjects : => "+avg);
}
//Calculating average % using total/no of subject formula
for(i=0;i<n-1;i++)
{
System.out.print(a[i]+",");
}
System.out.println(a[i]+") ="+avg/n);
}
}

Related

Average calculator with user input Java - " java.util.NoSuchElementException: No line found "

I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}

How do I keep track the number of times a specific input was entered by the user?

My program should ask the user to enter some grades. After the input is finished, the program has to show which grade was entered how many times (or in another word, how many times each grade was entered).
For example, if the user enters grade 3 two times, thats menas total 2 students has got the grade 3. If the grade F is entered 3 times, that means 3 students has got the failing grade F, and so on....
The final output should look something like this:
Example output:
grade F= 3 students
grade 3= 2 studnets
and so on....
...........................
...........................
Now my problem is with keeping track of each grade and print them out telling how many times (also means how many students got each specific grade) each of the grade was entered. I can't come up with idea to solve it.
My code:
package studentgrade;
import java.util.*;
public class StudentGrade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many total grade you want to enter (Depending on the total number of students)? ");
int totalStudents = input.nextInt();
String grade[] = new String[totalStudents];
//asking user to enter grade
for (int i = 0; i < totalStudents; i++) {
System.out.println("Enter grade " + (i + 1) + ": ");
System.out.println("Choose only between grade 3 and F:\n");
grade[i] = input.next();
if (grade[i] == "3") {//3 defines the only passing grade
//Store that into a variable
} else if (grade[i].equalsIgnoreCase("F")) {//F defines the failing grade
//Store that into a variable
}//else{
//System.out.println("Invalid input. Try again");
//}
}
//Now print out which grade was entered how many times
}
}
Define, at the top, a variable resembling each grade and set them to 0, and then, each time in the "if" statement, add one to the corresponding variable. variable++.
At the end, use
System.out.println("Grade 3: " + variable3);
System.out.println("Grade F: " + variableF);
Also, use .equals method to compare two strings in the if statement
If you don't need the sort of introduced values, simply create an array with your needed size n (don't see exactly what means from 3 to F).
int[] grade = new int[n];
If all inputs where numbers you can make direct:
grade[input.next()] ++;
Then, as all inputs are not int you can solve it with a switch
switch(input.next()) {
case "3":
grade[0] ++;
case "2":
grade[1] ++;
....
case "F":
grade[n-1] ++;
}
This is a good use for a Map. Right now your only storing the inputs 3 and F but if you wanted to adapt this program to have more grades this would scale perfectly and it is a clean and neat solution.
// the map to store how many times a grade was entered
private static final Map<String, Integer> gradeSumMap = new HashMap<String, Integer>();
public static void addToGradeSum(String key, int num) {
if(gradeSumMap.get(key) == null) {
gradeSumMap.put(key, num);
} else {
gradeSumMap.put(key, gradeSumMap.get(key) + num);
}
}
public static void printGradeSumMap() {
for(String key : gradeSumMap.keySet()) {
System.out.println("grade " + key + " = " + gradeSumMap.get(key));
}
}
// this needs to also be .equals or .equalsIgnoreCase
if (grade[i].equals("3")) {
addToGradeSum(grade[i], 1);
} else if (grade[i].equalsIgnoreCase("F")) {
addToGradeSum(grade[i], 1);
}
then just call printGradeSumMap() when you want to print it

how to only allow one argument at a time

I am allowing the user to enter numbers via command line. I would like to make it so when the user enters more then one number on the command line at a time it displays a message asking for one number then press enter. then carries on.
here is my code. If someone could show me how to implement this I would appreciate it.
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
try{
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
catch (InputMismatchException e) {
System.out.println("Stop it swine! Numbers only! Now you have to start over...");
main(args);
return;
}
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}
As suggested in the comments to the question: Just do not scan the line you read for numbers, but parse it as a single number instead using Double.valueOf (I also beautified the rest of your code a little, see comments in there)
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
// we can use a for loop here to break on q and read the next line instead of that while you had here.
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++; //that'S even shorter than count += 1, and does the exact same thing.
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("You entered more than one number, or not a valid number at all.");
continue; // Skipping the input and carrying on, instead of just starting over.
// If that's not what you want, just stay with what you had here
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
(Code untested, so there may be errors in there. Please notify me if you got one ;))
String[] numbers = inputs.split(" ");
if(numbers.length != 1){
System.out.println("Please enter only one number");
}

Loop that will execute as many times as user directs

Write a program to calculate the current grade based on the CSE 1341 syllabus. The program should prompt the user for their first and last name. It will then pass those names as Strings to the second method of the CSE1341Grade class. The name of the second method will be calcGrade. This method will prompt the user for the count of exam scores, count of quiz scores, and count of lab scores to entered by the user.
It will then utilize repetition structure to prompt for exam grades, quiz grades and lab grades based on the previous counts entered. For example, if the user entered count of exam scores to be 2; then the program will loop 2 times to input the two exam grades; and similarly for the count of quiz and count lab grades.
Assume you have a 100% attendance record and you will get all 5% of the attendance grade.
Use the syllabus to determine the weights of each of the categories such as the exams, quizzes and labs. Add 5% to the total score since you had perfect attendance.
Assume: all exams, labs and quiz scores are out of 100 points.
Sample Run:

java CSE1341Grade
First name: James
Last name: Bond
How many exam grades do you have? 1
How many quiz grades do you have? 2
How many lab grades do you have? 2
Enter exam 1 score: 90
Enter quiz 1 score: 80
Enter quiz 2 score: 80
Enter lab 1 score: 90
Enter lab 2 score: 90
Total Score: 84.55
James Bond your grade is a: B
^^That is my homework assignment, and this is what I have done so far
import java.util.Scanner;
public class CSE1341Grade
{
public static void main(String [] args)
{
//set up Scanner for user input, prompt for first name, define variable, and print response
Scanner s = new Scanner(System.in);
System.out.print("First name: ");
String first = s.nextLine();
System.out.printf(" %s\n", first);
//prompt user for last name, define variable, and print response
System.out.print("Last name: ");
String last = s.nextLine();
System.out.printf(" %s\n", last);
}
public static void calcGrade(String first, String last)
{
//prompt user for number of exam grades, define exam variable, print response
System.out.print("How many exam grades do you have? ");
String exam = s.nextLine();
System.out.printf(" %s\n", exam);
//prompt user for number of quiz grades, define quiz variable, print response
System.out.print("How many quiz grades do you have? ");
String quiz = s.nextLine();
System.out.printf(" %s\n", quiz);
//prompt user for number of lab grades, define lab variable, print response
System.out.print("How many lab grades do you have? ");
String lab = s.nextLine();
System.out.printf(" %s\n", lab);
while (exam != -1)
{
System.out.print("Enter " exam 1 " score: ", ++exam)
//define variables for computations
int score = 0;
int grade = 0;
//if statement to determine the final letter grade
if(score >= 90 && score <=100){
grade = 'A'; }
else if(score >=80 && score < 90){
grade = 'B'; }
else if(score >= 70 && score < 80){
grade = 'C'; }
else if(score >=60 && score < 70){
grade = 'D'; }
else {
grade = 'F'; }
}
}
My problem is figuring out how to create a loop that will prompt the user for however many exam grades needed.
I have performed few changes to your code based in the comments ..
Here you can see the diff
http://www.mergely.com/LIckVifT/
Note: It still does not finish your homework :-)
Update: Since the index in the foor loop does not really matters you could use it as this:
for (int i = 1; i <= examsCount; i++) {
// using i+1 to print starting from 1 instead of 0
System.out.print("Enter " + i + " score: ");
instead of
for (int i = 0; i < examsCount; i++) {
// using i+1 to print starting from 1 instead of 0
System.out.print("Enter " + (i + 1) + " score: ");
I like to do a loop and continue to ask the user for input until I get the result I want:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean shouldContinue = true;
while(shouldContinue) {
// do program logic
System.out.print("Should we continue? [Y or N] >> ");
if (input.nextLine().equalsIgnoreCase("N")) {
shouldContinue = false;
}
}
}
This is a relatively "structured" way to do an interaction loop and continue running a program over and over so long as the user wants.
-- UPDATE --
To do a number of iterations that you know ahead of time, simply pipe that into your counter for the loop:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number of grades to enter [number] : ");
int numberOfTimesToIterate = input.nextInt();
for (int i = 0; i < numberOfTimesToIterate; i++) {
// do stuff here
}
}
Pseudo-code:
function(int n) {
for (i = n, i > 0, i--) {
\\prompt user
}
}
That should give you the general idea of how to do it, namely taking the amount, and subtracting 1 from it until you reach 0, each time getting the data and doing what it needs to do with it. Don't forget to make sure that n never equals less than zero (invalid), and that n is an integer. Otherwise, it is desirable that you have the function simply prompt the user for an amount, then pass that amount to the function that actually uses it. Alternatively, create a function which iterates n times and calls a function passed to it as an argument that many times (much harder to correctly do).
Something like this should work for you.
System.out.println("Please enter the number of exam grades you want to enter");
int grade_count = s.nextInt();
int [] grades = new int[grade_count];
for(int i =0; i<grade_count; i++){
System.out.println("Enter grade for "+i+1 +"Exam");
grades[i] = s.nextInt();
}

Java- String index out of bounds exception " String index out of Range"

I am new to java, and going to bite the bullet by asking what is I am sure, a dumb question. I created some methods, and simply wanted to call them in main. I am getting an error for the while loop in the main method. The compiler is saying " Exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range:0 at java.lang.String.charAt(String.java:686) at Project3.main(Project3.java:61)
Any help would be greatly appreciated. Thanks. Full Code is below:
import javax.swing.JOptionPane;
import java.util.Scanner;
public class Project3
{
public static void main(String[] args)
{
int iScore1; //first variable input by user to calc average
int iScore2; //second variable input by user to calc average
int iScore3; //third variable input by user to calc average
double dAverage; //returned average from the three test scores
char cLetterGrade; //letter grade associated with the average
double dGPA; //the GPA associated with the letter grade
char cIterate = 'Y'; // loop check
String strAgain; //string user inputs after being asked to run again
System.out.print(createWelcomeMessage());
//pause in program
pressAnyKey();
while (cIterate == 'Y')
{
//prompt user for test scores
System.out.print("\n\nPlease enter the first test score: ");
Scanner keys = new Scanner(System.in);
iScore1 = keys.nextInt();
System.out.print("\nPlease enter the second test score: ");
iScore2 = keys.nextInt();
System.out.print("\nPlease enter the third test score: ");
iScore3 = keys.nextInt();
//calculate average from the three test scores
dAverage = calcAverage(iScore1, iScore2,iScore3);
System.out.print("\nThe average of the three scores is: " + dAverage);
//pause in program
pressAnyKey();
//get letter grade associated with the average
cLetterGrade = getLetterGrade(dAverage);
System.out.print("\nThe letter grade associated with the average is " + cLetterGrade);
//pause in program
pressAnyKey();
//get the GPA associated with the letter grade
dPGA = calcGPA(cLetterGrade);
System.out.print("\nThe GPA associated with the GPA is "+ dGPA);
//pause in program
pressAnyKey();
System.out.print("\nDo you want to run again?(Y or N):_\b");
strAgain = keys.nextLine;
strAgain = strAgain.toUpperCase();
cIterate = strAgain.charAt(0);
}//end while
//display ending message to user
System.out.print(createEndingMessage());
}//end main method
}//end class Project3
public static String createWelcomeMessage()
{
String strWelcome;
strWelcome = "Why hello there!\n";
return strWelcome;
}//end createWelcomeMessage()
public static String createEndingMessage()
{
String strSalutation;
strSalutation = "See you later!\n";
return strSalutation;
}//end createEndingMessage()
public static void pressAnyKey()
{
JOptionPane.showMessageDialog(null, "Press any key to continue: ");
}//end pressAnyKey()
public static int getTestSCore()
{
int iScore;
System.out.print("Enter a test score: ");
Scanner keys = new Scanner(System.in);
iScore = keys.nextInt();
return iScore;
}//end getTestSCore()
public static int calcAverage(int iNum1, int iNum2, int iNum3)
{
double dAverage;
dAverage = ((double)iNum1 + (double)iNum2 + (double)iNum3) / (double)3.0;
return dAverage;
}//end calcAverage(int iNum1, int iNum2, int iNum3)
public static char getLetterGrade(double dGrade)
{
char cLetter;
if (dGrade <60)
{
cLetter = 'F';
}
else if (dGrade >=60 && dGrade <70)
{
cLetter = 'D';
}
else if (dGrade >=70 && dGrade <80)
{
cLetter = 'C';
}
else if (dGrade >=80 && dGrade <90)
{
cLetter = 'B';
}
else if (dGrade >=90)
{
cLetter = 'A';
}
return cLetter;
}//end getLetterGrade(double dGrade)
public static double calcGPA(char cLetterGrade)
{
double dGPA;
if (cLetterGrade == 'A')
{
dGPA = 4.0;
}
else if (cLetterGrade == 'B')
{
dGPA = 3.0;
}
else if (cLetterGrade == 'C')
{
dGPA = 2.0;
}
else if (cLetterGrade == 'D')
{
dGPA = 1.0;
}
else
{
dGPA = 0.0;
}
return dGPA;
}//end calcGPA(char cLetterGrade)
You're reading three ints using scanner.nextInt(). Since nextInt does not consume any whitespace or newline after the read token, that means that if the user enters a number and presses enter, there's still a linebreak in the stream.
So when you call nextLine later it just reads that linebreak and returns the empty string.
Since calling charAt on an empty string will cause an out of bounds error, you get the error you get.
To fix this, either use next instead of nextLine, which will read the next word (consuming any whitespace before it), instead of the next line, or call nextLine twice. Once to consume the linebreak and once to read the actual line.
You should still check whether the user enters an empty line though.
The problem is caused by this line:
cIterate = strAgain.charAt(0);
The string apparently does not have a character at index 0, in other words, it is empty.
You may want to check the user input and ask again if none was supplied.
If you move line 67 or so, it's the line that ends the class. Move it to the end, and that brings it down to three errors. One of those three errors is a misspelling, the one about keys.nextLine needs () --> keys.nextLine() and the last error is that the method header returns an int, not a double. Doing this does generate another error, but if you set cLetter to a space in single quotes, ' ' then the code compiles.

Categories