minimum of integers - java

package variousprograms;
import java.util.*;
public class InputStats
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int a;
int b;
int c;
int d;
int e;
System.out.println("First Integer ");
a = input.nextInt();
System.out.println("Second Integer ");
b = input.nextInt();
System.out.println("Third Integer ");
c = input.nextInt();
System.out.println("Fourth Integer ");
d = input.nextInt();
System.out.println("Fifth Integer ");
e = input.nextInt();
System.out.println("Maximum is " + Math.max(Math.max(Math.max(Math.max(a,b), c), d), e));
System.out.println("Minimum is " + Math.min(Math.min(Math.min(Math.min(a,b), c), d), e));
System.out.println("Mean is " + (a + b + c + d + e)/5.0);
}
}
I wrote this code to find the minimum, maximum, and mean of a set of five integers using five variables for each integer. The problem is that I am supposed to use four variables instead of five, and I cannot use control statements such as if or loop.
How should I change the code I already wrote?

You could do it with variables for the current input, min, max, and total. Just keep re-using the same variable for input, and update the other three variables before you get the next input from the user.
To keep track of the maximum value without if statements, you'll have to do something like:
max = Math.max(max, input);
And something similar for the minimum value.

You don't need to store the inputs any longer than necessary, just store the results as you go:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int min;
int max;
long total;
int val;
System.out.println("First Integer ");
val = input.nextInt();
min = val;
max = val;
total = val;
System.out.println("Second Integer ");
val = input.nextInt();
min = Math.min(val, min);
max = Math.max(val, max);
total += val;
System.out.println("Third Integer ");
val = input.nextInt();
min = Math.min(val, min);
max = Math.max(val, max);
total += val;
System.out.println("Fourth Integer ");
val = input.nextInt();
min = Math.min(val, min);
max = Math.max(val, max);
total += val;
System.out.println("Fifth Integer ");
val = input.nextInt();
min = Math.min(val, min);
max = Math.max(val, max);
total += val;
System.out.println("Maximum is " + max);
System.out.println("Minimum is " + min);
System.out.println("Mean is " + total / 5.0);
}

Related

How do I get Java to read the lowest float number

So I wrote this code that reads the User's lowest and highest float number. However, it reads the highest number fine, but it doesn't read the lowest number. I'm not
sure what I did wrong.
public static void main(String []args)
{
float cat=(float) 0.0;
float highest = (float) 0.0;
float lowest = (float) 0.0;
Scanner scan = new Scanner(System.in);
for (double i=0.00; i<2; i++) {
System.out.print("Enter a number:");
cat = scan.nextFloat();
if (cat > highest) {
highest = cat;
}
else if(cat < lowest) {
lowest = cat;
//I think it has something to do with the line above with lowest=cat
}
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}}
The test for highest and lowest are independent. You should not have an "else" joining them.
You should also consider what would happen if all the number are negative.
First, initialize highest with a value lower than anything the user is likely to enter (and lowest with a value greater than anything the user is likely to enter). You don't use i other than as a loop counter, so I would make it an int. You don't use cat except as a local variable containing the current user input (so I would limit the scope to the loop body). Finally, you can use Math.max(float, float) and Math.min(float, float) to simplify your logic. Like,
public static void main(String[] args) {
float highest = Float.MIN_VALUE;
float lowest = Float.MAX_VALUE;
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
System.out.print("Enter a number:");
float cat = scan.nextFloat();
highest = Math.max(highest, cat);
lowest = Math.min(lowest, cat);
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}
You always compare your input with lowest value 0.your code will only show exact output when you will take negative value input but not for positive one. here is the exact solution of your code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float cat=(float) 0.0;
float highest = (float) 0.0;
float lowest = (float) 0.0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number:");
cat = scan.nextFloat();
highest=cat;
lowest=cat;
//assignt first input to both so it can compare with next input
for (int i=0; i<(number_of_input -1); i++) { //here i compare with (number of input -1) beacuse you have already taken a input before
System.out.print("Enter a number:");
cat = scan.nextFloat();
if (cat > highest) {
highest = cat;
//System.out.println("Highest number is: " + highest);
}
else if(cat < lowest) {
lowest = cat;
//System.out.println("Lowest number is: " + lowest);
}
}
System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
}
}

Prompting user for only positive number

