Calling method Java - java

Im having difficulty understanding what exactly I should pass my third method in the main class with. Im really just sort of lost at this point. Any help would be awesome. Here is my code that I have written:
Also, here are the directions for boolean method called "getOrder":
Write a method called getOrder that takes an ArrayList of Strings as a parameter (the products ArrayList) and returns a boolean.
In the method body, prompt the user to enter a product name (a String), then check whether the product name exists in the ArrayList of strings.
If it exists, return true, otherwise return false.
public static void main(String[] args) {
// Call your methods here
bannerPrinter();
productBuilder();
getOrder(??); -----------------------------Confused as to what to pass this method with
}
// Write your methods below here
public static boolean getOrder(ArrayList<String> products) {
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Please enter a product name: ");
String productName = in.nextLine();
if (products.contains(productName)) {
return true;
}
else {
return false;
}
}
public static ArrayList<String> productBuilder() {
ArrayList<String> products = new ArrayList<String>();
products.add("Desktop");
products.add("Phone");
products.add("TV");
products.add("Speaker");
products.add("Laptop");
return products;
}
public static void bannerPrinter() {
System.out.println();
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
}

You need to pass an ArrayList<String>. Looking at your code, you build one with productBuilder() which is otherwise unused. So:
ArrayList<String> products = productBuilder();
getOrder(products);
or
getOrder(productBuilder());
BTW, the following code:
if (products.contains(productName)) {
return true;
}
else {
return false;
}
is more easily written as
return products.contains(productName);

You would just pass an ArrayList. Like this:
ArrayList<String> lst = new ArrayList<String>();
lst.add("Phone");
lst.add("Laptop");
getOrder(lst);
You would fill your ArrayList first of course and then pass it.

Related

Java ArrayList add class object to list if object name is not already in the list?

I have looked through other questions but cant seem to find the answer I am looking for.
I am having trouble figuring out how to create a loop that adds a class object to an ArrayList only if it its name is not used in the list already.
This is the class I have.
package myPackage;
public class Cube {
private int length;
private String name;
public Cube(int initLength, String initName) {
this.length = initLength;
this.name = initName;
}
I would like to create new cubes and add them to a list. Here is the code I am trying to do this with.
In the while loop I can't figure out how to determine if the name has been used or not
package myPackage;
import java.util.ArrayList;
import java.util.Scanner;
public class PartFive {
public static void main(String[] args) {
ArrayList<Cube> cubelist = new ArrayList<>();
Cube oshea = new Cube (13, "oshea");
Cube mike = new Cube (7, "tony");
cubelist.add(oshea);
cubelist.add(mike);
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("enter cube name (blank quits): ");
String name = reader.nextLine();
if (name.equals("")){
break;
}
System.out.println("enter side length: ");
int length = Integer.valueOf(reader.nextLine());
Cube newcube = new Cube(length, name);
if(cubelist.contains(newcube.name)) {
// dont add to list
}
else {
cubelist.add(newcube);
}
}
reader.close();
System.out.println(cubelist);
}
}
Any constructive criticisms and suggestions are welcomed.
Replace
if(cubelist.contains(newcube.name)) {
dont add to list
}
else {
cubelist.add(newcube);
}
with
boolean found = false;
for(Cube cube: cubelist){
if(cube.getName().equals(name)) {
found = true;
break;
}
}
if(!found) {
cubelist.add(newcube);
}
The idea is to use a boolean variable to track if a cube with the same name as that of the input name already exists in the list. For this, iterate cubelist and if a cube with the same name as that of the input name is found, change the state of the boolean variable and break the loop. If the state of the boolean variable does not change throughout the loop, add the cube to the list.
From the code in your question:
if(cubelist.contains(newcube.name)) {
// don't add to list
}
else {
cubelist.add(newcube);
}
Method contains in class java.utilArrayList is the way to go but you need to be aware that method contains [eventually] calls method equals of its element type. In your case, the element type is Cube. Therefore you need to add a equals method to class Cube. I don't know what determines whether two Cube objects are equal, but I'll guess, according to your question, that they are equal if they have the same name, even when they have different lengths. I will further assume that name cannot be null. Based on those assumptions, here is a equals method. You should add this method to class Cube.
public boolean equals(Object obj) {
boolean areEqual = false;
if (this == obj) {
areEqual = true;
}
else {
if (obj instanceof Cube) {
Cube other = (Cube) obj;
areEqual = name.equals(other.name);
}
}
return areEqual;
}
Now, in method main of class PartFive you can use the following if to add a Cube to the list.
if (!cubelist.contains(newcube)) {
cubelist.add(newcube);
}
You can check for duplicate names in the cubelist array using lambda expressions (for better readability):
boolean isNameAlreadyExisting = cubelist.stream()
.anyMatch(cube -> cube.getName().equals(newcube.getName())); // this is returning true if any of the cubelist element's name is equal with the newcube's name, meaning that the name is already existing in the cubelist
if (!isNameAlreadyExisting) {
cubelist.add(newcube);
}
One thing that you should do is to remove the while(true) instruction which causes an infinite loop.
Another suggestion is to display the name of objects contained by cubelist, to see that indeed the names are not duplicated:
cubelist.stream()
.map(Cube::getName)
.forEach(System.out::println);

