java program that finds average with average method - java

I have a program that will average your numbers from the command line. Everything is in the main method.
1. The program should run allowing you to enter one number at a time and when you press enter it asks you for another number or offers the ability to press Q to get your average.
2. The program has a limit set to 20 numbers added. When you hit 21 the program notifies you that you added to many numbers and shuts down.
3. If you enter multiple numbers on the same line and press enter, for every number you enter it System.out.println a message once for every number instead of just once.
I would like to understand how to change the program to do these things.
How to get the System.out.println to only appear one time per entry.
How to get the program to output the average of 20 before it ends when someone enters 21
how do i change it to create a method for averaging outside of main then call on the averaging method inside the main.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan2.hasNextDouble()) {
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}

1.
scan2.hasNextDouble()
is parsing the line which contains multiple entries so it must be removed in the while loop. You can parse yourself using string tokenize and print the message only once.
2 . Simply add this line:
System.out.println("Your average is: " + (sum/count));
before returning in if condition to print the average before quitting.
3 . that really depends on what kind of function would you like. May be you can create a function that takes an array of numbers and prints out their average or maybe you want something else.
one possible function:
public double findAverage(ArrayList<Integer> numbers){
int sum=0;
for (Integer i: numbers){
sum+=i;
}
return sum/(double)numbers.size();
}

You can try with the following:
public static void main(String[] args){
if(args.length==20)
{
int sum=0;
sum += Integer.parseInt(args[0]); //do this for 20 array elements using loop
// do required calculation
}
else //print error message
}

Related

GPA calculator assistance

Hi I was wondering if I could get some help with a GPA calculator.
What it needs to do is:
The input will consist of a sequence of terms, e.g., semesters.
The input for each term will consist of grades and credits for courses taken within that term.
For each term, the user will type in an integer that represents the number of courses
taken within that term.
Each course is specified by a String letter grade and an int number of credits, in that order, separated by white space. 5. If the user types in -1 for the number of courses taken in a term, then the program must print a final overall summary and then terminate.
DO NOT prompt for any input. Thus, after you run your program in BlueJ, type Ctrl-T to force the Terminal window to pop up.
As always, follow the input / output format depicted in the Sample runs section.
Shown below is the error message I get and the code I have, thank you for any assistance in advance or tips I could try.
Terminal window and error message:
import java.util.Scanner;
/*
*
*
*/
public class Prog2 {
public static void main(String args[]) {
Scanner numberInput = new Scanner(System.in);
int numberofClasses = numberInput.nextInt();
Scanner input = new Scanner(System.in);
String [] grade = new String[5];
int [] credit = new int [5];
double totalCredit = 0.0;
double realGrade = 0.0;
double result = 0.0;
while (numberofClasses > 0)
{
for (int x = 0; x < numberofClasses; x++ )
{
grade[x] = input.next();
credit[x] = input.nextInt();
}
for(int x=0;x < numberofClasses; x++ ){
if(grade[x].equals("A+")){
realGrade=4.0;
}
else if(grade[x].equals("A")){
realGrade=4.0;
}
else if(grade[x].equals("A-")){
realGrade=3.67;
}
else if(grade[x].equals("B+")){
realGrade=3.33;
}
else if(grade[x].equals("B")){
realGrade=3.00;
}
else if(grade[x].equals("B-")){
realGrade=2.67;
}
else if(grade[x].equals("C+")){
realGrade=2.33;
}
else if(grade[x].equals("C")){
realGrade=2.00;
}
else if(grade[x].equals("C-")){
realGrade=1.33;
}
result = result+realGrade*credit[x];
totalCredit=totalCredit+credit[x];
}
System.out.println("Summary for term:");
System.out.println("----------------------------------");
System.out.println("Term total grade points: " + result);
System.out.println("Term total credits:" + totalCredit);
System.out.println("GPA:"+result/totalCredit);
}
// This block is getting used later please ignore
System.out.println("Final Summary:");
System.out.println("----------------------------------");
System.out.println(" Overall terms");
System.out.println(" Total grade points: " + result);// this needs to be all );
System.out.println(" Total credits" + totalCredit);//This needs to be all );
System.out.println("Cumulative GPA:"+result/totalCredit);
}
}
When your while loop ends, numberofClasses still contains the value that was entered before the while loop started the first time. Specifically, after you output the line:
GPA=3.0588...
you hit the end of the loop, then return to:
while (numberofClasses > 0)
which is true. The next "3" that you enter doesn't go into numberofClasses, it is picked up by
grade[x] = input.next();
Then the "A" is picked up by
credit[x] = input.nextInt();
which throws an exception since it's not an integer.
All you need to do is ask for the number of classes again at the end of the while loop:
System.out.println("GPA:"+result/totalCredit);
numberofClasses = numberInput.nextInt();
}
Output:
5
A 3
B 2
C 4
A 5
C 3
Summary for term:
----------------------------------
Term total grade points: 52.0
Term total credits:17.0
GPA:3.0588235294117645
3
A 3
B 5
C 1
Summary for term:
----------------------------------
Term total grade points: 81.0
Term total credits:26.0
GPA:3.1153846153846154
i recommend looking into whether your compiler or IDE has a "debug" feature. It is a very helpful tool, and lets you watch how your program goes through your code
Just a tip...
When you ask for input, print what you're asking for first. When I launched your program I had no idea what to do. Try adding System.out.println("input number of classes you took");before you prompt for that number.
Here is what is wrong. (If you printed what you're asking for first, this would be more apparent).
after your program displays the stats, you enter 5. Yet your program is actually still on this line grade[x] = input.next(); on line 22 i believe.
when you enter 5, your scanner is expecting a letter. and an exception is thrown.
you need to consider how you escape this loop here. while (numberofClasses > 0) perhaps use an if statement? otherwise your program loops for forever, never asking for a new class number

Adding message when certain condition is met (Java)

Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!

Squaring and totaling in java

So the challenge is to prompt the user to enter an integer value "count". Next
prompt them to enter "count" more values. Then square each value entered and add it to a main
value sum.Then display the sum of the square of all the numbers entered.
An example of the build output is like :
Please enter an integer value: 3
Please enter 3 numeric values:
7 8 3.5
The sum of the squares of each of these numbers is: 125.25
I'm still new to learning code, so I'm a bit lost at how to square multiple values on a single user input and also totaling them up. Can anyone offer some help?
import java.util.Scanner;
public class Assign2 {
public static void main(String[] args) {
sum_squares();
}
public static void sum_squares(){
Scanner in = new Scanner(System.in);
System.out.println ("Please enter an integer value:");
int count = in.nextInt();
System.out.println ("Please enter" + count + "more values:");
int square = in.nextInt();
}
}
You need to add a for-loop after:
System.out.println ("Please enter" + count + "more values:");
The for-loop should run for count times, and each time the loop is run, it should ask the user for an input. You can then take that input and square it (remember - squaring is as easy as multiplying a number by itself! 2 * 2 = 4, or 2-squared) Once you have the squared number, add it to a sum variable which you will have created before the for-loop. Then just print out the sum after the for-loop.
Here is a great tutorial on for-loops!

Showing process completed but no output is coming up

I am trying to create a program that accepts two numbers and outputs the smallest digit in one number that is larger than the other number(for example, given 4687 and 5, the program should output 6).
The problem that I'm having is that when I compile the program, even though I'm getting no errors, after inputting the two numbers, no output is being shown. The cursor just continues blinking where it is. This is the code:
import java.io.*;
import java.util.*;
public class Numbers {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int smallest = 10;
int num;
System.out.printf("Enter a value for n: \n");
int n = in.nextInt();
System.out.printf("Enter a value for num: \n");
num = in.nextInt();
int ch = System.in.read();
while (ch>n && ch<smallest) {
smallest=ch;
ch = System.in.read();
}
System.out.printf("Smallest number that is larger is %d", smallest);
}
}
I ran your program just fine. What you are experiencing is probably just that the program is waiting on input from you that you do not expect to enter.
It's expecting three inputs from the user, is that how you ran it?
Did you remember to hit the enter button on your keyboard after you input the numbers?
Here's a sample output from your program:
Enter a value for n:
100
Enter a value for num:
2
0 // <-- This value corresponds to your program prompting for int ch = System.in.read();
Smallest number that is larger is 10D
HINT: You probably want to convert the value entered for n to a String, then use the toCharrArray() method on String so you can traverse each character, like what you're doing in the while loop.
Try something like:
for(char ch : Integer.toString(n).toCharArray()) {
// rest of your while loop logic
}

