Need array assistance - java

I'm in a Java class and I'm having extreme difficulty getting started on the assignment. I do not want the answer but I really would appreciate any and all help on getting going and a basic outline of what to do.
A supermarket wants to reward its best customer of each day, showing the customer’s name on a screen in the supermarket. For that purpose, the customer’s purchase amount is stored in an ArrayList<Double> and the customer’s name is stored in a corresponding ArrayList<String>.
Implement a method
public static String nameOfBestCustomer(
ArrayList<Double> sales,
ArrayList<String> customers)
that returns the name of the customer with the largest sale.
Write a program that prompts the cashier to enter all prices and names, adds them to two array lists, calls the method that you implemented, and displays the result. Use a price of 0 as a sentinel.

You can use a Scanner to get the values that the cashier enters (an int for the purchase amount and a String for the customer's name, use conditions and throw exceptions to guarantee the values' types). Those values are put in two ArrayList (Lists of Integer and String).
Once the supermarket closes, you can use a loop on the list of purchases amounts to find the max purchase amount and its position in the list and use this position to find the best customer in the other list.

This is what you can do :
package com.assignments;
import java.util.ArrayList;
import java.util.Scanner;
public class MaxSalesCustomer {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> customerNameArray = new ArrayList<String>();
ArrayList<Integer> customerSalesValue = new ArrayList<Integer>();
String continueAdding = "Y";
Scanner sc=new Scanner(System.in);
while(continueAdding.equals("Y")){
System.out.println("Please Enter the customer Name:");
String name = sc.next();
customerNameArray.add(name);
System.out.println("Please Enter the sales value:");
Integer sales = sc.nextInt();
customerSalesValue.add(sales);
System.out.println("Do you want to continue 'Y/N' ?" );
continueAdding = sc.next();
}
String maxSalesCustomerName = getMaxSalesCustomerName(customerNameArray,customerSalesValue);
System.out.println(maxSalesCustomerName);
}
public static String getMaxSalesCustomerName(ArrayList<String> customerNameArray,ArrayList<Integer> customerSalesValue){
Integer maxValue = 0;
String maxSalesCustomerName = new String();
for (int i = 0; i < customerSalesValue.size(); i++){
if (maxValue < customerSalesValue.get(i)){
maxValue = customerSalesValue.get(i);
maxSalesCustomerName = customerNameArray.get(i);
}
}
return maxSalesCustomerName;
}
}

Related

Loop through the services array and ask the user which services they want for their <insert model>

Here are my instructions:
In main, ask the user what make of automobile they own. Store this data in a string.
Your first method should take the make via parameter and present the user with the following greeting: Hello! We will be happy to service your automobile today!
Write a second method named carMaintenance. It should take in the make via parameter and return the price to Main.
o Create two local arrays: services and prices.
§ One will hold these strings: Oil Change, Tire Rotation, Air Filter, Check Fluids
§ The second will hold these doubles: 39.99, 49.99, 19.99, 10.99
o Loop through the services array and ask the user which services he wants for his . Make sure you display the price along with the service. Use an accumulator to total the price for all requested services, using the prices array.
o Return the price to Main.
Write a third method name finalPrice that takes in the price from Main.
o First, tack on 30% for labor to the price.
o Then, ask if the car is an import. If the answer is yes, add another 5% to the price.
o Add 7% sales tax.
o Display the total price to the user from this method.
Method 1 is done, however method 2 I need help with the loop and I was wondering if I can get some assistance on it. Since it's only asking me the model and then greeting me.
import java.util.Scanner;
public class autoRepairShop {
/**
* #param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Scanner Object
String automobileMake;
Scanner input = new Scanner (System.in);
System.out.print("Input your automobile model/make: ");
String model = input.next();
System.out.println();
System.out.println("Hello! We will be happy to service your " + model + " automobile today!");
}
/** Method 2 **/
static void carMaintenance() {
String[] services = new String[3];
Scanner sc = new Scanner(System.in);
Scanner input = new Scanner (System.in);
double[] prices = new double[3];
String str;
services[0] = "Oil Change";
services[1] = "Tire Rotation";
services[2] = "Air Filter";
services[3] = "Check Fluids";
prices[0] = 39.99;
prices[1] = 49.99;
prices[2] = 19.99;
prices[3] = 10.99;
for (int i = 0; i<4; i++) {
String model = null;
System.out.println("which services do you want for your " + model);
String services1 = input.nextLine();
System.out.println("Your choices are");
for(String services + double prices = 0; );
}
};
}
A. Your arrays should be initialized to size 4 ([4]), as each array has 4 elements. As it is, you are going to get ArrayIndexOutOfBoundsException's on each arr[3] = ...; Also, it would be cleaner and safer to initialize your arrays like String services[] = ['A','B','C','D'];
B. For your loop, you want to move the printlns in the loop outside before the loop
System.out.println("Enter your model");
String model = input.nextLine();
It isn't clear how model fits in with what you are doing and how you are intending to use it, but I've left this in here, as it was in your original code
System.out.println("which services do you want for your " + model);
System.out.println("Your choices are");
for (int i = 0; i<4; i++) {
System.out.println(services[i] + ": " + prices[i]);
}
String services1 = input.nextLine();
Also you should create a constant (final) variable somewhere to indicate how many services and prices you have, and you should reference that variable in your loop iteration