this basic JAVA program should prompt the user, and print "Negative numbers are not allowed" until user enters a positive number. This must be handled by using while loop. how does it work ? This is my first post in stack overflow.
public static void main(String[] args)
{
System.out.print("Welcome to Box Price Calculator");
System.out.print(System.lineSeparator());
System.out.print(System.lineSeparator());
int boxVol = 20 ;
double price_each_box = 2.99;
System.out.print("Bottles :");
Scanner input = new Scanner(System.in);
int numberOfbottles = 1;
numberOfbottles = input.nextInt();
boolean valid = false;
while (input.nextInt() < 0){
System.out.println("Negative numbers are not allowed");
numberOfbottles = input.nextInt();
}
int box = (numberOfbottles / boxVol);
System.out.println("Box Needed : " + box);
double totPrice = (box * price_each_box);
System.out.println("Total Cost : $" + totPrice);
int leftOver = (numberOfbottles -(box * boxVol));
System.out.println("Unboxed :" + leftOver);
}
}
The problem here is that you are reading and compare again with input.nextInt() and not with numberOfbottles, inside the while condition. What you should do is to use a do...while and compare it with your variable numberOfbottles:
public static void main(String[] args)
{
System.out.print("Welcome to Box Price Calculator");
System.out.print(System.lineSeparator());
System.out.print(System.lineSeparator());
int boxVol = 20 ;
double price_each_box = 2.99;
java.util.Scanner input = new java.util.Scanner(System.in);
int numberOfbottles;
do
{
System.out.println("Bottles (Negative numbers are not allowed):");
numberOfbottles = input.nextInt();
}
while (numberOfbottles < 0);
int box = (numberOfbottles / boxVol);
System.out.println("Box Needed : " + box);
double totPrice = (box * price_each_box);
System.out.println("Total Cost : $" + totPrice);
int leftOver = (numberOfbottles -(box * boxVol));
System.out.println("Unboxed :" + leftOver);
}

How do I show the numbers I entered in Java

I'm writing a program where at the end I have to display the numbers I entered and the maximum and minimum of those entered numbers. However I'm running into a little problem, here is my code,
import java.util.*;
public class question3controlstructures {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
numbersinput ++;
System.out.println("do you want to enter another number?");
answer = in.next();
sum = sum + numberEntered;
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
}
}
The above comment are absolutely useful. However, here is little code
package com.mars;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question3controlstructures {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (scan.hasNextInt()) {
list.add(scan.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
int sum = 0;
int i = 0;
for ( ; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("sum..." + sum);
System.out.println("The average is: " + sum / i);
System.out.println(i);
System.out.println("max.. "+Collections.max(list));
System.out.println("min.. "+Collections.min(list));
scan.close();
}
}
As suggent in comments , you need a list to store the multiple numbered entered.
just compare the min and max every time you enter a number
int min = Integer.MAX_VALUE
int max = Integer.MIN_VALUE
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
System.out.println("YOU HAVE ENTERED: " + numbersEntered);
if (min > numberEntered) min = numberEntered;
if (max < numberEntered) max = numberEntered;
numbersinput ++;
sum = sum + numberEntered;
System.out.println("do you want to enter another number?");
answer = in.next();
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
//you can print your min max here.
The IntSummaryStatistics class together with Java 8's Stream API may be less verbose than dealing with min, max, sum and avg calculation manually.
public static void main(String[] args) {
// Get user input.
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
// No user friendly way to gather user input, improve!
numbers.add(scanner.nextInt());
}
// Transform input to statistics.
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer.intValue()));
// Print statistics.
String jointNumbers = numbers.stream()
.collect(Collectors.joining(", "));
System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
}

How to use Scanner get store input in one integer

