Comparing ArrayList to String - java

//My problem is that in the method canceledOrder the string [] waitingList[] is not being seen at least that is what I think.
public static String[] canceledOrder(String[] waitingList,String[] waitingList1,String []waitingList2,String[] waitingList3){//I've decided to pass these string [] hoping the string from the other methods will now be seen in canceledOrder();
Scanner in = new Scanner (System.in);
int option;
System.out.println("Select the event you want to cancel :\n");
events();
option= in.nextInt();
in.nextLine();
System.out.println("Person on wait list is " + waitingList[name] );
switch (option){
case 1:
System.out.println("Please enter your name:\n");
canceledname = in.nextLine();
System.out.println("name:" + canceledname);
for (String s : myStringList) {
if(s.equals(canceledname)){
s = waitingList[name];
System.out.println("The new name is\n" + s);
name++;
}
return s; // I want it to now return waitingList[name]
}
break;

I may be wrong, but did you want to loop through the arraylist to see if any values in the list equal cancelledName?
If so, you may want something like this
for (String s : myStringList) {
if(s.equals(canceledname)){
k = waitingList[name];
System.out.println("The new name is" + k);
name++;
}
}
Edit: with possible solution to problem
// declare array of Attendees, capacity is 20
// I would rather use ArrayList, but it seems you're trying to use array
String attendees[] = new String[20];
// delcare wait list
String waitList[] = new String[2];
// declare int for tickets sold
int ticketsSold = 0;
// declare waitlist
int waitlistCount = 0;
// prompt buyers for purchase of tickets
// ticketsSold = ticketsSold + 1 or 2 depending on tickets
// if ticketsSold is 20 do not sell tickets and send to waiting list
// Do this until full
// if ticketsSold = 20
// prompt user to go on wait list
// if yes, ask how many tickets
// if tickets requested for waitlist exceeds current waitlist + tickets requested
// System.out.println("Sorry, waitlist is full");
// else prompt for user name
String name = in.nextLine();
waitlist[waitListCount] = name;
// here's the part I think you're having problems with
// if person is deleted from attendees
// get name of person not attending
int i = 0;
while (!cancelledName != attendees[i]) {
i++
}
// replace attendees index with waitlist Name
attendees[i] = waitlist[0];
// move the waitlist forward
waitlist[0] = waitlist[1];
waitlist[1] = null;
This is the best I can think of as far as logic. If you logic is sound and looks similar to mine, just focus on the bottom portion, where I think you're having the most problems

I guess you want to find out if canceledname exists in myStringList, for that you'll have to traverse myStringList - no way around it.
for(String name : myStringList){
if(name.equals(canceledname){
// continue...
k = waitingList[name];
System.out.println("The new name is" + k);
i++;
name++;
}
}
For that kind of comparison it would be better to save the names in a Set for example:
HashSet<String> names = new HashSet<String>();
// here you'll add the names to the hash-set
// using: names.add("whatever");
// ...
//and now:
if(names.get(canceledname) != null){
// continue ...
}

You cannot compare ArrayList to String, instead use contains method to find if element exists in the ArrayList.
boolean isElementExists = myStringList.contains(canceledname);
if(isElementExists) {
// other codes here
}
See the API: ArrayList#contains()

Related

Selecting randomly from a string array

I have run into a little problem. I have a homework exercise where i need to 'randomly' select a string from a string array. The goal of the exercise is to make a code which choses a random (inserted) name. My code:
public void run() {
int userSelection = -1;
int userAmount = 0;
String[] users = new String[userAmount];
int[] amountChosen = new int[userAmount];
while (userSelection != 0) {
drawMenu();
System.out.println();
//user selecting the menu choice
System.out.print("Make a selection from the menu: ");
userSelection = userInput();
System.out.println();
//forcing the user to give one of the allowed values
while (userSelection < 0 || userSelection > 4) {
System.out.print("That is invalid input. try again: ");
userSelection = userInput();
}
//adding users
if (userSelection == 1) {
System.out.print("How many users do we have?");
userAmount = userInput();
users = new String[userAmount];
amountChosen = new int[userAmount];
addUsers(users, userAmount); //returns user array with names
System.out.println();
}
//selecting random user
else if (userSelection == 2) {
int playerSelect = (int) (Math.random()*userAmount);
amountChosen[playerSelect]++;
System.out.println(users[playerSelect] + " was chosen!");
System.out.println();
}
//display the amount the users were chosen
else{
System.out.println("******** Turns ********");
for (int i = 0; i < userAmount; i++){
System.out.println("* " + "[" + amountChosen[i] + "] " + users[i]);
}
System.out.println("***********************");
System.out.println();
}
}
}
As you can see i now have a totally random userselection. For keeping tabs on how often a player is chosen i already made the 'int[] amountChosen' array. The goal is to "select a random player, also make it chose the player that is chosen the fewest times" so basicly it needs to select the string with the lowest amountChosen. (Also: I am aware my code may be a little bit messy and weird in some places. I just started learning java)
Thank you for response!
I won't give out the answer to your assignment. But, here is a naive implementation of what you are trying to achieve:
private void someMethod() {
String[] strArray = {"foo", "bar", "foobar"};
Random random = new Random();
System.out.println(strArray[random.nextInt(strArray.length)]);
}
Explanation:
You take a random number between 0 and the length of your string array using Random and then just use this as an index to query your string array.
If I understand correctly, you want to pick randomly one of all players having the lowest amount chosen?
Use a Map<String, Integer> with the amounts;
Filter the map with all players with the lowest amount;
Use Random.nextInt(amountOfLowest).
You could use Java Streams.
Hints: • use map.entrySet().stream() to stream over the map elements • use values(), unboxed() and min() to get the lowest value • use filter(), map() and collect() to collect a list of all players with the lowest amount • use List.get(new Random().nextInt(...)) to select a player.

How do I update a users input in an arraylist?

So I'm making a program for a car dealership as my final project for my class. At this time I'd say I'm about 75% done, but I am having trouble figuring out how to update the users input in an array list. So each array list slot contains the year, make, model, color, and mileage of a car. I can add a new car, I can remove a car, and I can quit my program. I have tried many things, I've read many papers, blogs, forums, and my book for class, but its always updating with the programmers input.
package carDealer;
import java.util.ArrayList;
import java.util.Scanner;
public class VehicleInformation {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<VehicleInventory> car = new ArrayList<VehicleInventory>();
String userInput = "-";
while (!userInput.equals("q")) {
System.out.println("Commands: 'a' to add, 'd' to delete, 'e' to edit, 'q' to quit");
userInput = scnr.next();
if (userInput.equals("a")) {
System.out.println("Year: ");
int year = scnr.nextInt();
System.out.println("Make: ");
String make = scnr.next();
System.out.println("Model: ");
String model = scnr.next();
System.out.println("Color: ");
String color = scnr.next();
System.out.println("Mileage: ");
int mileage = scnr.nextInt();
VehicleInventory userCar = new VehicleInventory();
userCar.setMake(make);
userCar.setModel(model);
userCar.setYear(year);
userCar.setColor(color);
userCar.setMileage(mileage);
userCar.print();
addCar(car, userCar);
}
if (userInput.equals("d")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.remove(userNum - 1);
System.out.println("count: " + car.size());
}
if (userInput.equals("e")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.get(userNum - 1);
You can just do a loop to look up for the car model the user wants to update (it can be any other attribute), and once found update it's value with the desired one:
String vehicleToLookUp = "golf"; // This will be received by user input
String vehicleNewName = "golf gti"; // This will be received by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.get(i).setSomeAttribute(...); // Set the desired attribute here
}
}
Or if you want to substitute the whole object...
String vehicleToLookUp = "golf"; // This will be received by user input
VehicleInventory newVehicle = new VehicleInventory(); // You will set the attributes by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.set(i, newVehicle ); // Create your object and pass it here
}
}
Also, instead of all those if, you could use if/else if or even a switch/case for better performance/readability (think that even if your logic is true for first if, it will check for all the other if you created, wasting time and processing power.

How do I go about allowing a user to input as many strings as they want while also checking it against an array?

I am doing this assignment for my CSCI 1301 class and i'm kinda stuck.
The assignment is to write a program that will provide a list of services to users and allow them to choose any or all services they would like and display the final price.
Here's my code so far,
public static void carMaintenance()
{
Scanner sc = new Scanner(System.in);
String makeOfCar;
System.out.println("What's the make of your car?");
makeOfCar = sc.next();
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Fluid Check"};
double[] prices = {39.99, 49.99, 19.99, 10.99};
System.out.println("What services whould you like for your "+makeOfCar+"?");
System.out.println(services[0]+", "+services[1]+", "+services[2]+", "+services[3]+".");
}
Where i'm stuck at is how would I go about allowing the user to request as many services they want?(Logically speaking, they can only request up to 4 services)
I figured I could use another array and put it in a "do-while" loop to achieve this but then, once I check it against the "services" array how would I assign a price to each service the user requested so that I can calculate the total price for all requested services?
any insight and help is greatly appreciated!
You could keep track of the sum in an extra variable. So your idea with the extra array to check for duplicates would still work. Check if the service is already chosen and if not, add the chosen index to the sum.
public static void carMaintenance() {
Scanner sc = new Scanner(System.in);
String makeOfCar;
System.out.println("What's the make of your car?");
makeOfCar = sc.nextLine();
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Fluid Check"};
double[] prices = {39.99, 49.99, 19.99, 10.99};
double sum = 0;
System.out.println("What services whould you like for your " + makeOfCar + "?");
System.out.println(services[0] + ", " + services[1] + ", " + services[2] + ", " + services[3] + ".");
String choice;
//This array simply tracks true or false for chosen/not chosen. boolean arrays are initialized with all values false.
boolean[] chosenServices = new boolean[services.length]; //Can only be as many elements as there are services. This way you don't have to change it when you add another service
do {
choice = sc.nextLine();
int choiceIndex = getIndex(services, choice);
if (choiceIndex < 0) break; //Choice doesn't exist. You will have to refine that and add messages
if (!chosenServices[choiceIndex]) { //service not yet chosen
chosenServices[choiceIndex] = true;
sum += prices[choiceIndex];
} else {
System.out.println("Was already chosen!");
}
} while (!choice.toLowerCase().equals("exit")); //Or something similar
System.out.printf("%.2f", sum); //Price with 2 digits
}
public static int getIndex(String[] arr, String search) {
for (int i=0; i<arr.length; i++) {
if (search.equals(arr[i]))
return i;
}
return -1;
}
As mentioned in one of the comments, this is only a rough implementation. You might want to do this with index input from the user, you might want to check for false inputs more precise than I did here etc. but that should do what I think you mean.

Perform in-order(alphabetical) add in java array of objects

I have the piece of code below which as it is, just adds the new element to the end but i want to be able to add each new element ordered in alphabetical order by the Destination name. Not sure if i would have to sort the list after addition or insert the new object by first checking and then adding it. In either case not sure how to go about doing it.
public void add()
{
int newRating =-1;
in = new Scanner(System.in);
if((lastElement+1) < MAX_ELEMENT) //MAX_ELEMENT =100
{
System.out.print("Enter the Name: ");
newDestination = in.nextLine();
System.out.print("Enter the type of Vacation(Single character code: ");
validCharacterCode();
while(newRating < MIN_RATING || newRating > MAX_RATING)
{
System.out.print("Enter the Rating(1-5): ");
newRating = in.nextInt();
}
lastElement++;
aDestination[lastElement] = new Destination(newDestination,newVacationType,newRating);
}
else
{
System.out.print("Cannot add new elements: ");
System.out.println("List already has " + MAX_ELEMENT + " elements.");
}
}
If you decide to use Arrays.sort, it should be along these lines (includes example of comparator function using a lambda expression):
public void add()
{
String newDestination;
int newRating =-1;
in = new Scanner(System.in);
if((lastElement+1) < MAX_ELEMENT) //MAX_ELEMENT =100
{
System.out.print("Enter the Name: ");
newDestination = in.nextLine();
System.out.print("Enter the type of Vacation(Single character code: ");
String newVacationType = in.nextLine();
while(newRating < MIN_RATING || newRating > MAX_RATING)
{
System.out.print("Enter the Rating(1-5): ");
newRating = in.nextInt();
}
lastElement++;
aDestination[lastElement] = new Destination(newDestination,newVacationType,newRating);
Arrays.sort(aDestination, 0, lastElement, (o1, o2) -> o1.destination.compareTo(o2.destination));
}
else
{
System.out.print("Cannot add new elements: ");
System.out.println("List already has " + MAX_ELEMENT + " elements.");
}
}
Adding a collection of objects in a specific order, that's what the PriorityQueue (Java Platform SE 7) is made for. It guarantees the order inside the queue. If you need to use an array at the end, you can always convert it back.
Use PriorityQueue<Destination> instead of Destination[]:
Comparator<Destination> byName = new Comparator<>(
{
#Override
public int compare(Destination d1, Destination d2)
{
return d1.getName().compareTo(d2.getName());
}
});
int initialCapacity = 10;
PriorityQueue<Destination> destinationsByName = new PriorityQueue<>(initialCapacity, byName);
Now, refactor your add() method. Use this priority queue for insertion without worrying the order since order is taken care by destinationsByName:
public void add()
{
int newRating = -1;
in = new Scanner(System.in);
if ((lastElement+1) < MAX_ELEMENT) //MAX_ELEMENT =100
{
...
Destination d = new Destination(...);
destinationsByName.add(d);
// no need to sort again
}
...
}
What if you need an array again? No problem, you can use the following method to convert it back:
destinationsByName.toArray(new Destination[0]);

How do I print the second method at the end of the user input? In java

1.The program works but it prints out the second method everytime after the user inputs, I don't want this and I don't understand how to change it?
import java.util.Scanner;//import scanner so user can input
class arrays
{
public static void main(String[] param)
{
String[] animals = arrays(); // creating string array to store information
forloop(animals);// passing the array to the method forloop
System.exit(0);
} //end main method
public static String[] arrays() //array method
{
String[] animals = new String[5]; //array to store 5 animals
animals[0] = "Komodo Dragon"; //animals stored
animals[1] = "Manatee";
animals[2] = "Kakapo";
animals[3] = "Florida Panther";
animals[4] = "White Rhino";
return animals;
}
public static void forloop(String[] animals) // here the array has been passed as an argument
{
int endangered = 20;
String answer = "";
for(int i = 0;i<5; i++) //for loop to print the below
//print 5 times using the different animal names.
{
System.out.println(animals[i] + ":");
System.out.println("How many are left in the wild?"); // prints the question
Scanner scanner = new Scanner(System.in); // allows the user to input
answer = scanner.nextLine();
int count = Integer.parseInt(answer);
if(count<=endangered) // if statement used to print out the smallest number types by the user
{
System.out.println("The most endangered animal is the " + animals[i] + "."); // prints out the most endangered animal
System.out.println("There are only " + answer + " left in the wild.");
}
print(animals, answer, i);
}
}
public static void print(String[]animals, String answer, int i)
{
System.out.println(answer + ", " + animals[0]);
}
}
2.I want the method above to only print after the user has inputted for all 5 questions. I want it to print out in a comma separated list form (Suitable for spreadsheet).
For example:
5000, Komodo Dragon - 5000 being the whatever the user inputs
8000, Manatee
91, Kakapo
100, Florida Panther
18, White Rhino
There are various ways. Easiest may be to append the input from the user to the String value in array
For eg. updating respective record with count from user such that:
animals[0] = "5000, Komodo Dragon";
This will require extra effort if you want to update the record later. You may use other data structures to
maintain the record like Maps which may even be simpler. However, one way to do would be two dimensional array such that you can think
it as of 5 x 2 tables.
Now, array initialization can be of two dimensional such that first column holds animals name and can leave empty for count
public static String[][] arrays() //array method
{
String[][] animals = new String[5][2]; //array to store 5 animals
animals[0][0] = "Komodo Dragon"; //animals stored
animals[1][0] = "Manatee";
animals[2][0] = "Kakapo";
animals[3][0] = "Florida Panther";
animals[4][0] = "White Rhino";
return animals;
}
The forloop method now has to update second column for each animals record so we can update it as follows:
public static void forloop(String[][] animals) // here the array has been passed as an argument
{
int endangered = 20;
String answer = "";
Scanner scanner = new Scanner(System.in); // allows the user to input
for(int i = 0;i<5; i++) //for loop to print the below
//print 5 times using the different animal names.
{
System.out.println(animals[i][0] + ":");
System.out.println("How many are left in the wild?"); // prints the question
answer = scanner.nextLine();
int count = Integer.parseInt(answer);
animals[i][1] = String.valueOf(count);
if(count<=endangered) // if statement used to print out the smallest number types by the user
{
System.out.println("The most endangered animal is the " + animals[i][0] + "."); // prints out the most endangered animal
System.out.println("There are only " + answer + " left in the wild.");
}
}
//close the scanner
scanner.close();
print(animals);
}
In the above method notice that, animals[i][1] = String.valueOf(count); updates second column for each row where row is given by i. And scanner has been taken to above of the loop since same instance can be used multiple times. Also, it has
been closed after the loop ends and the print method is taken out of loop and signature of the method is also changed since all we need is in the two dimensional array.
Now, as in general table we stored records in rows and columns so, we can iterate over the array to print our records. Thus, print method can be changed as follows:
public static void print(String[][]animals){
for (String[] animal: animals)
System.out.println(animal[1] + ", " + animal[0]);
}
Small change is required in main method since the array is now two dimensional.
Your print statement is inside your for loop. Maybe consider changing your print() to a save() and store each result in an array of answers that you can later print out all at once.
e.g.
results[i] = answer + ", " + animals[i];
instead of the system.out.println in your print method. At the end, you can loop through that and System.out.println(results[i]);

Categories

Resources