Searching an ArrayList for String Instance

I want to create a code that allows you to put in a word then it searches through the Arraylist, then it sends that code with the new airport codes. I can't figure out how to search through the ArrayList and then print certain letters. One of my friend suggested HashMap, but it only wants me to put in integers for the letters.
import java.util.*;
public class Alphabet {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Put in a word, the machine will then translate it to airport codes!");
String name = in.next();
List<String> name1 = new ArrayList<String>();
name1.add("Alpha");
name1.add("Bravo");
name1.add("Charlie");
name1.add("Delta");
name1.add("Echo");
name1.add("Foxtrot");
name1.add("Golf");
name1.add("Hotel");
name1.add("India");
name1.add("Juliet");
name1.add("Kilo");
name1.add("Lima");
name1.add("Mike");
name1.add("November");
name1.add("Oscar");
name1.add("Papa");
name1.add("Quebec");
name1.add("Romeo");
name1.add("Sierra");
name1.add("Tango");
name1.add("Uniform");
name1.add("Victor");
name1.add("Whiskey");
name1.add("X-Ray");
name1.add("Yankee");
name1.add("Zulu");
for (String string : name1) {
if(name.equals(name1)){
name1.equals(name1);
}
}
System.out.println(name1);
}
}
That was a simple mistake, you are iterating the list but you did not take the string value to check with your name
for (String string: name1) {
if(name.equals(string)){
//Your code
}
}
You can use the following code as well.
name1.forEach(string -> {
if (string.equals(name)) {
System.out.println("found");
} else System.out.println("Not found");
});

How to search in a list for a part of a string and print out the whole string?

