Finding the max value in an arraylist - java

In this program I wrote I have to print out the name of the customer who spent the most in the store. I need help searching the array list for the customer who spent the most.
package bestcustomer;
import java.util.*;
/**
*
* #author muf15
*/
public class BestCustomer {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
sales.add(salesAmount);
System.out.println("Enter customers name");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales;
return name;
}
}

You should wrap these two field in a class called probably Customer and then
Use Collections.max();
Collections.max(yourCollection, customComparator);

You should consider making Customer a class, but this would find the name with your current data structures:
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales = 0;
int index = -1;
for(int i = 0; i < sales.size(); i++) {
if(sales.get(i) > maxSales) {
index = i;
maxSales = sales.get(i);
}
}
if(index == -1) {
return null; //lists are empty
}
return customers.get(index);
}

I might be a bit late..
I think that if you create a Customer class with two fields, name and sale it would be better design as mentioned by other answers.
Then in BestCustomer you could loop through the list of customer, find the highest sales and return the name.
Something like this for BestCustomer
private ArrayList<Customer> customers = new ArrayList<Customer>();
public BestCustomer(){
Scanner in = new Scanner(System.in);
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
System.out.println("Enter customers name");
String name = in.next();
customers.add(new Customer(name, salesAmount));
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer();
System.out.print(bestCustomer);
}
private double highestSale(){
double highestSale = 0;
for(Customer c: customers)
if (c.getSales() > highestSale)
highestSale = c.getSales();
return highestSale;
}
public String nameOfBestCustomer(){
for (Customer c: customers)
if(c.matchSale(highestSale()))
return c.getName();
return null;
}
}
and this is the Customer
public class Customer {
private String name;
private double sales;
public Customer(String name, double salesAmount) {
this.name = name;
sales = salesAmount;
}
public boolean matchSale(double sales){
return this.sales == sales;
}
public double getSales(){
return sales;
}
public String getName(){
return name;
}
}
I am a beginner so I am pretty sure there is a more efficient way to do it. Also I am using two getters and as far as my understanding goes it is not the better design..

In Java8, if defined Customer like mikey said
customers.stream()
.max(Comparator.comparing(Customer::getSales))
.get()
.getName()

Related

How do I update the element inside the arraylist?

