Adding/set variable to Array from another method - java

Ok, so I'm more of a dunce than a beginner so bear with me.
What I'm trying to accomplished is to try to set/add variable within an array.
The question I am doing is to create a package and call another method called addAccommodation(); and use that method to add the required info and adding it to TravelPackage travelpackage.
I'm posting section of the issue here. The arraylist is called travelPackages and the one I want to add variables into is TravelPackage travelpackage.
(addAccommodation(); is the method soppose to lead another section, and travelpackage.setAccID is the issue I'm trying to solve)
public void addPackages() {
Scanner input = new Scanner(System.in);
System.out.println("Input Customer ID: ");
int customerID = input.nextInt();
input.nextLine();
System.out.print("Input Duration in Days: ");
int duration = input.nextInt();
input.nextLine();
System.out.print("Date in format yyyy-mm-dd? ");
String date = input.nextLine();
LocalDate startDate = null;
try{
startDate = LocalDate.parse(date);
}
catch(Exception e){}
TravelPackage travelpackage = new TravelPackage(customerID, duration, startDate);
travelPackages.add(travelpackage);
addAccommodation();
}
public void addAccommodation(){
Scanner input = new Scanner(System.in);
boolean match = false;
while(true) {
System.out.print("Input Accommodation Type(Hotel, Lodge, Ski Club, Apartment, Village): ");
String type = input.nextLine();
for (Accommodation a: accommodations) {
if (a.getType().equalsIgnoreCase(type) && a.getAvailability()) {
// Update accommodation status in ArrayList
a.setAvailability(false);
travelpackage.setAccID(a.getAccID());
// Set match flag to break loop
match = true;
// Stop searching for matching bike
break;
}
}
if(match){
System.out.println("Did not find a match.");
break;
}
}
}
It keep saying cannot find symbol. Is there something I'm missing here? (Sorry if I can't provide proper info, I am quite dumb)

Related

Why is my String Variable empty after assigning something to it for a second time? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I am doing a project for school, and I am trying to make it to where you can set up a name for yourself while going through a series of questions asked by the computer. I want the user to be able to change their name right after assigning it if they do not like what they put down or they typed something wrong.
Right now the program assigns the name the user wants correctly the first time, but when it goes back through the loop to change it to something else the string is left blank.
Console Output
'''
import java.util.*;
public class JavaInputProdject
{
public static void main(String args[])
{
int i=0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old=false;
boolean aAge=true;
String user="User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n"+un);
do
{
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \""+ user +"\"(true/false)");
System.out.print(un);
if(bob.nextBoolean()==true)
{
boo = true;
un = user + "> ";
}
else
{
if(i>=3)
{
System.out.println("Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n"+un);
bob.next();
i++;
}
} while(boo==false);
}
}
'''
You need to replace the line bob.next() (near the end of the do-while loop) with bob.nextLine().
I believe that bob.next() does not consume the newline that is entered as a result of hitting the <ENTER> key after the bob.nextBoolean() call. Hence the user = bob.nextLine(); line (at the start of the do-while loop) is consuming that newline on the second and subsequent loop iterations. So replacing bob.next() with bob.nextLine() will resolve the problem.
For the sake of completeness, here is the corrected code:
import java.util.Scanner;
public class JavaInputProdject {
public static void main(String[] args) {
int i = 0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old = false;
boolean aAge = true;
String user = "User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n" + un);
do {
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \"" + user + "\"(true/false)");
System.out.print(un);
if (bob.nextBoolean()) {
boo = true;
un = user + "> ";
}
else {
if (i >= 3) {
System.out.println(
"Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n" + un);
bob.nextLine();
i++;
}
} while (boo == false);
}
}
Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
when you want to get correct username based on false flag you doesnt init a value to user.
you should write something like this with bob.nextLine :
System.out.print("Bob> Please type in a new Username\n"+un);
user = bob.nextLine();
i++;

NullPointerException when using .size() in an Arraylist class

currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main

Can't get my code to return an object from my ArrayList

I am trying to get it so that when a user enters, for example, the model of a guitar that it will return all the details for that specific model from my ArrayList. However, I get no errors when I run the program just no results. I have no clue what to do, any help would be greatly appreciated.
P.S. In my switch cases I kept trying multiple different ways to get results with no luck so please ignore if it is all over the place.
package guitarsrentalmanagementsystem;
import StockManagement.Guitar;
import java.util.ArrayList;
import java.util.Scanner;
public class GuitarsRentalManagementSystem {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<Guitar> data = new ArrayList<>();
data.add(new Guitar(100, 150.99, "Gibson", "Les Paul",
"Acoustic", "INDIAN_ROSEWOOD", "MAHOGANY", 1995, 8.99, "Red",
true));
data.add(new Guitar(101, 180.00, "Fender", "Stratocaster",
"Electric", "BRAZILIAN_ROSEWOOD", "MAHOGANY", 2001, 10.99, "Brown",
true));
data.add(new Guitar(102, 110.50, "Martin", "Noisemaker",
"Acoustic", "INDIAN_ROSEWOOD", "BRAZILIAN_ROSEWOOD", 2005, 5.99, "Black",
true));
for(Guitar g : data){
g.printDetail();
}
//Show data from the adobe arraylist
System.out.println("Valid search parameters are as follows :");
System.out.println("1. Model, eg Les Paul");
System.out.println("2. Serial number, eg 101");
System.out.println("3. Year of manufacture, eg 2001");
Scanner input = new Scanner(System.in);
System.out.println("Please select how you would like to search");
int search = input.nextInt();
for(Guitar g : data){
switch(search){
case 1:
System.out.println("You have chosen to search by model");
System.out.println("Valid models are Les Paul, Stratocaster or Noisemaker");
System.out.println("Please enter a model to search");
Scanner inputO1 = new Scanner(System.in);
String modelSearch = input.next();
if("Les Paul".equals(modelSearch)){
g.printDetail();
}
break;
case 2:
System.out.println("You have chosen to search by Serial number");
System.out.println("valid serial numbers are between 100 and 105");
System.out.println("Please enter a serial number to search");
Scanner inputO2 = new Scanner(System.in);
int serialSearch = input.nextInt();
System.out.println(g.getSerialNumber());
break;
case 3:
System.out.println("You have chosen to search by year of manufacture");
System.out.println("Valid manufacture dates are 1995, 2001 and 2005");
System.out.println("Please enter a manufacture year to search");
Scanner input03 = new Scanner(System.in);
int yearSearch = input.nextInt();
System.out.println(g.getYearOfManufacture());
break;
}
break;
}
}
}
There's issue with the way you are reading input: when you use scanner object and call nextInt() on it. it reads just the number. similarly when you call next it reads just one string value, i.e.
if you have entered "Les Paul" as input, scanner object next() method will ready only Les, so it wouldn't match with your condition.
so once you read integer call nextLine() method, so the cursor moves to next line, now read input from the next line by calling again the nextLine() method
case 1:
System.out.println("You have chosen to search by model");
System.out.println("Valid models are Les Paul, Stratocaster or Noisemaker");
System.out.println("Please enter a model to search");
Scanner inputO1 = new Scanner(System.in);
input.nextLine();
String modelSearch = input.nextLine();
if ("Les Paul".equals(modelSearch)) {
g.printDetail();
}
break;
the above code will work if the user enters model as "Les Paul".

