I am using a scanner class to average numbers together. I am using a method to do the averaging. I do not want the program to run if there are more than 20 args. I cant seem to get this to work. I am very new at java and trying to learn.
I appreciate any help I can get. Thanks!
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double x = 0.00d;
if (args != null) {
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
x = scan.nextInt();
if (x <= 21) {
System.out.println("Please do not add more than 20 numbers");
}
} else {
}
}
public double average(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}
Just run a while loop that breaks when 20 "args" is met or until a break like -1 is entered. Then if you are taking double values, you should use x = scan.nextDouble(). You also do not have a place where you are inserting the values into your array. At the end of your while loop you could put x into an array of doubles.
private double x;
private double Foo[] = new Foo[20];
private int this = 0; //Your counter
while(this < 20 && x != -1)
{
x = scan.nextDouble();
Foo[this++] = x;
}
Then carry out your public double Average by adding up the values in the array and dividing by (double)this
Here is a solution (cleaning up a lot of your code as well) that gets all the numbers on one line after the start of the program:
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double values[] = new double[20];
int count = 0;
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
String inputs = scan.nextLine();
scan = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan.hasNextDouble())
{
if(count == 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
values[count] = scan.nextDouble();
count += 1;
}
System.out.println("Your average is: " + average(values, count));
}
public static double average(double [] values, int count) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= count;
return average;
}
}
I got thinking you might want to use the args that are passed to main, since you use a null check, so you want to run your program like this:
java programTwo num1 num2 num3 num4 num5
etc. If that's the case, we have another solution:
class programTwo {
public static void main (String[] args) {
if(args.length > 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
double values[] = new double[args.length];
for(int i=0; i< args.length; ++i)
values[i] = Double.valueOf(args[i]);
System.out.println("Your average is: " + average(values));
}
public static double average(double [] values) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= values.length;
return average;
}
}
The args != null check is unnecessary. One way to accomplish what you want is to accept numbers while the scanner has a next number (scanner.hasNext() perhaps) and break if the number of inputs thus far is less than 20. Since the number of double numbers is unknown, you're better off using an ArrayList.
List<Double> doubles = new ArrayList<Double>();
and calling the add method on doubles
doubles.add(x);
Then pass this to a method that averages the values in the arraylist.
Related
I am working on a java code that calculates the average of grades in an array for N of students and it is working fine when I enter grades like {3,4,3} but when I use numbers with decimals like {3.7,2.5,3.2} it starts giving me errors and I want to make a class of data type Students for example.
import java.util.*;
public class ArrayAverageProblem {
public static void main(String[] args) {
System.out.println("Enetr number of students : ");
Scanner adnan = new Scanner(System.in);
int length = adnan.nextInt();
int[] input = new int[length];
System.out.println("Enter cgpa of students : ");
for (int i = 0; i < length; i++) {
input[i] = adnan.nextInt();
}
double averageCgpa = averageCgpa(input);
System.out.println("Average of students cgpa : " + averageCgpa);
adnan.close();
}
public static double averageCgpa(int[] input) {
double sum = 0f;
for (int number : input) {
sum = sum + number;
}
return sum / input.length;
}
}
Any help would be really appreciated.
i improved your code to use double numbers.
note that your grades must be double and use nextDouble() method to get grade from scanner.
this code is below
public static void main(String[] args) {
System.out.println("Enetr number of students : ");
Scanner adnan = new Scanner(System.in);
int length = adnan.nextInt();
double[] input = new double[length];
System.out.println("Enter cgpa of students : ");
for (int i = 0; i < length; i++) {
input[i] = adnan.nextDouble();
}
double averageCgpa = averageCgpa(input);
System.out.println("Average of students cgpa : " + averageCgpa);
adnan.close();
}
public static double averageCgpa(double[] input) {
double sum = 0f;
for (double number : input) {
sum = sum + number;
}
return sum / input.length;
}
Problem is with the input array datatype. If input array is also expecting double value (with decimal) you need to take the input array as double.
Please change the below line
int[] input = new int[length];
with
double[] input = new double[length];
and below line
input[i] = adnan.nextInt();
with
input[i] = adnan.nextDouble();
It will work for both the types of numbers(with and without decimal).
I hope this will solve the issue you're facing.
In java if both are int, result is also int.
So you can use sum / Double.valueOf(input.length);
i seem to be having trouble figuring out what to set the variable intValue to under the read value methods. The program is supposed to take 10 integers and average them, it works fine as far as catching exceptions and input, but the output displays all the numbers as 0 (because i set it to 0 temporarily but can not figure out what to change it to). Heres the code
package averagenumdriver;
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class AverageOfIntegers {
//Declare variables
private int numberOfValues;
private int[] integerValues;
private double average;
public AverageOfIntegers(int numberOfValues){
this.numberOfValues = numberOfValues;
}
//Define the readValues()
public void readValues(){
String stringValue = null;
int intValue = 0, i;
Scanner console = null;
i = 0;
integerValues = new int[numberOfValues];
while(i < numberOfValues){
try
{
console = new Scanner(System.in);
System.out.print("Enter value : ");
//read the value
stringValue = console.nextLine();
//check for number
intValue = 0;
parseInt(stringValue);
//Store only integer values
integerValues[i++] = intValue;
}
catch(NumberFormatException ex)
{
//Catch exception and handle it
System.out.println("Invalid Number entered" + "Reenter again ");
continue;
}
}
}
//read integer values
public void printValues()
{
System.out.println("Given values are ");
for (int i = 0; i < numberOfValues; i++)
{
System.out.println("Number: " + (i + 1) + " = " +
integerValues[i]);
}
}
public double getAverage()
{
int sum = 0;
//Calcualte the sum of integer values
for (int i = 0; i < numberOfValues; i++)
{
sum += integerValues[i];
}
//calculate average
average = (double)sum / numberOfValues;
return(average);
}
}
EDIT* question seems to be marked as a duplicate, but I am not asking about why division with two integers where the denominator is greater than numerator yields a 0.
Change
//check for number
intValue = 0;
parseInt(stringValue);
TO
//check for number
intValue = parseInt(stringValue);
I know that scanf is not a java function, so i'm hoping someone can help me to understand how to convert this. Research on this topic is difficult to piece together.
This is my code:
import java.util.Scanner;
public class Average {
Scanner Scanner = new Scanner (System.in);
int main (){
int counter;
int number;
int total;
float average;
total = 0;
counter = 0;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
While (number != 0) {
total = total + number;
counter = counter + 1;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
}
if(counter != 0) {
average = (float) total / counter;
System.out.println("Average is %.2f\n", average);
} else {
System.out.println("No valid numbers have been entered.");
return 0;
}
}
}
use input like this`
public class seting{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);`
int total = 0;
System.out.printlnln("Enter the value of total :");
total = scan.nextInt(); // use integer input
}
}
You cannot use the same name for the object as for the class. Change Scanner initialization as follows:
Scanner scanObj = new Scanner(System.in);
Replace all your scanf statements with the below:
number = scanObj.nextInt();
These are the changes done to your code:
import java.util.Scanner;
public class one {
public static void main(String[] args) {
Scanner Scanner = new Scanner (System.in);
int counter;
int number = 1;
int total;
float average;
total = 0;
counter = 0;
while(number != 0){
System.out.println("Enter the number 0 to end: ");
number = Scanner.nextInt();
System.out.printf("%d", number);
total = total + number;
counter = counter + 1;
}
if(counter != 0){
average = ((float)total /(float)counter);
System.out.printf("Average is %.2f\n", average);
}
else{
System.out.println("No valid numbers have been entered.");
//return 0;
}
}
}
First the Scanner takes the value the user entered. number = Scanner.nextInt(); This must be done inside your while loop since its the one that check the condition.
The next thing I changed was average = (float) total / counter;
This casts the total value only to a float. use brackets to both ends.
average = ((float)total /(float)counter); like this
Im' trying to get user input if he presses "a", he can do the average, calls in average method if he types in "s", he uses the sum method.
Im new to enums so im experimenting. I made an enum that stores a,b and am trying to compare it's values to user input using scanner.
I could be using if statements and forget the whole enum thing but i want to know how it works.
thanks.
public enum RecursionEnum {
s, a
}
main class:
import java.util.*;
public class Recursion {
static RecursionEnum enumtest;
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (enumtest) {
case a:
average();
case s:
sums();
}
}
public static void main(String[] args) {
yn();
}
public static int sums() {
int i = 0;
int j = 0;
int sum = i + j;
return sum;
}
public static double average() {
Scanner avgs = new Scanner(System.in);
System.out.println("Enter total number of numbers; ");
double tnum = avgs.nextDouble();
double[] nums = new double[(int) tnum];
double sum = 0;
for (int i = 0; i < tnum; i++) {
System.out.println("Enter number " + (i + 1) + " : ");
nums[i] = avgs.nextDouble();
sum += nums[i];
}
System.out.println(" ");
double avg = sum / tnum;
return avg;
}
}
This is the output:
Enter a for average or s for sum
a
Exception in thread "main" java.lang.NullPointerException
at com.towerdef.shit.Recursion.yn(Recursion.java:14)
at com.towerdef.shit.Recursion.main(Recursion.java:26)
Enumerable types have a synthetic static method, namely valueOf(String), which will return an enum instance matching the input, if it exists. Note that the input is case-sensitive in this case. Trim is used to deal with potential extraneous whitespace.
You can switch on that:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (RecursionEnum.valueOf(answer.trim())) {
case a:
average();
case s:
sums();
}
}
Of course, on Java 7 and higher, you can switching on strings. You may thus use:
public static void yn() {
Scanner boges = new Scanner(System.in);
System.out.println("Enter a for average or s for sum");
String answer = boges.nextLine();
switch (answer.trim()) {
case "a":
average();
break;
case "s":
sums();
break;
}
}
I am in the middle of an exercise on arrays and I am currently stuck on one of the variations in which
I have to use an Array (no arraylists) to gather user input with a
max number of 100 inputs and the inputs must stop if a negative
number is inserted.
The program then prints each value input by the user on a separate
line with the "Above", "Below", or "EqualTo" relating to the average
of the inputs.
Issue :- I am currently stuck in how I am supposed to get the value of the inputs from the load method into the correct spots on the print method. The program will compile but will only return an average1 equal to zero. Any help is appreciated, I just can't use an arraylist
import java.util.Scanner;
public class ScoreSetNumber3
{
private int[] scores;
private static final int SIZE= 100;
private double average1;
Scanner keyboard = new Scanner(System.in);
public ScoreSetNumber3()
{
scores = new int[SIZE];
}
public void load()
{
System.out.println("Please enter scores");
double sum = 0;
for( int used = 0; used < scores.length; used++)
{
scores[used] = keyboard.nextInt();
if(scores[used] >= 0)
{
sum += scores[used];
}
else
{
System.out.println("End of Inputs");
double average1 = sum / used;
System.out.println("Average value of array elements is" + " " + average1);
break;
}
}
}
public double getAverage()
{
return average1;
}
public void print()
{
for(int used=0; used < scores.length; used++)
{
if(scores[used] > getAverage())
{
System.out.println(scores[used] + " Above");
}
else if(scores[used] == getAverage())
{
System.out.println(scores[used] + " EqualTo");
}
else
{
if(scores[used] < 0)
{
break;
}
System.out.println(scores[used] + " Below");
}
}
}
}
That's because you are not saving the average to the global variable average1 but to a local variable. That is why average1 returned by getAverage() equal to zero.
Change the below line in load() method from
double average1 = sum / used;
to
average1 = sum / used;