How to make scanner scan multiple inputs from one scanner line in java?

The user should be able to input data of 5 customers with balances. However this piece of code only works for 1. I initially thought of using a for OR a while loop but I think they will create the display message 5 times.
import java.util.Scanner;
public class Assignment {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
Customer c [] = new Customer [5];
Customer hold;
String name; int count = 0;
double totalBalance = 0.0;
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
System.out.println("Search for all customers who have more than $100");
for (int i=0; i<count ; i++){
if (c[i].getBalance()>100)
System.out.println(c[i].getName());
totalBalance += balance;
averageBalance = totalBalance/5;
System.out.println("The average balance is: "+averageBalance);
}
}
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
for(int i=0; i<5; i++){
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
}
So, in the above code the display message prints 5 times but every time it will be for different customers. For e.g.
Enter 1 customer name and balance
John
20.0
Enter 2 customer name and balance
Jim
10.0
and so on.
I hope this helps. If you ask me you should be using java.util.ArrayList or java.util.LinkedList. These classes come with many features out of the box and you need not code much as in the case of arrays.
You are asking is not a coding problem but just a matter of design.
For what you are doing as per design you can follow below process or similar.
Enter comma separated user names in single line.
Read the line and split the names, now you have x customers detail like name read in a single shot.
Now you have names, repeat 1-2 above for every type of detail just need to be entered comma separated. Try to take one type of detail at a time, i.e. one, line one detail like salary of emp or department.
for pseudo code:
private String[] getDetails(BuffferReader reader){
// read a line at a time, using readline function
// using readed line/console input, split it on comma using split() function and return array of values.
}

Passing arrays as parameters and make calculations