public class billing{
private int id;
//File f=new File("C:/Users/Bingus/Documents/Projects/accounts.txt");
private String bc;
private String bd;
private String customerName;
private String customerAddress;
private String customerNumber;
private String periodT;
private String periodF;
private double presentR;
private double previousR;
private double previousB;
private double dueTotal;
private static ArrayList<Account> accountList = new ArrayList<>();
public billing(int id,String bc,String bd,String customerName,String customerAddress,String customerNumber,String periodT,String periodF,double presentR,double previousR,double previousB,double dueTotal){
this.id = id;
this.bc = bc;
this.bd = bd;
this.customerName = customerName;
this.customerAddress = customerAddress;
this.customerNumber = customerNumber;
this.periodT = periodT;
this.periodF = periodF;
this.presentR = presentR;
this.previousR = previousR;
this.previousB = previousB;
this.dueTotal = dueTotal;
}
public int getId(){
return id;
}
public String getBc(){
return bc;
}
public String getBd(){
return bd;
}
public String getCustomerName(){
return customerName;
}
public String getCustomerAddress(){
return customerAddress;
}
public String getCustomerNumber(){
return customerNumber;
}
public String getPeriodT(){
return periodT;
}
public String getPeriodF(){
return periodF;
}
public double getPresentR(){
return presentR;
}
public double getPreviousR(){
return previousR;
}
public double getPreviousB(){
return previousB;
}
public double getDue(){
return dueTotal;
}
public static void main(String[] args){
Scanner scanner = new Scanner (System.in);
Scanner kb = new Scanner (System.in);
int user_choice;
int x = 0;
do{
System.out.println();
System.out.println("1) New Billing");
System.out.println("2) Add Existing Billing");
System.out.println("3) View Billing Account ID");
System.out.println("4) View By Date");
System.out.println("5) Update Existing Billing");
System.out.println("6) Delete Billing Account");
System.out.println("7) Display All Account");
System.out.println("8) Exit");
System.out.println();
System.out.print("Enter choice [1-8]: ");
user_choice = scanner.nextInt();
switch (user_choice){
case 1:
int min = 1000;
int max = 9999;
int randomStr = (int)(Math.random() * (max - min + 1) + min);
int id = randomStr;
System.out.println("Your Account Number is : " + id);
System.out.print("Enter Billing Code: ");
String bc = scanner.next();
System.out.print("Enter Billing Date(dd/mm/yyyy): ");
String bd = scanner.next();
System.out.print("Enter Customer Name: ");
String customerName = kb.nextLine();
System.out.print("Enter Customer Address: ");
String customerAddress = kb.nextLine();
System.out.print("Enter Customer Number: ");
String customerNumber = scanner.next();
System.out.print("Enter Period To: ");
String periodT = scanner.next();
System.out.print("Enter Period From: ");
String periodF = scanner.next();
System.out.print("Enter Present Reading: ");
double presentR = scanner.nextDouble();
System.out.print("Enter Previous Reading: ");
double previousR = scanner.nextDouble();
System.out.print("Enter Previous Balance: ");
double previousB = scanner.nextDouble();
double dueTotal = getTotalDue(presentR,previousR,previousB);
Account user = new Account(id,bc,bd,customerName,customerAddress,customerNumber,periodT,periodF,presentR,previousR,previousB,dueTotal);
accountList.add(user);
break;
case 2:
case 3:
System.out.print("Enter Account Number: ");
int a = scanner.nextInt();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId()){
System.out.println("Account ID: " + accountList.get(i).getId());
System.out.println("Customer Name: " +accountList.get(i).getCustomerName());
System.out.println("Customer Address: " + accountList.get(i).getCustomerAddress());
System.out.print("Customer Number: " + accountList.get(i).getCustomerNumber());
}
}
System.out.println("\nBilling Code\t\tBilling Date\t\tAmount Due");
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId())
{
System.out.println(accountList.get(i).getBc()+"\t\t\t"+accountList.get(i).getBd()+"\t\t\t"+accountList.get(i).getDue());
}
}
break;
case 4:
case 5:
System.out.print("Enter Account Number: ");
a = scanner.nextInt();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId())
{
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);
}
}
break;
case 6:
System.out.print("Enter Account Number: ");
a = scanner.nextInt();
System.out.print("Enter Billing Code: ");
String b = scanner.next();
for(int i = 0; i<accountList.size();i++){
if(a == accountList.get(i).getId()){
if(b.equals(accountList.get(i).getBc())){
accountList.remove(i);
System.out.print("\nAccount Removed\n");
}else{
System.out.print("Invalid Billing Code\n");
}
}else if(a != accountList.get(i).getId()){
System.out.print("Invalid Account Number or Number not in the database.\n");
}else{
System.out.print("Try Again\n");
}
}
break;
case 7:
System.out.println("Account ID\t\tBilling Code\t\tAccount Name\t\tTotal Due\t\tPresent R\t\tPrevious R");
Collections.sort(accountList,Collections.reverseOrder());
for(int i=0; i<accountList.size();i++){
System.out.println(accountList.get(i).getId() + "\t\t\t"+accountList.get(i).getBc()+ "\t\t\t"+accountList.get(i).getCustomerName()+ "\t\t\t"+accountList.get(i).getDue()+"\t\t\t"+accountList.get(i).getPresentR()+ "\t\t\t"+accountList.get(i).getPreviousR());
}
break;
}
}while(user_choice!=8);
}
I'm new to programming in Java and I'm still learning towards it. I'm making my billing system which calcualtes the payment. My problem for this is how can I change or update the value which is already in the arraylist, I've tried the set() but I cannot make it work. using arraylist is a big jump for me and I haven't yet got a hang of it. I've watched youtube vids but they seem to show non user input arry lists
Any help?
[1]: https://i.stack.imgur.com/HhF33.png
There are two ways to do it.
First Option is Loop the list and reach the object you want to change, update its attributes. Since the object is accessed by reference, whatever values you will change it will effect.
Second option is remove the object at that index, create a new object and insert at that position.
public void testArrayList ()
{
class MyData
{
String Id = "";
String Name = "";
public MyData () {}
public MyData (String id, String name) {
Id= id;
Name = name;
}
public String toString ()
{
return " Id=" + Id + " Name=" + Name;
}
}
ArrayList myDList = new ArrayList ();
myDList.add(new MyData("1", "John"));
myDList.add(new MyData("2", "Mike"));
myDList.add(new MyData("3", "Tom"));
System.err.println ("Org List " + myDList);
MyData tmp = (MyData) myDList.get(1);
tmp.Id = "22";
tmp.Name = tmp.Name + " Changed";
System.err.println ("Mod List (Observe second Object ) " + myDList);
}
You need to set the value in ArrayList to be an object of type Account.
1.You need to get an object of type Account and use settter method to update bcode
2. Set that Account object back to ArrayList
Code TL:DR. Do you have a set method in your Account class?
//set method example
public void setBc(String newBc){ //can also use other data types as parameters
this.bc = newBc;
}
If so you can just
accountList.get(i).setBc("This New BCODE"); //The parameter can also be a variable of string type
Your code:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
String c = accountList.get(i).getBc(); //this is the part in which i am having a hard time to fix, ive used the set but still i cannot change the element inside.
int index = accountList.indexOf(c);
accountList.set(index, bCode);
If you want to update billing code in an account then get the account object and update the user entered bCode on the object. Also, you don't have to put the account back in the list:
System.out.println("Your Account Number is : " + accountList.get(i).getId());
System.out.print("Enter Billing Code: ");
String bCode = scanner.next();
Account existing = accountList.get(i);
//create new account with same data except bCode
Account updated = new Account(existing.getId(),bCode, existing.getBd(),/*do same for rest of the fields */);
int index = accountList.indexOf(existing);
accountList.set(index, updated);
You have to change this part in Your program
…
Billing billing = accountList.get(i);
//String c = billing.getBc(); // this is the part in which I am having a hard time to fix, I've used
// the set but still I cannot change the element inside.
billing.setBc( yourNewBc );
//int index = accountList.indexOf(c);
//accountList.set(index, billing);
…
class names are capitalized in Java
Here in this example we have iterated over the list and modified the values of the object.
Please make a setter to the values you want to modify and follow something like this.
public class Arr {
public static void main(String args[]){
ArrayList<Person> array = new ArrayList();
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("1.add 2. modify 3.view list ; anything else to to quit");
int choice = sc.nextInt();
if (choice==1){
System.out.println("Enter ID then salary");
int id = sc.nextInt();
int salary = sc.nextInt();
Person p = new Person(id,salary);
array.add(p);
System.out.println("Done");
}
else if (choice==2){
System.out.println("Enter ID");
int id = sc.nextInt();
for (int i = 0; i < array.size(); i++){
Person p = array.get(i);
if (p.getId()==id){
System.out.println("value exits. Enter salary to be modified:");
int salary = sc.nextInt();
p.setSalary(salary);
}
}
System.out.println("Done");
}
else if (choice==3){
for (int i = 0; i < array.size(); i++)
System.out.print(" " + array.get(i).getId() + " " + array.get(i).getSalary());
}
else
break;
}
}
}
public class Person {
int id;
int salary;
public Person(int id, int salary) {
this.id = id;
this.salary = salary;
}
public int getId() {
return id;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}

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.

sort arraylist and compare in arraylist in java

I'm a beginner in java. I have a problem with my code. I want to design my program but I stuck in ArrayList. How can I add a new price and display all food has price smaller or equals than the price of a new food? and sort the list f by price. Help me please, thank so much.
1.accept a new price named p: list all Food which have price <= p
2.sort list f ascending by price and output list after sorting
public class Food {
//states
private String name;
private double price;
//accessor
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
//mutator
public String getName() {
return name;
}
public double getPrice() {
return price;
}
//methods
public Food() {
name = "";
price = 0;
}
public Food(String name, double price) {
this.name = name;
this.price = price;
}
public double getSalePrice() {
double tax = 0.07;//7%;
if(name.toLowerCase().startsWith("k")) tax = 0.05;
return price + price * tax;
}
public void print() {
System.out.printf("%-20s%-10.1f ($)%-10.1f ($)\n",
name,price,getSalePrice());
//System.out.println(String.format("%-20s%-10.1f ($)%-10.1f ($)\n",
// name,price,getSalePrice()));
}
public int listp(ArrayList<Food> f, int priceP) {
int s,i,n;
n = f.size();
s = 0;
for(i=0;i<n;i++) {
if(f.get(i).price > priceP) s++;
}
return(s);
}
}
public class Main {
public static void main(String[] args) {
//a list of food
Scanner in = new Scanner(System.in);
final int MAX = 10;
Food [] f = new Food[MAX];
f[0] = new Food("BBQ",3.35);
f[1] = new Food("KFC",3.3);
f[2] = new Food("Ga 36",4.5);
int n = 3;
while(true) {
System.out.print("Enter food name: ");
String name = in.nextLine();
System.out.print("Enter food price: ");
double price = Double.parseDouble(in.nextLine());
f[n] = new Food();
//f[n].name = name;f[n].price = price;
f[n].setName(name);
f[n].setPrice(price);
n++;
System.out.print("Add more food (yes/no)? ");
String s = in.nextLine();
if(s.equalsIgnoreCase("no")) break;
}
//output list
for (int i = 0; i < n; i++) {
f[i].print();
}
System.out.print("Enter price of food p:");
double price = Double.parseDouble(in.nextLine());
System.out.println(listp(f,price));
}
public int listp(ArrayList<Food> f, int priceP) {
int s,i,n;
n = f.size();
s = 0;
for(i=0;i<n;i++) {
if(f.get(i).getPrice() > priceP) s++;
}
return(s);
}
}
Here is a working solution where the array was converted to a list and the listp method was changed to use streams which are really a good fit for your requirements:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//a list of food
Scanner in = new Scanner(System.in);
List<Food> f = new ArrayList<>();
f.add(new Food("BBQ", 3.35));
f.add(new Food("KFC", 3.3));
f.add(new Food("Ga 36", 4.5));
int n = 3;
while (true) {
System.out.print("Enter food name: ");
String name = in.nextLine();
System.out.print("Enter food price: ");
double price = Double.parseDouble(in.nextLine());
Food food = new Food();
//f[n].name = name;f[n].price = price;
food.setName(name);
food.setPrice(price);
f.add(food);
n++;
System.out.print("Add more food (yes/no)? ");
String s = in.nextLine();
System.out.println(s);
if (s.trim().equalsIgnoreCase("no")) break;
}
System.out.print("Enter price of food p:");
double price = Double.parseDouble(in.nextLine());
listp(f, price);
}
private static void listp(List<Food> f, double priceP) {
f.stream()
.filter(food -> food.getPrice() <= priceP)
.sorted(Comparator.comparingDouble(Food::getPrice))
.forEach(food -> System.out.printf("%s : %s%n", food.getName(), food.getPrice()));
}
}
Here is a variation of the listp method which allows you to limit the list by a number:
private static void listp(List<Food> f, double priceP, int limit) {
f.stream()
.filter(food -> food.getPrice() <= priceP)
.sorted(Comparator.comparingDouble(Food::getPrice))
.limit(limit)
.forEach(food -> System.out.printf("%s : %s%n", food.getName(), food.getPrice()));
}
This ensures that the printed out list is always as long as specified in the limit parameter.
Usage example:
listp(f, price, 2);
This will print a maximum of two items, even if the total list has more than that.
1.
public List<Food> findFoodWhichPriceLessThan(Collection<Food> listOfFood, double price){
return listOfFood.stream().filter(it -> it.getPrice() <= price).collect(Collectors.toList());
}
2.
public void sortFoodByPrice(List<Food> listOfFood){
Collections.sort(listOfFood, Comparator.comparingDouble(Food::getPrice));
}
or
public List<Food> sortFoodByPrice2(List<Food> listOfFood){
return listOfFood.stream().sorted(Comparator.comparingDouble(Food::getPrice)).collect(Collectors.toList());
}

