How do I show the numbers I entered in Java - 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());
}

Related

How to insert existing arrays inside a 3D array

I would like to create a 3d array with the already existing arrays(Score, CourseRating, and SlopeRating). I would like to do so, so that I can match the Scores with their Ratings. If it is not possible, I was thinking I could maybe find the index of the score, and match it with the Course and Slope rating so that I can calculate the Handicap Index.
import java.util.Arrays;
import java.util.Scanner;
public class RoughDraft {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int count;
int[] Scores;
double[] SlopeRating;
double[] CourseRating;
System.out.print("\nHow many scores would you like to enter?: ");
count = scnr.nextInt();
// ------ adds Scores, Course Rating and Slope Rating to Arrays ------ //
Scores = new int[count];
CourseRating = new double[count];
SlopeRating = new double[count];
if(count >= 5 && count <= 20) {
for(int i = 0; i < count; i++) {
System.out.printf("\nEnter Score #%d: ", i + 1);
if(scnr.hasNextInt()) {
Scores[i] = scnr.nextInt();
}
System.out.printf("Enter Course Rating #%d: ", i + 1);
if(scnr.hasNextDouble()) {
CourseRating[i] = scnr.nextDouble();
}
System.out.printf("Enter Slope Rating #%d: ", i + 1);
if(scnr.hasNextDouble()) {
SlopeRating[i] = scnr.nextDouble();
}
}
}
else {
System.out.print("Enter a minimum of 5 scores and a maximum of 20 scores.");
main(args);
}
System.out.print("\nScores: " + Arrays.toString(Scores));
System.out.print("\nCourse Ratings: " + Arrays.toString(CourseRating));
System.out.print("\nSlope Rating: " + Arrays.toString(SlopeRating));
}
}

Java grades exercise

I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}

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 + ".");
}

Finding unique numbers

I am trying to use a set to find the unique numbers and get the sum from user entered numbers. I heard that arrays are easier but a set might just do for me. I don't know much about sets or what they do so any input would be fantastic. Much appreciated everybody!
import java.util.Scanner;
public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);
public double go()
{
double a = 0
counter = 10;
int total = 0;
for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}
System.out.println("the total is ";
return a;
}
}
java.util.HashSet stores unique values. Made minor changes to your program to use Set to store unique values and calculate sum of unique values using for loop
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);
public int go() {
int a = 0;
int n = 0;
counter = 10;
Set<Integer> unValues = new HashSet<Integer>();
while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}
int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}
public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality
I used here (HashSet).
import java.util.Scanner;
public class quiz_assignment
{
int counter;
Scanner scan = new Scanner(System.in);
Set<Integer> ditinctSet = new HashSet<Integer>();
public int go()
{
int a=0;
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(!ditinctSet.contains(newInteger)){
ditinctSet.add(newInteger);
}
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
a=a+newInteger;
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("Distinct numbers are: ");
System.out.println(ditinctSet);
return n;
}
}
And here a link to start knoing more about sets.
Hashsets are useful because they don't store duplicate entries. You can use them to store your set of unique numbers that the user inputs. I also removed the variable "a" from your code because its purpose seemed identical to variable n's.
import java.util.Scanner;
public class quiz_assignment{
int counter;
Scanner scan = new Scanner(System.in);
public int go()
{
HashSet<Integer> distinctNumbers = new HashSet<>();
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
distinctNumbers.add(newInteger);
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
int size = distinctNumbers.size();
System.out.println("The sum of all ten integers is: " + n);
System.out.println("You inputed " + size + " numbers.");
System.out.println("Your numbers are:");
for(Integer i: distinctNumbers){
System.out.println(i);
}
return n;
}
}

minimum of integers

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);
}

Categories

Resources