How to do linearSearch to two ArrayList<String>? - java

I received a homework assignment to create a shopping list program where it will ask the user for a list of ingredients, and after the user enters them, it will compare the inputs to a "pantry list" to see if everything is available. If yes, then it will print out "You got everything you need!" and if no, it will print out "You still need" + "item that is missing." The specific instructions are:
A pre-created list for pantry items
User input into an ingredient list
Pass the ingredient list to a method
Use a conditional and loop in the method
Print out the results of whether the user needs to go shopping based on the items in the ingredient list that are not in the pantry.
Below is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class TheList
{
public static String linearSearch(ArrayList<String> pantry, ArrayList<String> input)
{
for (int i = 0; i < pantry.size(); i++)
{
if (pantry == input)
{
return "You got everything you need!";
}
}
return "You still need something!";
}
public static void main(String[] args)
{
// Create list for pantry items
ArrayList<String> pantry = new ArrayList<String>();
pantry.add("Bread");
pantry.add("Peanut Butter");
pantry.add("Chips");
pantry.add("Jelly");
//Create list for input items
ArrayList<String> input = new ArrayList<String>();
input.add("ingredientOne");
input.add("ingredientTwo");
input.add("ingredientThree");
input.add("ingredientFour");
// Execution
input();
System.out.println(linearSearch(pantry, input));
}
private static void input()
{
Scanner ingredientScan = new Scanner(System.in);
System.out.println("Please enter an ingredient: ");
String ingredientOne = ingredientScan.nextLine();
System.out.println(ingredientOne + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientTwo = ingredientScan.nextLine();
System.out.println(ingredientTwo + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientThree = ingredientScan.nextLine();
System.out.println(ingredientThree + " Done.");
System.out.println("Please enter an ingredient: ");
String ingredientFour = ingredientScan.nextLine();
System.out.println(ingredientFour + " Done.");
}
}
What am I missing? This is pretty amateur, but I am a beginner and really need some help!
My main question is the if part for the loop in the linearSearch string. When I execute the program, it always print out "You still need something!" As for which thing is missing, I have no clue where to start in that aspect.

I am assuming by linear search you mean searching if the pantry has everything in one pass.
For scenarios such as these using a Set is the best option because in a set you can search for a key in constant time.
private void search(Set<String> pantry,Set<String> ingredients){
for(String ingredient : ingredients){
if(!pantry.contains(ingredient)){
System.out.println("Something is missing");
return;
}
}
System.out.println("Everything is available");
return;
}
//Create a set like this
public void main(){
Set<String> pantry = new HashSet<>();
}

The answer is not hard, and since it's an assignment, maybe you need some advice:
The loop in the code is not utilized.
Also objects can't be compared using ==, it can only be compared using equals and in general you need to rewrite it.
Your problem is not that you need to use equals to compare, but that you need to do difference sets

Related

Why doesn't the boolean value register as true?

I am creating a shopping list program where it will ask the user for a list of input of pantry items. After that, the computer will compare the user's input and a pre-determined list of pantry items to see if the user got everything needed. Finally, it will either print out "You got everything," or "you still need something" plus the item missing.
This is the code I have, and everything works just fine, except one tiny error.
import java.util.*;
public class TheList
{
public static void main(String args[])
{
//scanner for user input
Scanner scan = new Scanner(System.in);
//pantry
ArrayList<String> pantry = new ArrayList<String>();
pantry.add("Bread");
pantry.add("Peanut Butter");
pantry.add("Chips");
pantry.add("Jelly");
//user input
ArrayList<String> input = new ArrayList<String>();
while(true)
{
System.out.println("Please enter an ingredient ('done' when complete): ");
String userInput = "";
if (scan.hasNextLine())
{
userInput = scan.nextLine();
}
if (userInput.equals("done"))
{
break;
}
input.add(userInput);
}
//print out result
boolean shoppingDone = input.contains(pantry);
if (shoppingDone == true) {
System.out.println("It looks like you have everything to make your recipe!");
}
else {
pantry.removeAll(input);
System.out.println("You need to go shopping!");
System.out.println("The following ingredients are missing:");
System.out.println(pantry);
}
}
}
My boolean value doesn't register as true, even if all elements from pantry list is contained in the input list. Why is that?
ArryList.contains() checks if a particular object is present in the collection. You probably want to use the containsAll method.

How do I search for null in this ArrayList and then replace it with another Object?

I have been writing code of a car parking structure for a bit now and i've gotten kinda stuck. So far I have an ArrayList that the user adds Vehicle properties to aswell as an ArrayList for a parking space with a "SpaceID" and the "Vehicle" from earlier.
So far I can make it so that the user adds the vehicle, and the vehicle gets added to a parking space, However I have made a temporary parking space with the index 0: and the element (vehicle) being null.
From here, I wanted to check the parking space ArrayList for "null" and then if it's found, replace null with the vehicle, However, I do not know how to go about implementing this. I will attach the current code i'm using, or at least a minimal version of it.
I have already tried using a Contains(null) method, but I can't seem to get that to work properly, I'm not sure if it even can work, but I have since then removed it from my code.
First of all, I have the function to create the vehicle and store it in an Array.
```
public void carInfo(Vehicle tempVehicle, parkingSpace vehicle) {
array = new MCP();
System.out.println("Please enter number plate: ");
input = new Scanner(System.in);
String plate = input.nextLine();
System.out.println("Please enter car make: ");
input = new Scanner(System.in);
String make = input.nextLine();
System.out.println("How would you best describe your Vehicle? ");
System.out.println("(Car, Small Van, Tall Van, Long Van, Coach,
Motorbike)");
type = new Scanner(System.in);
String type1 = input.nextLine();
if (type1.equalsIgnoreCase(vehicleType.CAR.toString())) {
tempVehicle.setPlate(plate);
tempVehicle.setCarMake(make);
tempVehicle.setVehicle(vehicleType.CAR);
inv.createInvoice();
tempVehicle.setInvoiceNumber(inv.invoiceNumber);
array.addStandard(tempVehicle);
array.parkVehicle(vehicle);
System.out.println(tempVehicle.toString());
System.out.println(vehicle.toString());
```
I also have my Arrays, which are on another class.
```
public MCP(){
vehicles = new ArrayList<>();
parkingSpaces = new ArrayList<>();
parkingSpaces.add(0, null);
parkingSpaces.add(1, null);
}
public void addStandard(Vehicle tempVehicle) {
vehicles.add(tempVehicle);
}
public void parkVehicle(parkingSpace vehicle) {
parkingSpaces.add(vehicle);
}
```
This is the way I tried to do it, but I couldn't figure this way out, so I stopped, i'm open to any other ways too.
// public void checkIfEmpty(parkingSpace vehicle){
// if(parkingSpaces.contains(null)){
// parkingSpaces.add(vehicle);
// }
// else{
// System.out.println("There is no room in this Zone");
// }
// }
I am also looking for a better way to populate parking spaces, but that's not the main concern, just something else just incase someone has any ideas
Thanks in Advance.
Since you are using an array list, when an item is deleted from it, there will be no empty element between two elements in it. When you delete an element, the elements shift. So in the case of this code, it checks if the number of elements in the array list is smaller than maximum number of cars
int maxSize = 10; //suppose that the maximum number of cars is 10
public void checkIfEmpty(parkingSpace vehicle){
if(parkingSpaces.size() < maxSize){
parkingSpaces.add(vehicle);
}
else{
System.out.println("There is no room in this Zone");
}
}
Try doing something like this:
public void checkIfEmpty(parkingSpace vehicle) {
boolean addedVehicle = false;
for (int i = 0; i < parkingSpaces.size(); i++){
if (parkingSpaces.get(i) == null) {
parkingSpaces.add(vehicle);
addedVehicle = true;
break;
}
}
if (!addedVehicle)
System.out.println("There is no room in this Zone");
}

several java class validation input

I have created a program on netbeans using java. The user is prompted to enter a "Number: ". For example, when they enter the number "1" the data from the array list appears "Number: 1" "Name: userA" and "Phone: 2". If i enter a value which isn't on the array list, for example 5 userA's details will appear. How could i enter in validation to check whether or not the number entered is held within the array list? If the number isn't in the array list is there a way of telling the user this and allowing them to try again to enter in the number.
Data Class:
public class Data {
private final List<DetailsT> DetailsL;
public Data() {
DetailsL = new ArrayList<>();
DetailsL.add(new DetailsT(1, "userA", 2));
DetailsL.add(new DetailsT(2, "userB", 9);
}
public ArrayList<?> getList() {
return (ArrayList<?>) DetailsL;
}
Output Class:
//initialize streams so we can send message
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
Data p = new Data();
List<DetailsT> DetailsL = (List<DetailsT>) p.getList();
for (DetailsTq : detailsT) {
int number;
while (true) {
// as soon as a message is being received, print it out!
number = in.readInt();
System.out.println("\n" + "Number: " + number);
}
}
}
}
Furthermore, when the user enters -1 into the program the session should end. I have attempted this in my code although when entering "-1", userA's details are still retrieved. All help would be appreciated, thank-you.
Assuming number is an attribute in DetailsT class, you can write a method in Data class which returns Details object for number by iterating the array list, e.g.:
public DetailsT findByNumber(int number){
for(DetailsT details : DetailsL){
if(details.getNumber() == number){
return details;
}
}
return null;
}
In main, you can call this method, and if it returns null then, you can prompt user to enter the number again, e.g.:
Data data = new Data();
DetailsT details = data.findByNumber(number);
if(details == null){
//do something
}else{
//do something else
}

How do I make this get method for array lists simpler? [duplicate]

This question already has answers here:
Ways to iterate over a list in Java
(13 answers)
Closed 7 years ago.
import java.util.*;
public class ChristmasParty
{
private Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
ChristmasParty cp = new ChristmasParty();
cp.run();
}
public void run()
{
menu();
addName();
}
public void menu()
{
System.out.println("Welcome to the guests lists program");
System.out.println("Enter a name or enter X to quit");
}
public void addName()
{
String nameAdded = "";
ArrayList<String> guestsLists = new ArrayList<String>();
do
{
System.out.print("Enter a name: ");
nameAdded = input.nextLine();
guestsLists.add(nameAdded);
System.out.println("-----------------------------------------------");
System.out.println(nameAdded + " has been added to the guests list.");
}while(!nameAdded.equals("X"));
System.out.println("Guests lists:");
System.out.println("========================");
System.out.println(guestsLists.get(0));
System.out.println(guestsLists.get(1));
System.out.println(guestsLists.get(2));
System.out.println(guestsLists.get(3));
System.out.println(guestsLists.get(4));
System.out.println(guestsLists.get(5));
System.out.println(guestsLists.get(6));
System.out.println(guestsLists.get(7));
System.out.println(guestsLists.get(8));
System.out.println(guestsLists.get(9));
System.out.println(guestsLists.get(10));
System.out.println(guestsLists.get(11));
System.out.println(guestsLists.get(12));
System.out.println(guestsLists.get(13));
System.out.println(guestsLists.get(14));
System.out.println(guestsLists.get(15));
}
}
Hello, I am trying to make a code that will prompt the user to enter a name,and that name will be saved in the arraylists, and then once the user exits and quits by pressing "X", it will display all the names in the lists. However how do I make the System.out.println(guestsLists.get()); codes simpler rather than typing it all out?
Put this code:
}while(!nameAdded.equals("X"));
System.out.println("Guests lists:");
System.out.println("========================");
for(int i = 0; i < guestsLists.size(); i++)
{
System.out.println(guestsLists.get(i));
}
OR
for(String s : guestsLists)
{
System.out.println(s);
}
And remove all the sysouts after the
System.out.println("========================");
Simply iterate through the list using an enhanced for loop:
...
for (String name : guestsLists) {
System.err.println(name);
}
...
You can use that form of a for loop when you do not need an index inside the loop, but just want to iterate over the collection. In these cases, it is much easier to read (and less code) than using an explicit index (or using an explicit Iterator).
See also https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

