I'm trying to print the count of numbers in the array that are greater than 5.5, but I have no idea where to start. I got the following code:
package les5;
import java.util.*;
public class Les5 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("How many numbers would you like to add? ");
int totalNumbers = s.nextInt();
double[] number = new double[totalNumbers];
for (int i = 1; i <= totalNumbers; i++) {
System.out.print("Number 1 " + i + ": ");
number[i - 1] = s.nextDouble();
}
int numbCount = number.length;
double avgNumber = Arrays.stream(number).sum() / number.length;
System.out.println("Numbers count: " + numbCount);
System.out.println("Average: " + avgNumber);
}
}
At the end it has to say: "Total numbers greater than 5.5: x"
Could anyone help me out?
Just iterate over the array and at each step check whether the current array element is greater than 5.5. If it is, increase a counter variable by 1.
double[] number = {10, 2, 3, 5, 6, 5.6};
int count = 0;
for (int i = 0; i < number.length; i++) {
if (number[i] > 5.5) {
count++;
}
}
System.out.println("Total numbers greater than 5.5: " + count);
public class Les5 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("How many numbers would you like to add? ");
int N = s.nextInt();
double[] number = new double[N];
//
int greaterThan5 = 0;
for (int i = 0; i <= totalNumbers; i++) {
System.out.print("Number " + i + ": ");
number[i] = s.nextDouble();
if(number[i] >5.5)
greaterThan5++;
}
int numbCount = number.length;
double avgNumber = Arrays.stream(number).sum() / number.length;
System.out.println("Numbers count: " + numbCount);
System.out.println("Average: " + avgNumber);
System.out.println("Greater than 5: " + greaterThan5);
}
}
Related
I am trying to find sum and averags of user inputed numbers and i also Need my program to only sum the positive numbers entered.
It needs to calculate only the positive numbers sum and ignore the negative inputs, would i put my num=0 or not?
import java.util.Scanner;
public class J12ForSumPos {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int maxNumbers, i, num, average;
int sum = 0;
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for (i = 1; i <= maxNumbers; i = i + 1) {
System.out.print("Enter Value " + i + ": ");
num = console.nextInt();
sum = sum + num;
}
average = sum / maxNumbers;
if (sum >= 0) {
System.out.println();
System.out.println("Sum: " + sum);
System.out.println();
System.out.println("Average: " + average);
System.out.println();
} else {
System.out.println("Sum is: " + sum * 0);
System.out.println();
System.out.println("Cannot Calculate Average - no positives entered");
}
}
}
You can try something like this:
Scanner console = new Scanner(System.in);
int maxNumbers = 0;
int totalSum = 0; // Sum of all numbers (positive and negative)
int totalAverage = 0; // Average of all numbers (positive and negative)
int positiveSum = 0; // Sum of all positive numbers
int positiveAverage = 0; // Average of all positive numbers
int positiveNumberCount = 0; // Amount of positive numbers entered
System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();
for(int i=1; i<=maxNumbers; i=i+1)
{
System.out.print("Enter Value " + i + ": ");
int num = console.nextInt();
if(num >= 0) {
positiveSum = positiveSum + num;
positiveNumberCount = positiveNumberCount + 1;
}
totalSum = totalSum + num;
}
positiveAverage = positiveSum / positiveNumberCount;
totalAverage = totalSum / maxNumbers;
It's up to you to decide whether or not to include 0 as a positive or a negative number, or exclude it. In my example it's being treated as a positive number.
I want to calculate the average numbers using arrays. I want the program asks for the amount of grades and after I want to put the grade numbers.
After I want to get the average output in a double.
This is my code so far:
public class Average {
public static void main(String[] args)
{
//int n = MyConsole.readInt("Enter number of grades: " );
int a = MyConsole.readInt("Enter grade 1: " );
int b = MyConsole.readInt("Enter grade 2: " );
int c = MyConsole.readInt("Enter grade 3: " );
int[] numbers = new int[]{a,b,c};
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Average value of array elements is : " + average);
}
}
Don't know what your class MyConsole is doing, but I guess is a Scanner:
Your code improved will be something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of grades: " );
int n = sc.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.print("Enter grade "+ (i + 1) + ": ");
int a = sc.nextInt();
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
}
OUTPUT (2 grades):
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 5
Average value of array elements is : 3.0
OUTPUT (5 grades):
Enter number of grades: 5
Enter grade 1: 10
Enter grade 2: 20
Enter grade 3: 30
Enter grade 4: 10
Enter grade 5: 50
Average value of array elements is : 24.0
NOTE
double average = sum / n;
performs an int division, so you won't have any decimal places! I would propose a fast cast:
double average = sum / (double) n;
With new output:
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 4
Average value of array elements is : 2.5
GUESS using your own class:
public static void main(String[] args) {
int sum = 0;
int n = MyConsole.readInt("Enter number of grades: " );
for (int i = 0; i < n; i++) {
int a = MyConsole.readInt("Enter grade "+ (i + 1) + ": ");
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
thank you !
Sorry for the poor explanation.
This is my first question
this it the code after edit:
import java.util.Scanner;
public class Average {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of grades: ");
int n = sc.nextInt();
int sum = 0;
int[] numbers = new int[n];
for(int i=0; i < numbers.length ; i++)
{
System.out.println("Enter grade " + (i + 1) + " :");
int a = sc.nextInt();
sum = sum + a;
}
double average = sum / (double) n;
System.out.println("Average value of array elements is : " + average);
sc.close();
}
}
Program to Calculate Average Using Arrays:
public class Inter1 { //name of the class
public static void main(String[] args) {//main method
int number[]={40,56,23,56,87,23,78}; //declaring the int array
int sum=0;
for (int s:number){ //for each
sum +=s;
}
int ave=sum/number.length; //to get the average
System.out.println("the average is "+ave); //out put
}
}
package inter1;
import static java.time.Clock.system;
import java.util.Scanner;
public class Inter1 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int total=0;
System.out.println("Enter how many number that do u wanna enter ?? ");
int num= in.nextInt();
int numbers[]=new int[num];
for (int i=0;i<numbers.length;i++){
System.out.println(i+1+":"+"enter the your numbers ? ");
numbers[i]=in.nextInt();
}
for (int i=0;i<numbers.length;i++){
total+=numbers[i];
}
int average =total/numbers.length;
System.out.println("the average is "+average);
}
}
public class Inter1 { //name of the class
public static void main(String[] args) { //main method
System.out.println("==============================");
int num[]={34,56,78,78,34,2,33,99,100,56}; //int array
int total=0;
for (int i=0;i<num.length;i++){ //for loop
total+=num[i];
}
int avrage1=total/num.length; //output
System.out.println("The average is "+avrage1);
}
}
Trying to let users enter number of integers so I can set array length then find the max and min value. However, I can't find max and min. Please help.
import java.util.Scanner;
import java.util.Arrays;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
System.out.println("Enter some integers:");
int integers = keyboard.nextInt();
int numbers [] = new int [numberEnter];
int maxValue = numbers[0];
int minValue = numbers[0];
int max = 0;
int min = 0;
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
You don't seem to be entering more then one value (and you never store integers in your array). Also, you aren't setting the min. I think you wanted
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number of integers to enter:");
int numberEnter = keyboard.nextInt();
int numbers[] = new int[numberEnter];
int pos = 0;
do {
System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
numbers[pos++] = keyboard.nextInt();
} while (pos < numberEnter && keyboard.hasNextInt());
int min = numbers[0];
int max = numbers[0];
for (pos = 1; pos < numbers.length; pos++) {
if (numbers[pos] < min) { // <-- test min.
min = numbers[pos];
}
if (numbers[pos] > max) { // <-- test max.
max = numbers[pos];
}
}
// Display everything.
System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
min, max);
}
Your numbers[] is empty. The user's input is not stored into the array.
Here is your fixed code:
package com.company;
import java.util.Scanner;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
int numbers [] = new int [numberEnter];
for (int i = 0; i < numberEnter; i++) {
System.out.println("Enter integer:");
numbers[i] = keyboard.nextInt();
}
int maxValue = numbers[0];
int minValue = numbers[0];
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
import java.util.Scanner;
class StdR {
public static void main(String[] args) {
// TODO Auto-generated method stub
StdR st = new StdR();
st.stdR();
//System.out.println(st.stdR();
}
void stdR()
{
char[] grade = {'A','B','C','D','E','F'};
Scanner input = new Scanner(System.in);
byte[] st = new byte[3];
double[] percentage = new double[st.length];
for(byte s = 0; s < st.length; s++){
System.out.println("\nStudent " + s);
short noOfMarks = 0;
short totalMarks = 450;
percentage[s] = 0.0;
byte[] marks = new byte[5];
for (byte i = 0; i < marks.length; i++){
System.out.println("Enter marks of Chapter "+ i + ": ");
marks[i] = input.nextByte();
noOfMarks += marks[i];
percentage[s] += (marks[i] * 100) / totalMarks;
}
System.out.print("No of marks: " + noOfMarks + "\t");
System.out.print("Percentage: " + percentage[s] + "\t");
if (percentage[s] > 79.0 && percentage[s] < 100.1)
System.out.print("Grade: " + grade[0]);
else if (percentage[s] > 69.0 && percentage[s] < 80.0)
System.out.print("Grade: " + grade[1]);
else if (percentage[s] > 59.0 && percentage[s] < 70.0)
System.out.print("Grade: " + grade[2]);
else if (percentage[s] > 49.0 && percentage[s] < 60.0)
System.out.print("Grade: " + grade[3]);
else if (percentage[s] > 39.0 && percentage[s] < 50.0)
System.out.print("Grade: " + grade[4]);
else if (percentage[s] < 40.0)
System.out.print("Grade: " + grade[5]);
}
double smallest = percentage[0] , largest= percentage[0];
for (int i=0 ;i< percentage.length; i++) {
if (percentage[i] < smallest) {
smallest = percentage[i];
} // end finding smallest
if (percentage[i] > largest) {
largest = percentage[i];
}
}
System.out.println("\n1st Position and Top percentage is " + largest);
System.out.println("\nLast Position and Least percentage is "+smallest);
}
}
Guys can you please help me answer this exercise using for loop without using string methods.
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should output the individual digits of 3456 as 3 4 5 6 and the sum as 18,and output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the code:
package MyPackage;
import java.util.*;
public class Integer
{
public static void main(String args[])
{
Scanner console = new Scanner (System.in);
int input;
int sum = 0;
int num1 = 0;
int counter = 1;
String num = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input))
{
input = input * (-1);
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
}
else
{
num = String.valueOf(input);
num1 = num.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < num1; i++ )
{
String var = num.substring(i,counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}
Iterating all the digits from right to left is easy enough - you just keep dividing by 10 and keeping the remainder.
Since you need to print them from left to right, but there don't seem to be any constraint on the memory usage, you could just keep them in a list, and print it backwards:
int num = ...; // inputed from user
List<Integer> digits = new LinkedList<>();
int sum = 0;
// Extract the digits and the sum
while (num != 0) {
int digit = num % 10;
digits.add (digit);
sum += digit;
num /= 10;
}
// Print backwards:
System.out.print ("The digits are: ");
for (int i = digits.size() - 1; i >= 0; --i) {
System.out.print (digits.get(i) + " ");
}
System.out.println();
System.out.println("Their sum is: " + sum);
For some reason the average is being populated wrong when I pass the array to the method I get a really low percent. It almost seems like since the Array shotsMade is only recording integers for made shots and not misses it is not calculating off the right base.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//main
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//class
You are calculating the avarage of 5 numbers but you only set 2. So if all shots hit your array will look like this: 10, 10, 0, 0, 0 and the avarage will be 4.
Old issue, you are using integer arithmetic total / nums.length with returns you an int value. You later assign it to a float, but the value already has been truncated.
Just change one of the values to float before the division, v.g. ((float) total) / num
Among others, your expression
float f = (total / nums.length);
will yield an inaccurate result.
Both total and nums.length are integers, and any operation between integers always results in an integer.
Example: if total=10 and nums.length=3, you'd expect the result to be 3.333... but actually the result is just 3. Only after that do you cast it to a float, resulting in 3.0.
To get the required result, you need to cast both integers to floats before dividing:
float f = (float) total / (float) nums.length;