Change specific data from an ArrayList

The exercise is, to create an arraylist for a class, where a User can enter "Guestnumber" + "Guestname" + "Guestemail".
In the menu you could remove an existing "Guest" with all the Information. Thats the code for it: (it works)
public void gastAendern() {
System.out.println("Guestnumber to delete:");
Scanner sc = new Scanner(System.in);
String input = sc.next();
for (Gast test : verwaltungG) {
int nummer = Integer.parseInt(input);
if (test.getgNr() == nummer) {
verwaltungG.remove(test);
a = 1;
break;
}
}
if(a==0) {
System.out.println("Guestnumber is not used");
verwaltungG is the ArrayList
Gast is the class for get+set
But now I got a problem to change an existing Guest, like for example:
I ask to type in the Guestnumber OR the Guestname OR the Guestmail to change it (I have to do it for all 3). So I have really no idea how to change it. I looked through Stackoverflow, google etc. but it only shows how to change them with List.set, but I don't know if it works with my kind of Problem, because I don't know how to use it.
You can do something similar as you are doing for delete, instead of remove - you need to change the details you need update :
System.out.println("Guestnumber to update :");
Scanner sc = new Scanner(System.in);
String input = sc.next();
for (Gast test : verwaltungG) {
int nummer = Integer.parseInt(input);
if (test.getgNr() == nummer) {
System.out.println("Enter new guest name for guest number : "+nummer );
String name = sc.nextLine();
System.out.println("Enter new guest email for guest number : "+nummer );
String email = sc.nextLine();
// now update the details
test.setName(name);
test.setEmail(email);
break;
}
}

Java for loop with if statement only iterating once

I have a version of a login for an employee system i would like to make, I have a for loop which should go through the entire list of Accounts, then see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!! What am i doing wrong? Also my list contains Employees and Managers which inherit from Account, the if statement uses the getName in Account to compare if it equals to the user input. Sorry if this is ridiculously stupid/bad! thanks.
List <Account> Accounts = new LinkedList<Account>();
Here is where i populate my Account, the main method calls this and the list() is called whihc contains the problematic loop
public void add() {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
problem:
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
}
}
System.out.println("Employee does not exist!");
login();
}
I am doing the print statement in the for loop to see what it is findng, and unfortunalty it is only the first account
EDIT: I have included more code here, my after my initial if statement i want to check if the code the user enters is also correct.
see if the name of an employee matches one in the list then the if
statement continues, further questions asked etc... it seems to only
iterate once and then stop as it will only find the first user and
tell me the other accounts do not exisit, even though they do!!
If it works for one employee and tells that others don't exist then your for loop does not iterate once.
The output you get is exactly what the code looks like. You get username once then try to match the same name with every employee in the list. If the names are equal you ask for password, otherwise you print out that employee doesn't exist. Everything right as it is in the code. You should add to your question the expected behaviour so I, or someone else can fix your code without guessing the purpose of your methods.
Here's one of those guesses:
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
userFound = true;
break;
}
}
}
if(userFound) {
login();
} else {
System.out.println("User not found.");
}
This is a possible solution that doesn't use your Account class (since I do not know what it looks like) and instead uses a Map:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = input.nextLine();
boolean found = false;
Map<String, String> accounts = new HashMap<String, String>();
accounts.put("Geoff", "password1");
accounts.put("Bob", "password2");
accounts.put("John", "password3");
Set<String> names = accounts.keySet();
for (String a : names)
{
if (!a.equals(empName))
{
continue;
}
found = true;
// three tries to login
boolean success = false;
for(int i = 0; i < 3; i++)
{
System.out.println("Please enter your passcode: ");
String code = input.nextLine();
if (accounts.get(a).equals(code))
{
System.out.println("logged in");
success = true;
}
else
{
System.out.println("Wrong password... try again");
}
}
if(!success)
{
System.out.println("User failed to authenticate after 3 attempts. User has been locked out!");
}
}
if(!found)
{
System.out.println("Employee does not exist!");
}
}
Since I do not know what the login() method does, I just simply added that into the code. This solution iterates three times in an attempt to get the correct password. If that fails, a message is displayed.

Categories

Resources