Cannot find the highest and lowest - java

I have some problems in highest and lowest.
import java.util.Scanner;
public class Lab3bq1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double [] num = new double[10];
double [] p = new double[10];
System.out.println("Enter the number of books purchased by :");
for(int i=0;i<num.length;i++)
{
System.out.print("Customer #"+(i+1)+ " = ");
num[i] = input.nextDouble();
}
System.out.println("Review for 10 Selected Customers");
System.out.println("Points Awarded:");
setp(num,p);
System.out.println("Total books purchased : "+settotalbook(num));
System.out.println("Highest points : Customer "+sethighest(p));
System.out.println("Lowest points : Customer "+setlowest(p));
}
public static void setp(double[] num, double[] p)
{
for(int i=0;i<p.length;i++)
{
if(num[i]>=1 && num[i]<=3)
p[i] = 10;
else if(num[i]<=6)
p[i] = 25;
else if(num[i]<=9)
p[i] = 40;
else
p[i] = 75;
System.out.println("Customer #"+(i+1)+ " = " + p[i] + " points");
}
}
public static double settotalbook(double[] num)
{
double total=0;
for(int i=0;i<num.length;i++)
{
total+=num[i];
}
return total;
}
public static double sethighest(double[] p)
{
double max=p[0], custnum=0;
for(int i=0;i<p.length;i++)
{
if(p[i]>max)
max=p[i];
custnum=i;
}
return (custnum+1);
}
public static double setlowest(double[] p)
{
double min=p[0], custnum=0;
for(int i=0;i<p.length;i++)
{
if(p[i]<min)
min=p[i];
custnum=i;
}
return (custnum+1);
}
}

Problem is with if block in both method
try:
if(p[i]<min){
min=p[i];
custnum=i;
}
and
if(p[i]>max){
max=p[i];
custnum=i;
}
store customer number who have min or max value..

It looks like you are beginner. Anyway, you should return max in the sethighest method and min in the setlowest method as #Uta Alexandru suggested.
There is one more mistake in the code. Whenever we write something like
if(condition)
statement#1
statement#2
So if condition is true then only statement#1 will execute and statement#2 is out of the condition.
Here in your code your wrote
if(p[i]>max)
max=p[i];
custnum=i;
and
if(p[i]<min)
min=p[i];
custnum=i;
custnum is updated at every iteration in loop.
If you want it to be updated only when your condition is true then you need to put your code in block like this.
if(p[i]>max) {
max=p[i];
custnum=i;
}
and
if(p[i]<min) {
min=p[i];
custnum=i;
}
Hope this helps. Enjoy :)

Related

Parameters, methods and inputs

I am a beginner in Java and I am wondering if there is a way to use one input from the user in more than one method? I am making a program that is supposed to take some inputs (integers) from the user and control the inputs, then calculate the average and lastly count the occurrence of the inputs?
I have one main method + 3 different methods (one calculates the average etc). I have tried a lot of different things, but haven't seemed to understand the point with parameters and how they work.
So this is just a quick overview.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int value = sc.nextInt(); //Number of how many elements the user want to enter
int[] input = new int[value]; //An array with all the values
}
public int secureInt(int number, int[] input, int value) {
if (!Integer.parseInt(number)) {
System.out.println("Invalid input");
} else {
for (int i = 0; i < value; i++) { //Add all the inputs in the array
input[i] = sc.nextInt();
}
}
public double averageCalculator (int value, int[] in){
double average; // The average
double sum = 0; // The total sum of the inputs
if (int i = a; i < value; i++) {
sum = sum + in[i];
}
average = sum / value;
return average;
}
//Count the occurence of inputs that only occure once
public static int countOccurence(//what parameter should i have here?) {
int count = 0;
}
}
Here is some code that may be helpful to you. The idea is to try to emulate or imitate the style & best practices in this excerpt:
import java.util.Scanner;
public class ArrayFiller {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int input_element_count = sc.nextInt(); //Number of how many elements the user want to enter
int element_count = input_element_count;
int[] array = new int[element_count]; //An array with all the values
enter_elements_of_array(array, element_count, sc);
double average = averageCalculator(array, element_count);
printArray(array);
System.out.println("The average of the entered numbers is " + average);
}
public static void printArray(int[] array) {
System.out.print("The array you entered is : [");
for (int element : array) {
System.out.print(" " + element + " ");
}
System.out.print("]" + "\n");
}
public static void enter_elements_of_array( int[] array, int element_count, Scanner sc) {
for (int i = 0; i < element_count; i++) { //Add all the inputs in the array
System.out.println("Please enter element " + (i+1) + " of " + element_count + ":");
array[i] = sc.nextInt();
}
}
public static double averageCalculator ( int[] array, int element_count){
double average; // The average
double sum = 0; // The total sum of the inputs
for (int i = 0; i < element_count; i++) {
sum = sum + array[i];
}
average = sum / element_count;
return average;
}
//Count the occurence of inputs that only occur once
public static int countOccurence(int[] array) {
int count = 0;
// algorithm for counting elements with cardinality of 1
return count;
}
}