I have to make a Java Program, where a user type in the total numbers of students, so I made this code:
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
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
Now, after adding the total number of students, we should add their names into an array:
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
After that, we should add correspondingly the age of each name, so I made this portion of code:
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
After making this code, I tested it using Ideone and Command Prompt and it works properly:
Now, I need to call method according to selection of the user:
if he typed 'a' a method should be called to specify the name and the age of the oldest student.
If he typed 'b' a method called to see how many students have an age specified by the user and If he typed 'c', a function called to calculate the average age of them all.
I am new to methods so I don't know how to add arrays into methods and make statements.
Here is the full 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
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
//Choosing a statistic
//if a:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X+X);
else if(X=='b')
//System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
else
System.out.println(X);
}
}
Right, so to start with your user enters an input, for example 'a', so let's go with this:
Firstly, you need to create the method where the name of the oldest student is displayed, so let's call it 'getOldestStudent' - when naming methods this is the typical naming convention, starting lowercase and then moving to uppercase for each new word - try and make them as intuitive as possible.
When making the method signature, you need to give it its visibility and also what it is going to return. In this case, as you are only using one class, we will give it private, so it is only visible by this class.
Now we need to return 2 things, so we can either put these into a string or put them into an array, which is what I would recommend, so we are going to return an array. However, you want to input an array to search through, so this goes in tbe brackets as parameters (or arguments). Therefore our method signature is the following:
private String[] getOldestStudent(String[] students, int[] ages)
Then inside this method, you can simply do the code you need to find the oldest student, add their name and age to the array and then return this.
Need anymore help just drop a comment.
On a side note, you would have been better off creating a 'Student' object and then giving this object a 'name' property and an 'age' property and then simply making an array of students and getters and setters (or accessors and mutators) for these properties.
James Lloyd's covers your question pretty well, I thought I might add some input as I think you are struggling with some principles.
At first, I would do as James advised and create a class Student that stores the values for each person.
public class Student {
public String name;
public int age;
// Constructors allow you to create a new Object and set some variables
// when you create it.
public Student (String name) {
this.name = name;
}
}
I used public to avoid getters and setters for this explanation, but I'd use private most had I to write it by myself.
Anyways, that way you only have to use one instead of two arrays (and name and age are connected with each other, e.g., you know the age of a student you know the name of, whereas with two different arrays it could happen that you don't know if nameArray[0] belongs to ageArray[0].
So you have an array Student[] students = new Student[numReaders]; and you can set each Student after reading the input, i.e., after reading the name you call students[i] = new Student(name); If you want to set the age of a Student afterwards you can do so by using student[i].age = age.
Now that we have filled our array, we can advance to your actual question.
char method;
method = stat.next().charAt(0);
// I think switch is a little easier to read for such cases
switch(method) {
case 'a': Student oldest = getOldestStudent(students);
if (oldest != null)
System.out.println(oldest.name);
break;
case 'b': //another method
break;
default: // equals to else as if none of the other cases was fulfilled
break;
}
Now you can write your own method for each scenario you have to cover.
public Student getOldestStudent(Student[] students) {
// at first we check some cases that do not require further checks
if (students.length == 0) {
System.out.println("No students have been specified");
return null; // this might lead to a NullPointerException so check the return Object whether it is null before doing anything with it
} else if (students.length == 1)
return students[0];
// no we have to see which students if the oldest in the regular case
// the first student will be used for comparison
Student oldestStudent = students[0];
for (int i = 1; i < students.length; i++) {
// see if our current student is older
if (oldestStudent.age < students[i].age)
oldestStudent = students[i];
}
return oldestStudent;
}
This way you can easily access the Students name afterwards (see above in the switch). You can build all your methods like this by passing the array to the methods and iterating through it. Depending on whether you want to return one or more Students (as it might vary between the different methods) you have to change the return type from Student to Student[].

How do I store user input into an array list?

I am writing a program that allows the user to input the details of a book and store them in an Array List. My question is, how can I get the code I am using to store more than one value in my array list instead of just overwriting what's already there?
Here's what I have so far...
Scanner input = new Scanner(System.in);
System.out.println("What is the book called?..");
String bTitle = input.nextLine();
System.out.println("Who is the author?..");
String bAuthor = input.nextLine();
System.out.println("How many do you have?..");
int bQuantity = input.nextInt();
System.out.println("How many are out on loan?..");
int bNumOnLoan = input.nextInt();
System.out.println("How many times has it been loaned?..");
int bNumTimesLoaned = input.nextInt();
ArrayList<Book> books = new ArrayList<Book>();
Book object = new Book(bTitle, bAuthor, bQuantity, bNumOnLoan, bNumTimesLoaned);
books.add(object);
But when I run this again the values that I entered before have been replaced. Any help would be most appreciated as I am stumped.
import java.util.ArrayList;
import java.util.Scanner;
public class BookCapture {
static ArrayList<Book> books = new ArrayList<Book>();
public static void main(String ase[]){
for(int i=0;i<5;i++){
capture();
}
System.out.println(books.toArray());
}
public static void capture(){
Scanner input = new Scanner(System.in);
System.out.println("What is the book called?..");
String bTitle = input.nextLine();
System.out.println("Who is the author?..");
String bAuthor = input.nextLine();
System.out.println("How many do you have?..");
int bQuantity = input.nextInt();
System.out.println("How many are out on loan?..");
int bNumOnLoan = input.nextInt();
System.out.println("How many times has it been loaned?..");
int bNumTimesLoaned = input.nextInt();
Book object = new Book(bTitle, bAuthor, bQuantity, bNumOnLoan, bNumTimesLoaned);
books.add(object);
}
}
class Book{
// your book class
// do override your tostring() method;
}
In the above code you are requesting the user to enter the details 5 times and this gets captured in the books ArrayList object. The for loop can be modified to make it more user friendly by asking he want to enter more book.
For example modify the above code to ask the user the following way.
Press 1: if you wish to add another book
Press 2: If you wish to view all the books
Press 3: If you wish to quit the program.
Further assignment.
Read a little about serialization.This will solve the problem of having the data stored in between runs.Then,modify the program to additionally do the following.
Press 4: If you wish to quit with books stored.
Press 5: If you wish to retrieved all archived books :)
Using .add() doesn't replace what is inside the ArrayList, it only adds a new element to the list.
That means to add more than one item, just use .add() multiple times.
Then you could get these items using their indices, for example:
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
In order to get 'item1', use list.get(0), and to get 'item2', use list.get(1).
Also, Java will not save variable data between runs. When a program ends, all the data stored inside any variables will be lost.
To save the data between runs, you could save the data to a file and read the data from it at the start of the run. Look into using a FileWriter and FileReader.