I made a code which uses one input and store it in a genertic list and then I use another input to compare it with the first input ... If the first input is "Eric 1991" while the second input is just "Eric" so I want to print out all the sequence like this "Erik 1991" .. I used different ways to search in the namebirthday list , I used for loop then I used contains but they seeme do not work ,, Now I use toLowerCase().contains(x.toLowerCase()
I am getting error in eclipse in line of toLowerCase().contains(x.toLowerCase()
How can I correct that line to run the code???
package shapes;
import java.util.ArrayList;
import java.util.Scanner;
public class Base {
public static void main(String [] args) {
ArrayList<String> namebirthday = new ArrayList<String>();
Scanner sn = new Scanner(System.in);
String n=sn.nextLine();
// String k=sn.nextLine();
// String m=sn.nextLine();
namebirthday.add(n);
// namebirthday.add(k);
// namebirthday.add(m);
Scanner sb = new Scanner(System.in);
String x=sb.nextLine();
if (namebirthday.toLowerCase().contains(x.toLowerCase())){ // The method toLowerCase() is undefined for the type ArrayList<String>
System.out.println(namebirthday);
} else {
System.out.println("x" +"is not found" );
}
}
}
Acually I tried to put if (((String) namebirthday).toLowerCase().contains(x.toLowerCase())){ but eclipse says "Cannot cast from ArrayList to String- The method toLowerCase() is undefined for the type ArrayList"
What to do???
thanks
You have to use foreach to get the element form your lest and then do your comparison.
If you use namebirthday.contains then this will won't work for input is like "Eric".
See following code:
for(String currentString : namebirthday){
if (currentString.toLowerCase().contains(x.toLowerCase())){
System.out.println(currentString );
} else {
System.out.println("x" +"is not found" );
}
}
Cannot cast from ArrayList to String- The method toLowerCase() is
undefined for the type ArrayList
if (namebirthday.contains(x.toLowerCase())){
System.out.println(x);
} else {
System.out.println("x" +"is not found" );
}
}
You cannot use toLowerCase() in on a list. You have to implent yourself the contains method.
private static boolean containsIgnoreCase(List<String> nameBrithday, String s) {
for (String s1 : nameBrithday){
if ( s1.toLowerCase().contains(s.toLowerCase())){
return true;
}
}
return false;
}
You can't call toLowerCase() on the array, you have to call it on each of the members of the array:
boolean found = false;
for(String nm : namebirthday) {
if (nm.toLowerCase().contains(x.toLowerCase())) {
System.out.println(nm);
found = true;
// Add a break; here if you only care about the first match
}
}
if(!found) System.out.println("x" +"is not found" );
namebirthday is a List instance, not a String one. If you want to check something on content of this list, you need to get a single element that is a String. I am posting two examples how you can do it (the first one is probably more useful for you):
Check if the list contains the element
if (namebirthday.contains("Erik 1991")) {
// Do something
}
Iterate whole list and do the checking on each element
for (String element : namebirthday) {
if (element.equals("Erik 1991")) {
// Do something
}
}
Here is the fixed code
package shapes;
import java.util.ArrayList;
import java.util.Scanner;
public class Base {
public static void main(String [] args) {
ArrayList<String> namebirthday = new ArrayList<String>();
Scanner sn = new Scanner(System.in);
String n=sn.nextLine();
// String k=sn.nextLine();
// String m=sn.nextLine();
namebirthday.add(n);
// namebirthday.add(k);
// namebirthday.add(m);
Scanner sb = new Scanner(System.in);
String x=sb.nextLine();
for (String str : namebirthday){
if (str.toLowerCase().contains(x.toLowerCase())){
System.out.println(str);
} else {
System.out.println("x" +"is not found" );
}
}
}
}

How do you return an array object in java?

How do you return an array object in Java? I have an object that has an array in it and I want to work with it in my main class:
// code that does not work
class obj()
{
String[] name;
public obj()
{
name = new string[3];
for (int i = 0; i < 3; i++)
{
name[i] = scan.nextLine();
}
}
public String[] getName()
{
return name;
}
}
public class maincl
{
public static void main (String[] args)
{
obj one = new obj();
system.out.println(one.getName());
}
I am sorry if the answer is simple but I am teaching myself to code and I have no idea how you would do this.
You have to use the toString method.
System.out.println(Arrays.toString(one.getName()));
toString is a built-in function in Java (it might need library import; if you are using Netbeans, it will suggest it).
If the problem is to print it use
System.out.println(Arrays.toString(one.getName()));
//note System, not system
When you do getName() you are returning a reference to an array of strings, not the strings themselves. In order to access the individual strings entered, you can use the array index
String enteredName = name[index] format.
From your program, it looks like you want to print each item entered. For that, you could use a method like the following
public void printName() {
// for each item in the list of time
for(String enteredName : name) {
// print that entry
System.out.println(enteredName);
}
}

Searching a class array with multiple values per record

I need to search an object array for a Name and then print out all info corresponding to that name.
I have
public class AccessFriendlyFile {
private Friendlies[] fr = new Friendlies[100];
private int size = 0;
public AccessFriendlyFile (){
try {
Scanner scFile = new Scanner(new File("Friends.txt"));
String line, name, surname, cell, mail, landline;
while (scFile.hasNext()){
line = scFile.nextLine();
Scanner sc = new Scanner(line).useDelimiter("#");
name = sc.next();
surname = sc.next();
cell = sc.next();
if (sc.hasNext()){
mail = sc.next();
landline= sc.next();
fr[size] = new ExtendFriendlies(name, surname, cell, mail, landline);
}
else {
fr[size]= new Friendlies(name, surname, cell);
}
size++;
sc.close();
}
}catch (FileNotFoundException ex){
System.out.println("File not found");
}
How do I code a method that will search "fr" for a name and print out all corresponding info?
Many Thanks
Jesse
Edit:
Here is my Search method, that is currently not working.
public int Search(String name) {
int loop = 0;
int pos = -1;
boolean found = false;
while (found == false) {
if (fr[loop] == name) {
found = true;
pos = loop;
} else {
loop++;
}
}
return pos;
}
Incomparable types error on the if statement.
In your Friendlies class, have a method called getName() that will return the name of that Friendly. Iterate through the fr until you find the matching name. Once you've found that name, use similar get methods to print out all the information you want for the matching Friendly you just found.
I would suggest that you rename your variables here. The Friendlies class stores, I think, a single contact, a Friend. The list of Friend objects is an array that you might beter name friendList or even friendlies. I would also encourage you to not use size as a counter variable. Size is how many friends you have, and you can iterate through them using i, or friendCounter, or use a for each loop as I demonstrate below,
public Friendlies find(String name) {
for(Friendlies friend : fr) {
if(friend.getName().equalsIgnoreCase(name))
return fiend;
}
return null;
}
//now to print the info you can do this:
Friendlies findJoe = find("Joe");
if(findJoe==null)
System.out.println("You have no friends namd Joe.");
else
System.out.println(findJoe);
My code assumes that you implement toString() in Friendlies. If you use netbeans, you can auto-generate this code and then tweak it to get the format you want. (Just right-click where you want to write the method and choose insert code)
This should work:
public List<Friendlies> search(String name) {
List<Friendlies> list = new ArrayList<Friendlies>();
for(Friendlies friendlies : fr) {
if(friendlies.getName().equals(name)) {
list.add(friendlies);
}
}
return list;
}
Then, with the returned list, implement a nice display of the data :)
Assuming the AccessFriendlyFile loads the data into your array, you can use a for each loop, if you want to retieve all the matching names :
List<Friendlies> getByName(String searched){
List<Friendlies> result = new Arraylist<Friendlies>();
for (Friendlies currentFriendly : fr){
if (searched.equalsIgnoreCase(currentFriendly.getName()){
result.add(currentFriendly);
}
}
return result;
}
for only the first one :
Friendlies getByName(String searched){
for (Friendlies currentFriendly : fr){
if (searched.equalsIgnoreCase(currentFriendly.getName()){
return currentFriendly;
}
}
return null;
}
You should use lists instead of fixed arrays. If the files contains more than 100 records you'll get an indexoutofbounds exception.

Categories

Resources