How can I make it so the there will be the same number of questions as the user inputs the number of jobs. For example, lets say you had worked in 5 jobs, I want the program to ask the user to ask,
Your salary for job 1
Job 2
Job 3
Job 4
Job 5, and so on. My code right now is.
import java.util.Scanner;
public class Personal_Info {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int Salary1;
int Salary2;
int Salary3;
int TotalJobs;
int Average;
String Name;
int Largest;
int Smallest;
int Sum;
System.out.print("What is your first name?: ");
Name = Scanner.nextLine();
System.out.print("How many jobs have you had?: ");
TotalJobs = Scanner.nextInt();
System.out.print("Enter income from job #1: ");
Salary1 = Scanner.nextInt();
System.out.print("Enter income from job #3: ");
Salary2 = Scanner.nextInt();
System.out.print("Enter income from job #3: ");
Salary3 = Scanner.nextInt();
Sum = Salary1 + Salary2 + Salary3;
Average = Sum / TotalJobs;
Largest = Salary1;
Smallest = Salary1;
if(Salary2 > Largest)
Largest = Salary2;
if(Salary3 > Largest)
Largest = Salary3;
if(Salary2 < Smallest)
Smallest = Salary2;
if (Salary3 < Smallest)
Smallest = Salary3;
System.out.println("Hello " + Name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + Largest + ". The lowest paying job paid is "+ Smallest + ". The average is " + Average + ".");
but it wouldn't work cause it'll only ask the user three times, job 1, 2, and 3.
If I try,
for (int x = 0; x<TotalJobs; x++){
System.out.print("How many jobs have you had?: ");
number = Scanner.nextInt();
I don't know how to get the highest/smallest/average from that stored value which would be 'number'.
Hope this will help You
class SalaryCalculate{
public static void main(String args[]){
int totalJobs,jobcounter,maxSalary,minSalary,averageSalary=0;;
int[] jobsincome;
String name;
Scanner sc= new Scanner(System.in);
System.out.println("Enter your name");
name=sc.nextLine();
System.out.println("How many jobs you had");
totalJobs= sc.nextInt();
jobsincome= new int[totalJobs];
for(int i=0;i<totalJobs;i++){
jobcounter=i+1;
System.out.println("Enter the income for your job "+jobcounter);
jobsincome[i]=sc.nextInt();
averageSalary=averageSalary+jobsincome[i];
}
jobsincome=average(jobsincome);
maxSalary=jobsincome[totalJobs-1];
minSalary=jobsincome[0];
averageSalary=averageSalary/totalJobs;
System.out.println("Hi "+name+" your min salary is "+minSalary+" max salary is "+maxSalary+" average salary is "+averageSalary);
}
public static int[] average(int jobsincome[]){
int length=jobsincome.length;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if(jobsincome[i]>jobsincome[j]){
int temp=jobsincome[j];
jobsincome[j]=jobsincome[i];
jobsincome[i]=temp;
}
}
}
return jobsincome;
}
}
Use an array.
Also only capitalize classes, not variables
System.out.print("How many jobs have you had?: ");
int totalJobs = scanner.nextInt();
int[] salaries = new int[totalJobs];
// Loop here
// System.out.print("Enter income from job #"+x);
// salaries[x] = scanner.nextInt();
With this list, you can get the length directly and use separate loops for the sum, min, max. Or streams
With the sum and length, find an average
use an integer arraylist to keep salaries and loop through inputs
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ArrayList<Integer> sallaries = new ArrayList<>();
int TotalJobs;
double average;
String name;
int largest;
int smallest;
System.out.print("What is your first name?: ");
name = input.nextLine();
System.out.print("How many jobs have you had?: ");
TotalJobs = input.nextInt();
for (int i= 0; i<TotalJobs ; i++){
System.out.print("Enter income from job #"+(i+1)+" : ");
sallaries.add(input.nextInt());
}
average = sallaries.stream().mapToInt(Integer::intValue).average().orElse(-1);
largest = Collections.max(sallaries);
smallest = Collections.min(sallaries);
System.out.println("Hello " + name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + largest + ". The lowest paying job paid is "+ smallest + ". The average is " + average + ".");
}

How do I find the average of the doubles in the file - JAVA

I need to Skip over text or integers. It reads a .dat file that has numbers (int/doubles) and strings in it. It also Calculates and prints max, min, sum, and the count of the number of words in the file. How do I do the average? Thank you!!
import java.io.*;
import java.util.*;
public class ProcessFile {
public static void main(String [] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("Enter file name: ");
String n = console.next();
File f = new File(n);
while(!f.exists()){
System.out.print("Doesn't exist. Enter a valid filename: ");
n = console.next();
f = new File(n);
}
Scanner input = new Scanner(f);
int minInt = Integer.MAX_VALUE;
int maxInt = Integer.MIN_VALUE;
int countInt;
int averageInt =
double minDouble = Double.MIN_VALUE;
double maxDouble = Double.MAX_VALUE;
double countDouble;
double averageDouble = //sum / countDouble
while(input.hasNext()){
if (input.hasNextInt()){
int next = input.nextInt();
maxInt = Math.max(next, maxInt);
minInt = Math.min(next, minInt);
countIntC++;
averageInt =
System.out.println("The results for the integers in the file :");
System.out.printf(" Max = %d\n", maxInt);
System.out.printf(" Min = %d\n", minInt);
System.out.printf(" Count = %d\n", countInt);
System.out.printf(" averageInt = %d\n", averageInt);
} else if (input.hasNextDouble()) { //can I read it as a double
double = next2 = input.nextDouble();
maxDouble = Math.max(next2, maxDouble);
minDouble = Math.min(next2, minDouble);
countDouble++;
averageDouble =
System.out.println("The results for the integers in the file:");
System.out.printf(" Max = %f\n", maxDouble);
System.out.printf(" Min = %f\n", minDouble);
System.out.printf(" Count = %f\n", countDouble);
System.out.printf(" averageInt = %f\n", averageDouble);
} else { //it is String
}
}
}
}
I see three problems
1) you need to initialize countDouble
countDouble = 0;
you're trying to do this countDouble++ before it's been ititialized
2) double = next2 = input.nextDouble();
I believe should be this
double next2 = input.nextDouble();
3) there no such variable countIntC
you're trying to countIntC++
should be countInt++
To calculate, I think you want to do this
averageInt = (maxInt + minInt) / countInt; // I THINK, depending on your logic
All in all, I have a feeling there's alot going on in your code, that can be thrown out.

Categories

Resources