Validating the kind of data in an ArrayList java

Hello everyone~ I'm a little new in this theme of programming. I'm here to expose a particular case, of my college project, hoping that can find a way to validate the java code.
Basically, I'm designing a system to sum the daily sales of a company and save them into a matrix. The code below corresponds to the first day only.
package fsystem;
import java.util.ArrayList;
import java.util.Scanner;
public class class_Sist {
public class_Sist() {
}
ArrayList <Integer> MondayPrices = new ArrayList();
int Week[][]= new int [2][7];
public void addPricesDay1(){
Scanner scn = new Scanner(System.in);
String answer;
Integer auxAddition=0;
boolean flagNext= false, flagAgain= false;
System.out.println("Next it is come to apply the amounts of sales made on the day "+Week[0][0]+". Please "
+ "indicate the price of each of the items that were sold.");
do {
System.out.println("Enter the price of the corresponding article.");
MondayPrices.add(scn.nextInt());
do {
System.out.println("It requires enter the price of another article?");
answer= scn.next();
if (("Yes".equals(answer))||("yes".equals(answer))) {
flagNext=false;
flagAgain=true;
}
if (("No".equals(answer))||("no".equals(answer))){
flagNext=false;
flagAgain=false;
System.out.println("Introduced sales prices have been stored successfully.");
}
if ((!"Yes".equals(answer))&&(!"yes".equals(answer))&&(!"No".equals(answer))&&(!"no".equals(answer))) {
System.out.println("Error. Please respond using by answer only yes or no.");
flagNext=true;
}
} while (flagNext==true);
} while (flagAgain==true);
for (int i=0; i<MondayPrices.size(); i++) {
auxAddition= auxAddition+MondayPrices.get(i);
}
System.out.println("The total amount in sales for monday is "+auxAddition);
Week[1][0]=auxAddition;
}
}
So, what I need is to validate that the data inputted by the user be only numeric, and never otherwise, but I don't know completely how ArrayList works, therefore, I would greatly appreciate if someone could explain me how I can do that.
Use Scanner hasNextInt() function.
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method.The scanner does not advance past any input.
Use it with while to check whether the input is integer.
Scanner stdin = new Scanner(System.in);
while (!stdin.hasNextInt()) stdin.next();
MondayPrice.add(stdin.nextInt());
http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29
You can validate the input before adding the integer in the ArrayList.
I hope this will help - How to use Scanner to accept only valid int as input

Categories