Java program high-low game

I wrote this in jQuery however the loop isn't right and I can't see my error? It doesn't end when a user inputs -99? Nor calculate the highest and lowest figure?
import java.util.Scanner;
public class LargestandSmallest
{
public static void main (String [] args)
{
//Create a Scanner object for the keyboard input
Scanner keyboard = new Scanner(System.in);
//Declare local variable
double number;
//Explain what the program does
System.out.println ("This program will ask you to enter in a series of");
System.out.println ("numbers, and then will display the lowest and");
System.out.println ("highest numbers, out of what you enter, until you input");
System.out.println ("the value indicated to end the program.");
//Have the user input a series of numbers and continue processing
//until the user enters -99
System.out.println ("Please enter a number: (or -99 to end the program).");
number = keyboard.nextDouble();
//Display the table headings
System.out.println ("Lowest\tHighest");
System.out.println ("------------------");
//Call the method to caluclate the highest and lowest numbers
calculateLowHigh(number);
}
//Module called calculateTemp
public static void calculateLowHigh(double number)
{
//Declare local calculation variables
double highestNumber = 0;
double lowestNumber = 0;
//Set the parameters for running the loop
while (number != -99)
{
for(number = 0; number < 5; number++)
{
//Calculate the lowest and highest numbers entered
if (number > highestNumber) {
highestNumber = number;
}
if (number < lowestNumber) {
lowestNumber = number;
}
}
}
//Display the results
System.out.println (lowestNumber + "\t\t" + highestNumber);
}
}
Your problem is that in calculateLowHigh, you're using the number variable for two different things. It's the parameter in which the number that the user typed is passed into this method; but you've also used it as the loop index inside the for loop. Maybe you should use a different variable for one or the other purpose. Better still, dispense with the for loop altogether - it doesn't seem to do anything.
Also, the while loop should be done in main, not in calculateHighLow, otherwise the user will only ever have the opportunity to input a number once.

Categories