How to sum value in a specific object?

I have this code where you would search for the patient ID and when found a sub menu will show, the user would then be prompted to choose. If the user chooses bill the would then be asked to enter a transaction and it would be summed to the balance in the same object as the ID that was searched. However when the user inputs a value it always sums the value to the balance(450) in the object.
How can I fix this?
NB: it's in an array
output: adds the input to the first object only.
patient pAccount[] = new patient [10];
patient p1 = new patient("Jabari","luck",d1 ,"234-4343", "p01" ,450);
patient p2 = new patient("Lisa", "nun", d2,"311-5634" , "p02",300);
patient p3 = new patient("Kyle", "Hep",d3 ,"555-5555" , "p03",2000 );
//search array for patient ID
public static void ID(person [] pAccount) {
Scanner scan= new Scanner(System.in);
String num = scan.next();
for(int i=0; i< pAccount.length; i++) {
if (pAccount[i].getpatID().equals(num)) {
System.out.println("found");
break;
}
}
}
//sum user input to balance
public static void bill(person[] pAccount) {
Scanner in = new Scanner (System.in);
double sum;
double num= in.nextDouble();
for(int i=0; i <= pAccount.length; i++) {
person ad= pAccount[i];
sum = ((patient) ad).getbalance()+ num;
System.out.println("Balance: " +sum);
break;
}
}```
what I understood from your question is, you need to add sum to the balance of a specific object in Patient Object array. Below is the way to do,
(I excluded few member variables which I didn't get just by looking at Object creation in your question and kept only name, patId and balance in Patient Class. Also I assumed you've Constructor with all the fields)
I took your code and modified a little for you requirement. You can refer comments I added in the code snippets.
PatientMainClass.class
public class PatientMainClass {
public static void main(String[] args) {
Patient pAccount[] = new Patient[3];
Patient p1 = new Patient("Jabari", "p01", 450);
pAccount[0] = p1;
Patient p2 = new Patient("Lisa", "p02", 300);
pAccount[1] = p2;
Patient p3 = new Patient("Kyle", "p03", 2000);
pAccount[2] = p3;
//Use bill method to add Amount to existing balance of all the Patient Objects
Patient.bill(pAccount);
System.out.println();
for (int i = 0; i < pAccount.length; i++) {
System.out.println("After adding amount to the Balance of pAccount[" + i + "] is : " + pAccount[i].getBalance());
}
System.out.println();
//Use billToSpecific method to add Amount to specific Patient Object
//to billToSpecific method, pass both Patient Array and Patient ID to which you want to add Amount
Patient.billToSpecificPatient(pAccount, "p02");
System.out.println();
for (int i = 0; i < pAccount.length; i++) {
System.out.println("After adding amount to p02, Balance of pAccount[" + i + "] is : " + pAccount[i].getBalance());
}
} }
Patient.class
public class Patient {
private String name;
private String patId;
private double balance;
public Patient(String name, String patId, double balance) {
super();
this.name = name;
this.patId = patId;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatId() {
return patId;
}
public void setPatId(String patId) {
this.patId = patId;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
// This method will Add entered value i.e.. "num" to the Balance of all the Patient Objects
public static void bill(Patient[] pAccount) {
System.out.println("In bill method"); // Always try using System.out.println for Debugging
Scanner in = new Scanner(System.in);
double sum;
double num = in.nextDouble();
for (int i = 0; i < pAccount.length; i++) {
Patient ad = pAccount[i];
sum = ((Patient) ad).getBalance() + num;
ad.setBalance(sum);
System.out.println("Balance: " + sum);
// break; // Commenting break statement to add balance to all the Objects
}
}
// This method will Add entered value i.e.. "num" to the Balance of the Specific Patient Object
public static void billToSpecificPatient(Patient[] pAccount, String patId) {
System.out.println("In billToSpecific method"); // Always try using System.out.println for Debugging
Scanner in = new Scanner(System.in);
double sum;
double num = in.nextDouble();
for (int i = 0; i < pAccount.length; i++) {
if (pAccount[i].getPatId().equals(patId)) {
Patient ad = pAccount[i];
sum = ((Patient) ad).getBalance() + num;
ad.setBalance(sum);
System.out.println("Balance: " + sum);
break; // Using break statement to exit the loop once we add amount to specific Patient Object
}
}
} }
I guess, you can now resolve your issue with the help of these code snippets. Hope it is helpful.

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

Use scanner only from main method

I have this class (with setters, getters and one method) that asks from a user a number indefinitely until he types -1.
I've called the Scanner Method from both, the main method and the class itself, is there a way to call the Scanner method only once only from the main method and apply the input to the class every time it is needed? I really appreciate your help. If something is not clear, please contact me.
Here's the Class Code:
public class calculation {
int current = 0;
int maxNum = 0;
int minNum;
int counter=0;
float sum = 0;
float avg;
Scanner scan = new Scanner(System.in);
public void setMin(int min){
this.minNum = min;
}
public int getMin(){
return minNum;
}
public void setMax(int max){
this.maxNum = max;
}
public void setSum(float sum){
this.sum += sum;
}
public void minMax(int current){
setMin(current);
while(current!=-1){
setSum(current);;
if(current>getMin()){
setMax(current);
}else if(current<getMin()){
setMin(current);;
}
current = scan.nextInt();
counter++;
}
System.out.println("The smallest number you entered was: \n" + minNum);
System.out.println("The biggest number you entered was: \n" + maxNum);
System.out.println("The sum of all those numbers is: \n" + sum);
System.out.println("The avarege number is: \n" + (sum/counter));
}
}
And here's the main method code:
public class minusOne {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation cal1 = new calculation();
System.out.println("Type numbers at will, when finish, type -1 and press enter");
cal1.minMax(scan.nextInt());
scan.close();
}
}
From what I understand, you don't want to have two call to new Scanner(System.in);
To avoid this, you can simply, in your class calculation, write :
Scanner scan;
And add a constructor :
public calculation(Scanner sc){
scan = sc;
}
Of course, in the main method you should write :
new calculation(scan)
I hope I answered your question
Note: in Java your classes name should start with uppercase letter, it should be Calculation
You have some alternatives for this, you can have your Calculator class with a constructor that takes a Scanner as a parameter and then store it in a field, or you cand have a public field in the Calculator class and in your main when you get the scanner just affect this field (but it should be private, you can change it via getters and setters methods).
/* This is the first option*/
public class Calculation {
int current = 0;
int maxNum = 0;
int minNum;
int counter=0;
float sum = 0;
float avg;
private Scanner scan;
public Calculation(Scanner scan){
this.scan = scan;
}
public int setCurrent(int current){
this.current = current;
return current;
}
public void setMin(int min){
this.minNum = min;
}
public int getMin(){
return minNum;
}
public void setMax(int max){
this.maxNum = max;
}
public void setSum(float sum){
this.sum += sum;
}
public void minMax(int current){
setMin(current);
while(current!=-1){
setSum(current);;
if(current>getMin()){
setMax(current);
}else if(current<getMin()){
setMin(current);;
}
current = setCurrent(current);;
counter++;
}
System.out.println("The smallest number you entered was: \n" + minNum);
System.out.println("The biggest number you entered was: \n" + maxNum);
System.out.println("The sum of all those numbers is: \n" + sum);
System.out.println("The avarege number is: \n" + (sum/counter));
}
}
/* Second option */
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation cal1 = new calculation();
//if the field scan in Calculation is public
cal1.scan = scan;
//if it is private
cal1.setScan(scan);
System.out.println("Type numbers at will, when finish, type -1 and press enter");
cal1.minMax(scan.nextInt());
scan.close();
}

Calculate average value in array

I am working on a project in Java that requests user inputs information like name, id, score in array.I need to help about calculate a average grade that user input and how to find out who have highest score. Here is my code:
package finalproject;
import java.util.Scanner;
public class FinalProject {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Cis84[] student = new Cis84[50];
int option;
for (int c = 0; c < 50; c++)
student[c] = new Cis84();
do {
System.out.print("");
System.out.println("1) Add Information");
System.out.println("2) Show report");
System.out.println("3) Exit");
System.out.print("\nEnter option: ");
option = input.nextInt();
switch (option) {
case 1:
String n;
double g;
int index,
i;
System.out.println("Which position of the student?");
index = input.nextInt();
System.out.println("What is the student's name:");
n = input.nextLine();
n = input.nextLine();
System.out.println("What is student's Id");
i = input.nextInt();
System.out.println("What is student's score");
g = input.nextDouble();
student[index].setName(n);
student[index].setGrade(g);
student[index].setId(i);
break;
case 2:
for (int c = 0; c < 50; c++)
System.out.println(student[c]);
break;
case 3:
System.out.println("You are done");
break;
default:
System.out.println("Try again");
break;
}
} while (option != 3);
}
}
and class
package finalproject;
public class Cis84 {
private String name;
private int id;
private double grade;
public Cis84() {
name = "not input yet";
id = 00000;
grade = 0.0;
}
public Cis84(String n, int i, double g) {
name = n;
id = i;
grade = g;
}
public void setName(String n) {
name = n;
}
public void setId(int i) {
id = i;
}
public void setGrade(double g) {
grade = g;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public double getGrade() {
return grade;
}
public String toString() {
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
}
This is for homework, clearly, and I don't feel comfortable giving you a straight answer. However, what you will want to do is when it is time to display the averages, go through the entire students array and sum up the scores, then divide by the size of the array, likely using a for loop. You could keep track of the size of the array by having a counter increased anytime option 1 of the switch-case is called.
To find the highest score, you should be able to use the average-calculation for loop mentioned above, and check the grade against the previous highest grade. Record the index of whichever has the highest grade and print it out.
Have some pseudocode!
for(size of array which isn't NULL){
add indexed grade to sum;
check to see if this index has the highest grade;
}
display (sum/size); //the average
display highest grade;
calculating average would be something like the below code. Remember, average is the sum of all the values divided by the total number of values
double sum = 0, divisor = 0;
for (int k = 0; k < student.length; k++){
sum += student[k].getGrade();//add up all the grades
divisor = k;//get the number of total items
}
return sum/divisor; //divide
private static double calculateAverage(Cis84[] students) {
double sum = 0;
for (Cis84 student : students) {
sum += student.getGrade();
}
return sum / students.length;
}
private static double calculateHighestScore(Cis84[] students) {
double highestScore = 0;
for (Cis84 student : students) {
if (student.getGrade() > highestScore) {
highestScore = student.getGrade();
}
}
return highestScore;
}
Then, to show the information:
case 2:
System.out.println("Average:");
System.out.println(calculateAverage(student));
System.out.println("Highest score:");
System.out.println(calculateHighestScore(student));

Categories

Resources