I am creating a member application using the scanner to input data into an array called memberList. The data is going into an object and then the object is being stored in the array. I am using string and integers in the object.
I am writing a method to change one of the string variables in the array from yes to no, it is whether the member has paid their fees or not.
I am trying to enter the members name by calling my getName method and using the setFeePaid to change the String to "yes" from "no".
There is something wrong with the loop, as it only lets me change the first member in the array. Could anyone help please.
public static void payMemberYearlyFees(){
for (int i=0; i < memberCount; i++) {
Member member = memberList[i];
System.out.println("Enter the name of the member who has to pay their fee:");
if (input.nextLine().equals(member.getName())) {
member.setFeePaid("yes");
System.out.println();
System.out.println(member.getName() +" has paid their membership fee.\n");
System.out.println("********Returning to Main Menu.********\n");
}
else{
System.out.println();
break;
}
}
}
In your for loop, you are first taking a member (the first one in the list) and then asking the user to input a name. It then checks if the input name is the same as the member that you've taken (remember, only the first of the list). If you input any other name, the if statement fails and you go to the else block, which stops the loop.
This should work:
public static void payMemberYearlyFees(){
System.out.println("Enter the name of the member who has to pay their fee:");
String inputName = input.nextLine();
for (int i=0; i < memberCount; i++) {
Member member = memberList[i];
if (inputName.equals(member.getName())) {
member.setFeePaid("yes");
System.out.println();
System.out.println(member.getName() +" has paid their membership fee.\n");
System.out.println("********Returning to Main Menu.********\n");
break;
}
}
}
Then call this method as many times as you want. If you want your code to be a bit cleaner, you can do the for loop this way:
for (Member member : memberList){
if (inputName.equals(member.getName())) {
member.setFeePaid("yes");
System.out.println();
System.out.println(member.getName() +" has paid their membership fee.\n");
System.out.println("********Returning to Main Menu.********\n");
break;
}
}
That way you just take the members of your list one by one without having to deal with the i variable and manually pick the i member of the list.
Related
The code doesn't show any errors. However, I am getting an unexpected output. I am supposed to get the smallest number for age, but what I keep getting is the last value entered for age. Can you help me point out the mistakes in this code?
Maybe there is some logical error in the getYoungestPet() method?
package pet;
public class Pet
{
public static String petName;
public static int petAge, petWeight;
int youngestAge=9999;
static int test;
public static String setPetName()
{
return petName;
}
public int setPetAge()
{
return petAge;
}
public int setPetWeight()
{
return petWeight;
}
public int getYoungestPet() //probably an error here..?
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}
}
package pet;
import java.util.Scanner;
public class PetMain extends Pet
{
public static void main(String[] args)
{
System.out.println("How many pets do you want to enter? " );
Scanner data= new Scanner(System.in);
int petNumber=data.nextInt();
for (int i = 1;i<=petNumber; i++)
{
Pet PetObject = new Pet();
System.out.println("Please enter name for Pet " + i );
Scanner input = new Scanner(System.in);
petName= input.next();
System.out.println("Your pet's name is : " + petName);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Age" );
petAge= input.nextInt();
System.out.println("Your pet's age is : " + petAge);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Weight" );
petWeight= input.nextInt();
System.out.println("Your pet's weight is : " + petWeight);
System.out.println(" ");
System.out.println(PetObject.getYoungestPet());
}
}
}
The code is supposed to show the smallest age but it shows the latest entered age.
you should declare youngestAge as static variable. so that all of the petObject could share the same value.
static int youngestAge=9999;
your setter and getter methods are also not proper.
public static String setPetName()
{
return petName;
}
should be:
public static void setPetName(String name)
{
petName=name;
}
Also don't forget to set values into PetObject from main method.
...
petName= input.next();
PetObject.setPetName(petName);
...
There are many things that are problematic with this code.
But just to answer your question directly, think about how many pet objects there could be in this program if every time the for loop runs it recreates the pet object because it is inside the for loop.
however, simply moving it outside the for loop will not help because then you will simply keep resetting the values of the same pet object every time you run the for loop.
Consider making an array of pet objects.
Also, your code never actually accesses the pet objects instance variables
In addition, there are other problems with your use of static as others have pointed out.
cheers.
Each time you are creating a Pet, you are getting a different youngestAge with value 9999 for that object. So each time it is comparing the latest petAge with 9999 and giving you the latest petAge as your enterd petAge is less than 9999.
If you need to store the smallest age, then keep it in a static field. Cause, keeping an extra field to store the smallest age for all object is redundant for memory.
If you want your desired output with the existing design, then do this:
Make youngestAge static:
static int youngestAge=9999;
And also don't forget to make the method static too. There is no need to make it object property anymore, both the field variables, it is using, are static.
public static int getYoungestPet()
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}
I'm making a "dog register" where you can save information about dogs and bid on dogs up for auction etc.
I am a beginner and was recently told that array list should be private, this information got me in some trouble.
I got a class named Auction where you can store bids, I made a get method in this class to use in the main class. It works on every line except one in my method where you can delete a user.
private void deleteUser()
{
System.out.println("Enter the name of the user: ");
String name = input.nextLine().toLowerCase().trim();
User deleteUser = getUser(name);
while (name.isEmpty()) {
System.out.println("Error. Enter the name of the user: ");
name = input.nextLine().toLowerCase().trim();
deleteUser = getUser(name);
}
if (deleteUser == null) {
userException();
return;
}
for (Auction a : auctionRegister) {
ArrayList<Bid> bids = new ArrayList<>();
for (Bid b : a.getBidList()) {
if (b.getUser() != deleteUser) {
bids.add(b);
}
}
a.getBidList() = bids;
}
if (deleteUser.getDogList() != null) {
for (Dog dog : deleteUser.getDogList()) {
dogRegister.remove(dog);
}
}
userRegister.remove(deleteUser);
System.out.println("User " + deleteUser.getUserName() + " is removed");
}
I get the error message on this line("The left-hand side of an assignment must be a variable"):
a.getBidList() = bids;
Everything worked when i had the array list public so my question is, how do i solve this?
Java has 2 varieties of 'buckets' in which to store information. One variety is a variable, the other is a constant. Both varieties let you look in the bucket to see the contents. A variable also allows you to you replace the current contents of the bucket.
Your syntax , a.setBidList() is a method call, which is constant. You can read from it but you can't assign a new value to it. Since you have it on the left side of an assignment statement, you are asking Java to do something it can't do.
I do not know how to do the borrowHolding() in the Library Menu I have to create.
So the purpose of the borrowHolding() is for members to be able to borrow books or videos.
This is a just a sample data of the array:
member[0] = new StandardMember("ID", "Name");
member[1] = new PremiumMember("ID", "Name");
holding[0] = new Book("ID", "Title");
holding[1] = new Video("ID", "Title", loanFee);
This is the borrowHolding() method in the TestLibrary class: (the array is in the TestLibrary class too)
public static void borrowHolding(){
String option;
option = input.next();
do{
Scanner scan = new Scanner(System.in);
int tempId = 0;
System.out.println("Enter your ID: ");
String searchID = scan.next();
for(int i = 0; i < member.length; i++){
if(member[i].getID().equals(searchID)){
tempId = i;
}
}
So for the method, I tried to write a code that will search through the array to find the memberID that wants to borrow. It is not completed yet because I believe I am not doing it correctly
There is a Member class that contains
public class Member{
public Holding[] getCurrentHoldings(){
}
}
from the name of the method, it is used to store the holdings of the members that borrowed. So if member 1 borrows a book, that book will be stored inside the array, i think. I was thinking of using an ArrayList for this method, but not sure if it would make sense.
To borrow a book or video, there are certain conditions to be able to borrow, but I do not know how to implement this into the borrowHolding(). One of the condition are in the Holding class.
public class Holding{
public boolean borrowHolding(){
if(status == true && isOnLoan() == false)
borrowDate = newDateTime(); //this is to get the time when the book or video is borrowed
return true;
}else
return false;
}
}
And there is another condition in the Member class is that the Member must have enough credit to borrow. A book loan fee will cost $10 and a video will vary from $4 or $6.
I think I wrote a few information that is not needed but I guess its better than less information.
My problem is what do I do to the borrowHolding() method in the LibraryMenu? how do I make that if a member wants to borrow a holding, the holding will go under the member's array in the member class
public class Member{
public Holding[] getCurrentHoldings(){
}
}
with the condition from the holding class if it is met, and while executing the borrowHolding method, the method from the member class will be able to subtract the member credit by the loan fee from the book or video. is it possible?
public class Member{
private int credit = 30;
public int calculateRemainingCredit(){
credit = credit - //(the loan fee from the book or video class)
}
}
If your intentions are to add a holding to the member class then this is possible. I would suggest adding an ArrayList of Holding's rather than a regular array because it seems as if the size is going to be constantly changing.
public class Member{
private ArrayList<Holding> currentholdings; // you may need to import the arraylist
private int credit;
public void init(){ // goes in constructor
currentholdings = new ArrayList<Holding>();
credit=0;
}
public void addHolding(Holding newholding){ // adds a new holding to the members array
currentholdings.add(newholding);
credit-=newholding.getFee(); // will need to add a fee variable to the holding class;
}
}
And as for checking to see whether or not the member has enough "credit", that can be done in the borrowHolding() method right after you identify the index of the array. I would just recommend adding a parameter of the member to the borrowHolding() method so you can easily access the variables from that member.
if(member[i].getID().equals(searchID)){
tempId = i;
int tempHolding; // index of whatever holding you wanted (could get this from the scanner)
if (holding[tempHolding].borrowHolding(member[tempId])){ // check status
member[tempId].addHolding(holding[tempHolding]); // they have passed the req. so you can add the holding
}
break;
}
Hope this answered your question.
The assignment for my class asks me to create a program that tells a supermarket which customer, on a daily basis, has spent the most money in the store. The program must find this customer and display their name.
Goals of assignment - To work with multiple classes, work with ArrayLists and apply the knowledge gained.
My question:
How should I loop my two output statements in my main class? Is that right in my main method? I need it to loop until the sentinel is used.
How is this going to affect my sentinel?
What type of questions should I be asking myself when dealing with loops? I'd like to think I'm overthinking this portion.
I really want to understand what I am doing here, so any help in the right direction would be appreciated! Thanks, in advance, for taking the time to help me out!
import java.util.Scanner;
public class main {
public static void main(String[] args) {
System.out.println("* * * * * THE SUPERMARKET * * * * *");
System.out.println(" Written by Nate Irwin");
System.out.println();
double finalTotal = -1;
String anAccountName;
Scanner input = new Scanner(System.in);
Store store = new Store();
do {
System.out.println("Enter the customer name: ");
if(input.hasNextLine()){
anAccountName = input.nextLine();
System.out.println("Enter customer total price, hit 0 to QUIT: ");
finalTotal = input.nextDouble();
store.addAccount(anAccountName, finalTotal);
System.out.println();
}
} while (finalTotal != 0);
System.out.println(store.getHighestCustomerTotal() + " has spent the most with us today!");
}
}
Store class:
import java.util.ArrayList;
public class Store {
// Creates an ArrayList.
private ArrayList<CustomerAccount> accounts = new ArrayList<CustomerAccount>();
//
public void addAccount(String anAccountName, double finalTotal) {
accounts.add(new CustomerAccount(anAccountName, finalTotal));
}
// Gets the HIGHEST customer total.
public String getHighestCustomerTotal() {
CustomerAccount highest = accounts.get(0);
for (int i = 1; i < accounts.size(); i++) {
if (accounts.get(i).getTotal() > highest.getTotal())
{
highest = accounts.get(i);
}
}
return highest.getAccountName();
}
}
CustomerAccount class:
public class CustomerAccount {
// Variables defined to this class.
private String accountName;
private double total;
// Constructor.
public CustomerAccount(String anAccountName, double finalTotal) {
accountName = anAccountName;
total = finalTotal;
}
// Gets total from each customer.
public double getTotal() {
return total;
}
// Gets a customer's name.
public String getAccountName() {
return accountName;
}
}
I think your approach is fine, it gets the job done.
I'm not too sure what you're asking by saying how should you loop the two output statements, followed by if it should be in the main method. From what I understand, and by looking at your code, running this input loop is perfectly fine from the main class. The do-while is fine although I'd move the first 'introductory' output outside the loop so you don't see it every time the loop reiterates.
Also, I notice you're not actually calling/instantiating the Store class in your main method, there's no data being added to the Store class for when it iterates through the accounts ArrayList.
As far as the answer that stated a more "modern" approach, I think the for loop you used is fine. I think the person was referring to the for-each loop. It doesn't really matter how you loop through it with the little amount of data you have.
There's some error in the logic for that loop. The getHighestCustomerTotal() is referencing an empty accounts ArrayList. You declared an ArrayList within the Store class and tried to loop through it but it's empty unless you called the addAccount() method from your main method at some point, so you'd need some error checking on that.
Your loop in main:
Doesn't really use the data you type in... One would expect this data to be used to create CustomerAccount instances
Has a completely unnecessary while(Condition) test at the end. This kind of loop is normally done with a While True and some test in the loop breaks out of the loop.
In getHighestCustomerTotal()
you can use a more "modern" form of the for() where you iterate elements of the list directly instead of iterating the index.
I'm working on a class that will take user input to assign values to an object created in a source class. Those objects will then be added to an array, which then prints the values on it. However, the "list" under print : list is telling me that I need to initialize the variable. Why is it not recognizing that this is an array even though it seems to work fine in my do loop?
import java.util.Scanner;
import name.Names;
public class NameTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
String entry;
Scanner firstscan = new Scanner(System.in);
Scanner lastscan = new Scanner(System.in);
Scanner codescan = new Scanner(System.in);
Scanner entryscan = new Scanner(System.in);
String first;
String last;
int code;
System.out
.println("This program will prompt you to input first name, +"
+ "last name, and zip code for an individual. Hit \"x\" when finished\n");
do {
System.out.println("Enter first name:");
first = firstscan.nextLine();
System.out.println("Enter last name:");
last = lastscan.nextLine();
System.out.println("Enter zip code:");
code = codescan.nextInt();
Names nm = new Names(first, last, code);
Names[] list = new Names[25];
int count = 0;
list[count] = nm;
count++;
System.out
.println("To quit hit \"X\" or any other key followed by enter to continue:");
entry = entryscan.nextLine();
} while (!(entry.equalsIgnoreCase("x")));
for (Names print : list)
System.out.println(print + "");
}
}
For one, you are instantiating your array inside your loop, that means every time your loop runs through, it creates a new array instead of updating the old one. Then, once you leave your loop, you leave its "scope". That means everything you declare inside the loop is not available outside. The solution is to declare your array outside the loop.
Every block in java has its own scope (defined through brackets). While you can access variables that have been declared outside your block while inside it, it does not work the other way around; as you can see. Just google java scope, and you will understand more. Hope that helps ;)
You will need a method in the class Name that return the first, last name and the zip code because if you just use:
System.out.println(print + "")
You are printing the object Name and no the String that represents the attributes saved in the object.
For example you can have the method in the class Name:
String getFirst()
{
return this.first;
}
And the last line in your class Nametester can be
System.out.println(print.getFirst() + "");