Instance variable with the same value for different objects although different values were assigned

First of all and before posting my question let me ask you people to stop downvoting my questions even if they seem stupid to you ,this site is an important place for me, it helps me a lot with my java doubts which are many,a question ban would be an heavy setback for me, so be helpful even by not answering!
Now for the question,
I have this method were i assign a value to a setter method with user input
public void addName() {
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add a citizen name?");
String answer = input.nextLine();
while (!answer.equals("y") || (!answer.equals("n"))) {
if (answer.equals("y")) {
String giveName = input.nextLine();
this.setName(giveName);
break;
} else if (answer.equals("n")) {
System.out.println("Not adding a name!");
break;
}else{System.out.println("Please choose y or n!");
answer = input.nextLine();}
}
}
this method is later called in main from object p1 and object p2 and being assigned a differend value for each one to the instance variable name
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Portugueses();
Pessoas p2 = new Alemaes();
p1.addName();
p2.addName();
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
but when i call the getName() method at the end of main both p1 and p2 have the same value!
Shouldn't each object get it´s own copy of an instance variable?
The Problem is in your addName()-function. Your running your loop(while (!answer.equals("y") || (!answer.equals("n")))) until a y or n is entered. So as soon as you enter it, your loop will stop.
In your loop your checking if the input that was made cotains a y or n. Now the problem should be clear. Your loop won't run with those two values entered, but inside the loop you want to check if one of those is entered.
Two little personal hints(everyone has another style): Don't use break; let your loops end themselfs. Do it with an boolean-variable and updating it's state.
The second hint would be to use one Scanner-Object. For example you could add a Scanner-parameter to your addName-function. Just init one in your MainClass.
Those hints and fixes of the problem applied to your code could look like that:
public void addName(Scanner input) {
System.out.println("Do you want to add a citizen name?");
String answer;
boolean isAnotherInputNeeded = true;
while (isAnotherInputNeeded) {
answer = input.nextLine();
if (answer.equals("y"))
{
System.out.println("What's the name?");
String giveName = input.nextLine();
this.setName(giveName);
isAnotherInputNeeded= false;
}
else if (answer.equals("n"))
{
System.out.println("Not adding a name!");
this.setName("No name entered");
isAnotherInputNeeded= false;;
}
else
{
System.out.println("Please choose y or n!");
}
input.reset();
}
}
And your MainClass:
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Pessoas();
Pessoas p2 = new Pessoas();
Scanner input = new Scanner(System.in);
p1.addName(input);
p2.addName(input);
System.out.println("You entered the following names:");
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
Hope that helps!

Categories