Problem: Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the average and max. A negative integer ends the input and is not included in the statistics.
Ex: When the input is:
15 20 0 5 -1
the output is:
10 20
You can assume that at least one non-negative integer is input.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.println(avg + " " + max);
}
}
I had a lot of trouble with this problem. Is there any way I could have done this without having to do count -1 while computing the average?
Also, is this this the most efficient way I could have done it?
How about this? If you have questions from the implementation, please ask.
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
while (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
num = scnr.nextInt();
}
int avg = count == 0 ? 0 : total/count;
System.out.println(avg + " " + max);
}
If you use while loop instead of do-while loop, you don't have to count the negative number input anymore. And no, it's not the most efficient way, but it's a good start!
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userNum;
int maxNum = 0;
int totalSum = 0;
int averageNum;
int count = 0;
userNum = scnr.nextInt();
while (userNum >= 0) {
if (userNum > maxNum) {
maxNum = userNum;
}
totalSum += userNum;
++count;
userNum = scnr.nextInt();
}
averageNum = totalSum / count;
System.out.println("" + averageNum + " " + maxNum);
}
}
int Num;
int max = 0;
int total = 0;
int average;
int count = 0;
Num = scnr.nextInt();
while (Num >= 0) {
if (Num > max) {
max = Num;
}
total += Num;
++count;
Num = scnr.nextInt();
}
average = total / count;
System.out.println("" + average + " " + max);
}
}
Related
How could I use the following method to sum the integers of two numbers in a separate method? I'm trying to teach myself how to use overloaded methods but this is starting to confuse me. Thanks!
public static void sumNUmber(){
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
System.out.println(sum);
public static void main(String[] args) throws ClassNotFoundException {
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println(sumDigits(num));
}
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
output
Enter a number
234
9
You probably want to take your core algorithm and put it into a single function and then call it twice, once for each number. For example,
// Core algorithm.
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
public static void sumNumber() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int numA = in.nextInt();
System.out.println("Enter another number");
int numB = in.nextInt();
int totalDigits = sumDigits(numA) + sumDigits(numB);
System.out.println(totalDigits);
}
//Merry Xmas :D
public int sumNumbers(int num) {
int returnval;
if (num < 10) {
return num;
} else if (num < 100) {
returnval = Math.floor(num/10) + (num%10);
} else if (num < 1000) {
returnval = Math.floor(num/100) + Math.floor(num/10) + (num%10);
} //repeat as needed
return 0;
}
I want to create program read more than 10 numbers from the user and find the maximum number and minimum number then print all the numbers from the user.
This is my program, but I don't know how can I find the maximum number and minimum number:
import java.io.*;
public class ass3 {
public static void main (String [] args) throws IOException
{
int times , num1 ;
int max , min;
System.out.print("How many numbers you want to enter?\n*moer than five number");
times=IOClass.getInt();
if (times>5) {
for(int i = 0;i<times;i++){
System.out.println("please type the "+i+ "number");
num1=IOClass.getInt();
}
}
}
}
If you initialize the min and max like this:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
You can check whether the new number is smaller than min or bigger than max, and change them if needed:
int num = ...;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
This is my solution, hope it helps:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to enter?\nThe number must be grater than 5");
int times = in.nextInt();
if (times > 5)
{
int[] numbers = new int[times];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < times; i++)
{
System.out.println("Please type the " + i + " number:");
int number = in.nextInt();
numbers[i] = number;
if(number < min)
{
min = number;
}
if(number > max)
{
max = number;
}
}
System.out.println("Max: " + max);
System.out.println("Min: " + min);
}
in.close();
}
}
I am working on an assignment which prompts the user to input an integer, and displays that integer with the digits separated by spaces, and provides the sum of those digits. I have this working, but my individual digit display is form the last digit to the first. How can I make it display the digits from first to last?
Here is what I have so far:
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
System.out.print(" " + temp + " ");
}while (num > 0);
System.out.println("The sum of the digits = " + sum);
}
}
One option would be to use the String#valueOf(Integer) method.
Example
int input = 12345;
String inputStr = String.valueOf(input);
for(char c : inputStr.toCharArray()) {
// Print out each letter.
}
if you use the method String.valueOf(12345)
you can easily reverse the String with the method in this library:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse(java.lang.String)
StringUtils.reverse(String.valueOf(input));
Here is the solution
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
ArrayList<Integer> values = new ArrayList<>();
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
values.add(temp);
}while (num > 0);
Collections.reverse(values);
Iterator<Integer> it = values.iterator();
while(it.hasNext()){
System.out.println(" "+it.next()+" ");
}
System.out.println("The sum of the digits = " + sum);
}
}
BTW you should have to import ArrayList etc.
I would highly recommend putting the number into a String and then reading it, parsing it, and use the number however you want. As follows,
int input = 12345;
String inputString = input + "";
int sum = 0;
for (int i = 0; i < inputString.length(); i++) {
sum += Integer.parseInt(inputString.charAt(i) + "");
}
System.out.println(sum);
However an alternative way, not as pretty is..
int input = 12345;
int sum = 0;
while (input > 0) {
int i = (input + "").length() - 1;
int n = (int) (input / Math.pow(10, i));
input -= (int) (n * Math.pow(10, i));
sum += n;
}
System.out.println(sum);
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);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 months ago.
Improve this question
I could get the largest without using arrays but, unable to get the smallest one.
public static void main(String[] args)
{
int smallest=0;
int large=0;
int num;
System.out.println("enter the number");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
for(int i=0;i<n;i++)
{
num=input.nextInt();
if(num>large)
{
large=num;
}
System.out.println("the largest is:"+large);
//gives the largest number in n numbers
code for the smallest..
if(i==0&&num>0)
small=num;
if(num<small)
small=num;
System.out.println(small);
}
Try this :
int smallest = Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
num=input.nextInt();
if(num>large)
{
large=num;
}
if(num<smallest){
smallest=num;
}
public static void main(String[] args) {
int smallest = 0;
int large = 0;
int num;
System.out.println("enter the number");//how many number you want to enter
Scanner input = new Scanner(System.in);
int n = input.nextInt();
num = input.nextInt();
smallest = num; //assume first entered number as small one
// i starts from 2 because we already took one num value
for (int i = 2; i < n; i++) {
num = input.nextInt();
//comparing each time entered number with large one
if (num > large) {
large = num;
}
//comparing each time entered number with smallest one
if (num < smallest) {
smallest = num;
}
}
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
Try this...This simple
import java.util.Scanner;
class numbers
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if ( x > y && x > z )
System.out.println("First number is largest.");
else if ( y > x && y > z )
System.out.println("Second number is largest.");
else if ( z > x && z > y )
System.out.println("Third number is largest.");
else
System.out.println("Entered numbers are not distinct");
}
}
public class Main {
public static void main(String[] args) {
int i = 10;
int j = 20;
int k = 5;
int x = (i > j && i > k) ? i : (j > k) ? j : k;
int y = (i < j && i < k) ? i : (j < k) ? j : k;
System.out.println("Largetst Number : "+x);
System.out.println("Smallest Number : "+y);
}
}
Output:
Largetst Number : 20
Smallest Number : 5
Try the code mentioned below
public static void main(String[] args) {
int smallest=0; int large=0; int num;
System.out.println("enter the number");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
num=input.nextInt();
smallest = num;
for(int i=0;i<n-1;i++)
{
num=input.nextInt();
if(num<smallest)
{
smallest=num;
}
}
System.out.println("the smallest is:"+smallest);
}
#user3168844: try the below code:
import java.util.Scanner;
public class LargestSmallestNum {
public void findLargestSmallestNo() {
int smallest = Integer.MAX_VALUE;
int large = 0;
int num;
System.out.println("enter the number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int i = 0; i < n; i++) {
num = input.nextInt();
if (num > large)
large = num;
if (num < smallest)
smallest = num;
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
}
public static void main(String...strings){
LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
largestSmallestNum.findLargestSmalestNo();
}
}
import java.util.Scanner;
public class LargestSmallestNum {
public void findLargestSmallestNo() {
int smallest = Integer.MAX_VALUE;
int large = 0;
int num;
System.out.println("enter the number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int i = 0; i < n; i++) {
num = input.nextInt();
if (num > large)
large = num;
if (num < smallest)
smallest = num;
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
}
public static void main(String...strings){
LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
largestSmallestNum.findLargestSmalestNo();
}
}
import java.util.Scanner;
public class LargestSmallestNumbers {
private static Scanner input;
public static void main(String[] args) {
int count,items;
int newnum =0 ;
int highest=0;
int lowest =0;
input = new Scanner(System.in);
System.out.println("How many numbers you want to enter?");
items = input.nextInt();
System.out.println("Enter "+items+" numbers: ");
for (count=0; count<items; count++){
newnum = input.nextInt();
if (highest<newnum)
highest=newnum;
if (lowest==0)
lowest=newnum;
else if (newnum<=lowest)
lowest=newnum;
}
System.out.println("The highest number is "+highest);
System.out.println("The lowest number is "+lowest);
}
}