Java passing class array into array

I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}

Searching through arraylists for the largest number

So I'm currently making a code right now that searches through arraylists and prints out the largest one. This code prompts the user for BankAccount names and how much money the account has. Currently I've run into the problem of not knowing how to search through arraylists for the biggest number. I also don't know how to compare each balance to the maxBalance. Any help is appreciated, Thanks.
import java.io.*;
import java.util.*;
import java.text.*;
public class Project43Tester
{
public static void main(String args[])
{
NumberFormat formatter = NumberFormat.getNumberInstance( );
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String name;
ArrayList <String> aryLst = new ArrayList<String>();
do
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Please enter the name to whom the account belongs.(\"Exit\" to abort)");
name = kbReader.nextLine( );
if( !name.equalsIgnoreCase("EXIT") )
{
System.out.print("Please enter the amount of the deposit. ");
double amount = kbReader.nextDouble();
System.out.println(" ");
ArrayList <String> BankAccount = new <String> ArrayList();
AryLst.add(BankAccount);
}
}while(!name.equalsIgnoreCase("EXIT"));
Search aryList and print out the name and amount of the largest bank account
BankAccount ba = //get first account in the list
double maxBalance = ba.balance;
String maxName = ba.name;
for(int j = 1; j < aryLst.size( ); j++)
{
?
? Step through the remaining objects and decide which one has
largest balance (compare each balance to maxBalance)
?
}
System.out.println(" ");
System.out.println("The account with the largest balance belongs to " + maxName + ".");
System.out.println("The amount that the account contains is $" + formatter.format(maxBalance) + ".");
}
}
You will have to traverse the ArrayList. During the traversal of the ArrayList, set the first element as max and compare it with next. If it is greater, then set the new element as the max.
The easiest way is to use ArrayList's sort function. No headache there.
Refer this link
List<String> l = new ArrayList<String>();
l.add("2.33");
l.add("3.45");
l.add("1.11");
Collections.sort(l);
for(String s: l) {
System.out.println(s);
}
Result:
1.11
2.33
3.45
This is a slightly modified version of your code. Would advise to use a Comparable/Comparator for sorting (which you should try; modify below code).
Here's simple traversal through the array iterating and accessing object properties for your example.
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Project43Tester
{
static class BankAccount
{
String name;
Double amount;
public BankAccount(String name, Double amount)
{
this.name = name;
this.amount = amount;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Double getAmount()
{
return amount;
}
public void setAmount(Double amount)
{
this.amount = amount;
}
}
public static void main(String args[])
{
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String name = null;
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
do
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Please enter the name to whom the account belongs.(\"Exit\" to abort)");
name = kbReader.nextLine();
if (!"EXIT".equalsIgnoreCase(name))
{
System.out.print("Please enter the amount of the deposit. ");
double amount = kbReader.nextDouble();
System.out.println(" ");
bankAccounts.add(new BankAccount(name, amount));
}
}
while (!"EXIT".equalsIgnoreCase(name));
BankAccount maxBankAccount = null;
for (BankAccount bankAccount : bankAccounts)
{
if (maxBankAccount == null)
{
maxBankAccount = bankAccount;
}
else if(bankAccount.getAmount() > maxBankAccount.getAmount())
{
maxBankAccount = bankAccount;
}
}
System.out.println(" ");
System.out.println("The account with the largest balance belongs to " + maxBankAccount.getName() + ".");
System.out.println("The amount that the account contains is $" + formatter.format(maxBankAccount.getAmount()) + ".");
}
}

Categories

Resources