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
}
Related
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
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 wanted to pass the "result" of "You Chose : abc" to a return type, so I can then pass it into my serialized method, so that I can then serialize that chosen team. I know how to return an array, but how would I return an array -1 ?
Code snippets are as follows :
public class Display{
public String[] printGreeting(int choice, String[] clubName) {
result = clubName;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (choice >= 1 && choice <= 20) {
System.out.println("You chose: " + clubName[choice - 1]); // return the clubName -1
}
return result; // how to declare return statement ?
}
}
Here is my serialize code, not sure how I would pass the array, via an alias or use object ?
public class Serialize
{
public void Serialize() // receive return type from printGreeting();
{
// how to put object info into files, rather than declare here ?
try
{
FileOutputStream fileOut = new FileOutputStream("/home/cg/root/club.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(club);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in C:/tmp/club.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}
Any help with this would be greatly appreciated :)
Here you declare to return an array of String[]:
public String[] printGreeting(int choice, String[] clubName) {
// ↑ here you say this method MUST return an array if Strings
What you need is
assign the user's choice to returned variable
return just ONE String
public String printGreeting(int choice, String[] clubName) {
result = clubName;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
if (choice >= 1 && choice <= 20) {
// assign choice to result
result = clubName[choice - 1];
// print choice
System.out.println("You chose: " + result); // return the clubName -1
}
// return the chosen club name
return result;
}
Actually, I don't know why result is a class attibute (but i cannot see declaration), what does not make much sense if you want to return it, I will code the method as:
public String printGreeting(int choice, String[] clubName) {
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); // ??
if (choice >= 1 && choice <= 20) {
choice --; // if choice is valid, get the array position.
// print choice
System.out.println("You chose: " + clubName[choice]);
return clubName[choice];
}
// if the choice is not correct, return null or "" as you want
return null;
}
UPDATE
Could anyone advise how I would pass that returned String to my serialize method, I think I know how to serialize it, but not 100% sure on parameter passing.
I don't get exactly what you want to achieve, maybe would be better to rephrase question with your target clear, and your tries.
Serialize (shortly), in Java is make an object's attributes convertible to Strings, then, a String either an String[] array does not need to be serialized.
As long as Display methods are not static, you must create an instance of Display to execute as follow:
public class Main {
public static void main(String [] args) {
// create an instance of Display class
Display d = new Display();
// get the needed values to pass to printGreeting method:
String[] clubs = {"club one", "club two" // put 20 clubs
// get the index from the user
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int choice = sc.nextInt();
// call the method and get the return:
String result = d.printGreeting(choice, clubs)
// then get a serializer and execute method:
Serialize s = new Serialize();
s.serialize(result);
}
}
change the method Serialize.serialize() to Serialize.serialize(String) as follows:
public class Serialize
{
public void serialize(String club)
// ↑ receive return type from printGreeting();
{
// your serialize code
}
}
What do you want to return? The club name (String) or the whole array?
It's not clear in your code if result is an array or a String, you simply say result = clubName. If it's an array it should be String[] result = clubName;, if you want to return a String it should be String result = clubName[choice -1];, in that case you have to change the method to public String printGreeting(int choice, String[] clubName) and you can return result;
I currently have a working GUI program that has a few buttons on it to simply step through my arraylist of items. These simply display the first, last or next and previous index results. This list has String, int and double inside of it. Now I have added a JTextField for input and a search button. My question is how do I get my search button to search through this array list? I was reading this answer but I don't understand the datum thing. Do I have to convert the entire arraylist to string before searching through it? Would something like
ArrayList<inventoryItem> inventory = new ArrayList<>(); ....
JTextField input = new JTextField(18); ...
JButton searchButton = new JButton("Search");
searchButton.setToolTipText("Search for entry");
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (String s : inventory) {
if (usrInput.contains(s)) {
inventory.get(currentIndex);
outputText.append(" somehow put whatever the index is equal to here");
}
}
}
});
The error I get is that inventoryItem cannot be converted to string. The second problem: I am having is how to I make it output everything in that index. For example my output looks like this:
class officeSupplyItem extends inventoryItem {
public officeSupplyItem(String itemName, int itemNumber, int inStock, double unitPrice) {
super(itemName, itemNumber, inStock, unitPrice);
}
#Override
public void output(JTextArea outputText) {
outputText.setText("Item Name = " + itemName + " \n"); //print out the item name
outputText.append("Item Number = " + itemNumber + " \n"); //print out the item number
outputText.append("In Stock = " + inStock + " \n"); //print out how many of the item are in stock
outputText.append("Item Price = $" + formatted.format(unitPrice) + " \n"); //print out the price per item
outputText.append("Restocking fee is $" + formatted.format(restockingFee) + " per item \n");
outputText.append("Value of item inventory = $" + formatted.format(value) + " \n"); //print out the value of the item inventory
outputText.append("Cost of inventory w/restocking fee = $" + formatted.format(inventoryValue) + " \n"); //print out the total cost of inventory with restocking fee
}
}
I would also like to understand what the datum portion of the mentioned link means.
I am not quite clear on what you mean by "This list has String, int and double inside of it".
You are comparing an object field with the text entered. You need not convert InventoryItem to a string. What you need to do is identify which fields you want to compare and use them in the comparison.
From what I see the text being entered to the JTextField is the search criteria for your code. If I assume it to be itemName, your code should be as follows :
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (InventoryItem s : inventory) {
if (usrInput.equalsIgnoreCase(s.getItemName())) {
//you can call output string here
outputText.append(" somehow put whatever the index is equal to here");
}
}
}
});
This is for the case if the JTextField input is the itemName. If this is any different than you expect, please comment.
From the link you shared, the difference is that his List contains only Strings, that is why "datum" is a String. This cannot be used for your case.
Hope this helps!
As per my understanding, what ever the searchText is (itemName or itemNumber) the results should be listed. Therefore, you could write a search method that compares and returns whether it matches the search string as follows in the InventoryItem class.
public boolean isSearchTextAvailable(String searchText) {
if (this.itemName.equals(searchText)) {
return true;
} else {
try {
int no = Integer.parseInt(searchText);
if (this.itemNumber == no) {
return true;
}
} catch (NumberFormatException e) {
System.out.println("Not a integer");
}
}
return false;
}
You can enhance this method to any number of fields you want to be searched within.
Then use this method in the action for the searchButton.
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (InventoryItem invItem : inventory) {
if (invItem.isSearchTextAvailable(usrInput)) {
invItem.output(outputText);
}
}
}
});
You have to make input (JTextField) a field in this class to make it work.
Few tips to increase quality of your code:
Separate InventoryItem and OfficeSupplyItem classes to different files
Notice the naming convention for class names is PascalCase
Better to have JavaGUIFixed class extended from JFrame and all its components defined as fields and not local variables since you use them in various other methods other than makeWindow() method where you actually create the JFrame
Do not use invItem.output(outputText) type of methods, where you pass a JTextField to a object Method to write to it. What you could do instead is write a method like getOutputString() in InventoryItem class which will return a formatted string of what needs to be printed and then call outputText.setText(invItem.getOutputString()) - Your implementation is restricting you to have all classes as inner classes to JavaGUIFixed.
Hope this helps!
Your enhanced for loop is saying for each String element s in ArrayList inventory... But inventory is declared to be an ArrayList of inventoryItem objects, not a list of strings, and the for loop isn't accessing the variables where the values you are trying to search are stored, as each index of inventory is just storing a reference to an object.
If your main goal is taking input, storing, sorting, and outputting it, you might consider taking and storing it as strings in a string collection. You can always parse to int or double if you need to at some point, but it will be easier to sort and search with a homogenous data type.
Where I saw datum used in that link was just as a variable name, the same way you used 's' in your code.
I have marked #maheeka 's response as the answer. I however had to modify his code because of the way that I had previously written my program. It now looks as follows:
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (int i = 0; i < inventory.size(); i++) {
if (usrInput.equalsIgnoreCase(inventory.get(i).getItemName())) {
currentIndex = i;
displayItem(outputText);
I also had to set up my getter on the itemName as I apparently had forgotten that part. Thank you #Aadi Droid for that.
I have a program that allows the user to choose between a binary search tree a splay tree and a red black tree. I wrote the class for the binary search tree and now im working on the splay tree but ive realized that my method that interacts with the user only works with the binary search tree. I set it up so that it will create an instance of whichever tree the user selects but down in my code I use only the variable that would be created if the user selected a binary search tree. My question is how can i make it so that I will only create an instance of the tree that the user selected and how can i use only one variable so that when i insert items or work on the tree i dont have to add more conditional statements for different trees?
this is what i have now
import java.util.Scanner;
import java.lang.Math.*;
public class Driver1
{
public static void main(String[] args)
{
//local variables
String treeChoice = null;
String choice = null;
String choice2 = null;
String command = null;
int insertAmount = -1;
String pattern;
int height = -1;
int i = -1;
//BST<Integer> myTree = null;
//ST<Integer> mySTTree = null;
int num = 0;
//Scanners to take user input
Scanner input = new Scanner(System.in);
Scanner inputt = new Scanner(System.in);
System.out.println("Which tree would you like to test (BST, ST, RBT)? ");
treeChoice = input.nextLine();
//Based on user input either a BST, Splay Tree, or RBT will be initialized.
if("BST".equalsIgnoreCase(treeChoice))
{
BST<Integer> myTree = new BST<Integer>();
}
else if("ST".equalsIgnoreCase(treeChoice))
{
//System.out.println("Splay Tree not ready yet");
ST<Integer> mySTTree = new ST<Integer>();
}
else if("RBT".equalsIgnoreCase(treeChoice))
{
System.out.println("RBT not ready yet");
//RBT<Integer> myTree = new RBT<Integer>();
}
else
{
System.out.println("Invalid Entry");
}
//Ask user how many items to input
System.out.println("How many items would you like to insert? ");
insertAmount = input.nextInt();
//ask user if the items will be random or sorted
System.out.println("Pattern (random or sorted): ");
choice2 = inputt.nextLine();
//If random, create random numbers
if("random".equalsIgnoreCase(choice2))
{
for(i = 1; i <= insertAmount; i++)
{
myTree.insert((int)(Math.random()*1000000)+i);
}
}
//else fill the tree with numbers in order from 1 to the user limit
else if("sorted".equalsIgnoreCase(choice2))
{
for(i = 1; i <= insertAmount; i++)
{
myTree.insert(i);
}
}
//Keep asking users input on what to do to the tree until user says quit
while(command != "quit")
{
System.out.println(
"Next command (insert X, delete X, find X, height, quit)?");
command = inputt.nextLine();
if (command.startsWith("insert"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.insert(num);
if(result == false)
{
System.out.println("Item already present.");
}
}
else if(command.startsWith("delete"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.delete(num);
}
else if(command.startsWith("find"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.find(num);
if(result == true)
{
System.out.println("Item present.");
}
else
{
System.out.println("Item not present.");
}
}
else if(command.startsWith("height"))
{
System.out.println("Current height of tree " + myTree.height());
}
else if(command.startsWith("quit"))
{
break;
}
System.out.println();
}
}//Close main method
as you can see I fill only myTree which would be the tree created if the user selected bst. and in the while loop i only work on myTree.
How can i make this more generic or my other idea was to take the users input and then create the instance of that tree and then pass the instance into a seperate method so that i could still use only myTree since it would refer to the instance that was passed into that method but im not sure how to pass an instance into another method. This way seems like the best but im not sure
any help is appreciated
Your trees should extend a common base class, or better, a implement common interface, say Tree, that specifies the methods to be used on all trees (find, insert, delete). Then you should have only one variable Tree myTree to which you assign an actual instance of the type the user selects.
Are you sure your above code works, however? If you do this
if("BST".equalsIgnoreCase(treeChoice))
{
BST<Integer> myTree = new BST<Integer>();
}
then the variable myTree will be unavailable after the } because the code block in which it is declared ends there. You can declare a variable at one point and assign a value to it later, like so:
Tree<Integer> myTree;
if("BST".equalsIgnoreCase(treeChoice)) {
myTree = new BinarySearchTree<Integer>();
} else if("ST".equalsIgnoreCase(treeChoice)) {
myTree = new SplayTree<Integer>();
} else if("RBT".equalsIgnoreCase(treeChoice)) {
myTree = new RedBlackTree<Integer>();
} else {
throw new IllegalArgumentException(treeChoice + " is not a valid input");
}
I very much recommend that you give your classes real names that make obvious what they represent, not just two or three letter combinations. Note that if you do not throw an exception in the last else branch, the compiler will later complain that "the variable myTree may not have been initialized".
Alternatively, you could put all your code after the tree creation if-else-statements into a method, say <T> void testTree(Tree<T> myTree) and call this method directly where you evaluate the user input, e.g. if("BST".equalsIgnoreCase(treeChoice)) testTree(new BinarySearchTree<Integer>());, but at some you will want to assign it to a variable anyway.