I am trying to write a program that mimics the actions of a vending machine for my CS class. I have a double array stock that represents the the number of items at a particular "slot" [my vending machine is weird and is kinda like one long vending machine with 1 column of different items]. Here is my code so far:
public class VendingMachine
{
// define fields here
public static double itemPrice[];
public static String[] itemName;
public static int stock[][];
public static int maxPerSlot;
public static double cashAmmount;
public VendingMachine(int numslots, int maxperslot, double cash)
{
final int numSlots = numslots;
maxPerSlot = maxperslot;
cashAmmount = cash;
stock = new int[numSlots][1];
itemPrice = new double[numSlots];
itemName = new String[numSlots];
// complete this method
}
public void setProduct(int slot, String product, double price)
{ int Slot = slot;
itemPrice[Slot] = price;
itemName[Slot] = product;
stock[Slot][0] = 0;
//
}
public void restockProduct(String product, int quantity)
{
String Product = product;
int Quantity = quantity;
for(int i = 0; i < itemName.length;i++){
if (Quantity > (maxPerSlot-stock[i][0])){
return;
}
if (Product.equals(itemName[i])&&Quantity < maxPerSlot){
stock[i][0] += Quantity;
}else if ((maxPerSlot-stock[i][0])==0){
continue;
}
}
//Put # of products in slot that holds it and if that slot is full put the rest in the next
//available slot that holds that product, if all full return error.
}
public double getCashOnHand()
{
return cashAmmount; // replace this line with your code
}
public int getQuantity(int slot)
{
return stock[slot][0]; // replace this line with your code
}
public int getQuantity(String product)
{ int total = 0;
for (int i = 0; i<itemName.length;i++){
if (product == itemName[i]){
total += this.getQuantity(i);
}
}
return total;
}
public boolean buyItem(int slot)
{ int snum = slot;
double price = 0;
if (stock[snum][0] != 0){
stock[snum][0]--;
price= itemPrice[snum];
cashAmmount += price;
return true;
} else {
return false;}
// replace this line with your code
}
}
and the main method that runs it:
public class vmd
{
public static void main(String[] args)
{
boolean success;
// vending machine w/ 20 slots, 10 items maximum per slot, $5 cash on hand
VendingMachine v = new VendingMachine(20, 10, 5.00);
v.setProduct(0, "Cheesy Poofs", 0.75);
v.setProduct(1, "Red Bull", 1.25);
v.setProduct(2, "Cheesy Poofs", 0.75);
v.restockProduct("Cheesy Poofs", 8);
v.restockProduct("Red Bull", 7);
v.restockProduct("Cheesy Poofs", 5); // 2 more go into slot 0, remaining 3 into slot 2
success = v.buyItem(0);
System.out.println(success); // should print "true"
System.out.println(v.getCashOnHand()); // should print "5.75"
System.out.println(v.getQuantity(2));// should print "9"
System.out.println(v.getQuantity("Cheesy Poofs")); // should print "12"
}
}
When I run this thought I consistently get:
true
5.75
8
15
as my out put when I am suppose to get:
true
5.75
9
12
as my output. Why is this? I am assuming it has something to do with the restockProduct() method but I can't seem to narrow it down and its really getting on my nerves. According to my CS teacher the restockProduct() method is suppose to add the given quantity of the specified product to the vending machine and Put as many of the items as possible into the first slot that has been designated to hold that particular kind of product (using setProduct()).
If not all of the items will fit into the first slot, put as many of the rest as possible into the second slot that holds that kind of product, etc. For partial credit, your method should at least be able to find the first slot designated for the specified product and put all of the items there".
You are right, restockProducts doesn't do what you want it to. Here's what you have:
public void restockProduct(String product, int quantity)
{
String Product = product;
int Quantity = quantity;
for(int i = 0; i < itemName.length;i++){
if (Quantity > (maxPerSlot-stock[i][0])){
return;
}
if (Product.equals(itemName[i])&&Quantity < maxPerSlot){
stock[i][0] += Quantity;
}else if ((maxPerSlot-stock[i][0])==0){
continue;
}
}
So when you restock "Cheesy Poofs", the first time, here's what happens:
On loop 0, you are Cheesy Poofs, so you put 8 items in there.
On loop 1, you have the wrong type, so nothing goes there
On loop 2, you have Cheesy Poofs, so you put 8 there.
Somehow, you need to remember that you've put 8 in the first slot. Also, you need to have a mechanism to put some into one slot, and some into another, right now I don't see that being possible in your code.
you have several problems in your restockProduct described by others, anyway you can change you restockProduct function to this one:
public void restockProduct(final String product, int quantity)
{
for (int i = 0; i < itemName.length; i++)
{
if ( (product.equals(itemName[i]) || "".equals(product) ) && (maxPerSlot - stock[i][0]) > 0)
{
stock[i][0] += quantity;
if (stock[i][0] > maxPerSlot)
{
quantity = stock[i][0] - maxPerSlot;
stock[i][0] = maxPerSlot;
}
else
return;
}
}
if (quantity > 0)
throw new IllegalArgumentException("Cannot stock product");
}
NOTE: we're either inserting product to slot where product already is OR where no products at all
NOTE2: after inserting we're checking is there any rest we should insert further or everything is here
Your problem is here:
for(int i = 0; i < itemName.length;i++){
if (Quantity > (maxPerSlot-stock[i][0])){
return;
}
Your first call to restock "Cheesy Poofs"
v.restockProduct("Cheesy Poofs", 8);
puts 8 items into the machine.
Your second call to restock cheesy poofs:
v.restockProduct("Cheesy Poofs", 5);
Fails to do anything. Your if statement says that if the quantity (5) is greater than maxPerSlot - current stock which is (10 - 8) or just 2, then return.
5 is greater than 2 so the method ends and nothing is added to your machine.
Additionally you need to put some sort of control in there to break out of the loop once you've added all 8 items to the machine. As it stands you're adding 8 cheesy poofs to two different slots. Once you add the 8 to the first Cheesy Poof row you should remove 8 from what you have left to stock.
I took the liberty of reconstructing that method and this is what I think you're trying to achieve:
public void restockProduct(String product, int quantity)
{
String Product = product;
int Quantity = quantity;
for(int i = 0; i < itemName.length;i++){
if (Product.equals(itemName[i])){
if (Quantity > (maxPerSlot-stock[i][0])){
Quantity -= maxPerSlot-stock[i][0];
stock[i][0] += maxPerSlot-stock[i][0];
}
if (Quantity <= (maxPerSlot-stock[i][0])){
stock[i][0] += Quantity;
return;
}
}
}
}
Related
I'm trying to make a simple billing system for a restaurant.
This shows the menu to the user and lets them choose, add an Item or quit.
In the end, it prints the bill.
The issue I'm facing is, I want the user to be able to add an item again with the item's number instead of overwriting the value.
Below code is my attempt which doesn't return anything.
public void addOrder(String meal, int quantity,
String[] dish, double[] cost) {
for (int i = 0; i < orderedFood.size(); i++) {
// look if food item already exists, update quantity of it by
// adding the previous value of the item to the new amount
if (orderedFood.get(i).contains(meal)) {
int oldQuantity = orderedQuantity.get(i);
orderedQuantity.set(i, oldQuantity + quantity);
break;
} else {
// if theres no item of this type yet, create a new one
orderedFood.add(meal);
orderedQuantity.add(quantity);
}
}
The code below shows how the food object gets created, and how the program works.
public static void Order() {
String[] dish = {"Sandwich", "Coffee", "Salad"};
double[] cost = {6.5, 3.2, 4.0};
for (int i = 0; i < dish.length; i++) {
System.out.println("\n" + dish[i] + ": " + cost[i] + "€.");
}
System.out.println("\nWhat would you like to order? \n\n");
Scanner myObj = new Scanner(System.in);
List<String> dishList = new ArrayList<>(Arrays.asList(dish));
// check if item exists
String menuItemTemp = myObj.nextLine();
String menuItem = "";
if (dishList.contains(menuItemTemp)) {
System.out.println("\nOkay.\n");
menuItem = menuItemTemp;
} else {
System.out.println("Error 404 Not Found.");
Order();
}
System.out.println("\nHow many? \n");
int userQuant = myObj.nextInt();
Bill myBill = new Bill();
myBill.addOrder(menuItem, userQuant, dish, cost);
System.out.println("\nOrder more? 1 - Yes. 2 - No. \n");
Scanner menuScan = new Scanner(System.in);
int menuScanner = menuScan.nextInt();
switch (menuScanner) {
// if another order is to be made
case 1:
System.out.println("\nOkay.");
Order();
break;
// output and end of program
case 2:
myBill.getOrder();
System.out.println(Math.round(myBill.getTotal() * 100.00) / 100.00 + "€\n");
System.out.println("\nThanks for ordering!\n");
// close scanners
menuScan.close();
myObj.close();
// end
System.exit(1);
}
Any nudge in the right direction would help a lot.
The error is the premature else. When not already present, you need to walk the entire for loop before knowing that there is no match.
If you do return instead of break you can treat the not-found case after the for.
public void addOrder(String meal, int quantity,
String[] dish, double[] cost) {
for (int i = 0; i < orderedFood.size(); i++) {
// look if food item already exists, update quantity of it by
// adding the previous value of the item to the new amount
if (orderedFood.get(i).contains(meal)) {
int oldQuantity = orderedQuantity.get(i);
orderedQuantity.set(i, oldQuantity + quantity);
return;
}
}
// if theres no item of this type yet, create a new one
orderedFood.add(meal);
orderedQuantity.add(quantity);
}
Of course
for
orderedFood.get(i).contains(meal)
int oldQuantity = orderedQuantity.get(i);
orderedQuantity.set(i, oldQuantity + quantity);
hints that an other data structure might be better:
Map<String, Integer> ordered = new HashMap<>(); // Meal to quantity.
public void addOrder(String meal, int quantity,
String[] dish, double[] cost) {
ordered.merge(meal, quantity, Integer::sum);
}
That is map the meal names to the total quantity. Indices are irrelevant.
Map.merge works as follows:
merge(K key, V value, (Value oldv, Value newv) -> resultv)
If newv is null, a remove is done.
Otherwise:
The lambda is called with an (possibly accumulating) old value, and the passed value.
if (oldv == null)
put(key, newv);
else
put(key, oldv + newv); // newv == value
Integer::sum is the same as (x, y) -> x + y.
So I would've left a comment if could've however I don't have enough reputation for that yet. I'm not sure what your myBill.getTotalOrder() function is. My first thought here without seeing more of your source code to understand your design would be to just make a Meal object that tracks its name, how much it is, and how many times it was ordered. Then during your getTotalOrder() you could just loop through each meal and add up the total.
The goal of my task is to generate a presents list(with a max amount price) with presents from another list. The max amount(totalePrijs) cannot exceed 500 AND you can't have the same present more than once in that generated list. The presents chosen are done with a random generator that goes up to 27(amount of presents).
It works perfectly except for the same present more than once part. Which I have yet to figure out. Either I was thinking of making an empty IntegerArray and checking if that Array contained x, if it did than it should restart from the beginning of the while statement otherwise it would add x to that array and continue.
The other way I thought off was changing the if statement to
if (selectedCadeauModel.contains(present.name) && totalePrijs + present.price < 500)
But that just made it loop infinitly I think.
This is the code that executes when clicking on the generate presents button.
selectedCadeauModel.clear();
double totalePrijs = 0;
while (totalePrijs < 500) {
NumberGen ran = new NumberGen();
int x = Integer.parseInt(ran.toString());
Cadeau present = (Cadeau) cadeauModel.elementAt(x);
if (totalePrijs + present.price < 500) {
totalePrijs += present.price;
selectedCadeauModel.addElement(new Cadeau(present.name, present.price));
} else {
break;
}
ftxTotaalPrijs.setValue(totalePrijs);
lstGeneratedPresents.setModel(selectedCadeauModel);
ftxGemiddeldePrijs.setValue(totalePrijs / selectedCadeauModel.size());
}
/
public class Cadeau {
String name;
double price;
public Cadeau(String naam, double prijs) {
name = naam;
price = prijs;
}
/
public class NumberGen {
Random randomGenerator = new Random();
int getal = randomGenerator.nextInt(27);
#Override
public String toString() {
return String.format("%d", getal);
}
}
I'm creating a scheduling and registration system for a class project. I'm required to be able to add and delete rooms and courses. Each course can only last an hour and may not happen at the same time as another course in the same room. I'm able to delete the course itself, but I'm having trouble deleting the time associated with that course.
What I've done is create an ArrayList of Rooms with each room being able to hold an ArrayList of Courses. Each of these courses has a specific hour which is checked if it's in use using an ArrayList of times. I was able to add the courses hour to the list and halt the user from creating another course with the exact time slot in the same room. However, whenever I remove the course I'm trying to remove the time as well so that another course that's created may use that time slot. Problem is, the time slot gets filled and stays filled even after removing the course and I'm not sure why.
Some guidelines:
Rooms can be added and deleted by the user. (To delete a room, no course should be scheduled in this room).
All courses can be deleted by the user.
The user can create courses by specifying a room number and the participants.
A room cannot hold more than one course at any one-hour slot.
To be honest I've been working for around 7 hours straight and I'm not to confident in my code, if I'm even doing things right, or even what I'm talking about really. I apologize if I'm not being specific enough or making any sense, please let me know if something needs clarification. If you have any other tips/pointers or see any other mistakes please let me know. Thanks in advance.
Course.java
package Schedule;
import java.util.ArrayList;
public class Course extends Room {
private String name;
private int roomNum, hour, students;
private static ArrayList < Course > courseList = new ArrayList < > ();
private static ArrayList < Integer > times = new ArrayList < > (24);
public Course() {}
public Course(String name, int hour, int roomNum, int students) { //Constructor
this.name = name;
if (hour > 7 && hour < 18) {
this.hour = hour;
} else {
System.out.println("Not a valid time slot. Time set to 6:00PM/1800 HOURS. ");
this.hour = 18;
}
this.students = students;
this.roomNum = roomNum;
boolean inUse = checkTime(hour, roomNum);
if (inUse == false) {
times.add(hour);
Room.addCourse(roomNum, this);
courseList.add(this);
}
}
public static void deleteCourse(int courseNum, int roomNum) {
boolean pass;
pass = Room.removeCourse(courseNum, roomNum);
if (pass == true) {
times.remove(courseNum);
courseList.remove(courseNum);
System.out.println("Course Removed ");
}
}
public static boolean checkTime(int hour, int roomNum) {
boolean exist = false;
for (int i = 0; i < courseList.size(); i++) {
if (courseList.get(i).hour == hour && courseList.get(i).roomNum == roomNum) {
exist = true;
System.out.println("Time already in use, course could not be added. ");
}
}
return exist;
}
}
Room.java
package Schedule;
import java.util.ArrayList;
public class Room {
private int number, numOfClasses;
private static int numOfRooms = 1000;
private static ArrayList < Room > roomList = new ArrayList < > ();
private ArrayList < Course > courseList = new ArrayList < > ();
public Room() {}
public Room(int number, int numOfClasses) { //Constructor
this.number = number;
this.numOfClasses = numOfClasses;
if (roomList.size() < numOfRooms) {
roomList.add(this);
System.out.println("Room added");
} else {
System.out.println("Room couldn't be added, not enough rooms available.");
}
}
public static void numOfRooms(int r) {
numOfRooms = r;
}
public static void deleteRoom(int roomNum) { //Delete room
boolean exist = false;
for (int i = 0; i < roomList.size(); i++) {
if (roomList.get(i).getRoomNum() == roomNum) {
if (roomList.get(i).courseList.size() > 0) {
System.out.printf("%s%d%s%n", "Cannot delete room ", roomNum, " " + "There is currently a course in the room. ");
} else {
roomList.remove(i);
System.out.printf("%s%d%s%n", "Room ", roomNum, " Deleted");
}
exist = true;
}
}
if (exist == false) {
System.out.printf("%s%d%s%n", "Room ", roomNum, " does not exist, could not delete.");
}
}
public int getRoomNum() {
return number;
}
public static ArrayList < Room > getRoomList() {
return roomList;
}
public static void addCourse(int roomNum, Course c) { //Add Course to room.
boolean empty = true;
for (int i = 0; i < roomList.size(); i++) {
if (roomList.get(i).getRoomNum() == roomNum) {
roomList.get(i).courseList.add(c);
System.out.printf("%s%d%n", "Course added to room ", roomNum);
empty = false;
}
}
if (empty == true) {
System.out.println("No rooms with that room number. ");
}
}
public static boolean removeCourse(int courseNum, int roomNum) {
boolean exist = false;
try {
for (int i = 0; i < roomList.size(); i++) {
if (roomList.get(i).getRoomNum() == roomNum) {
roomList.get(i).courseList.remove(courseNum);
exist = true;
}
}
if (exist == false) {
System.out.println("Could not find course to delete. ");
}
} catch (IndexOutOfBoundsException e) {
System.out.println("Error: Could not find a room or course to delete. ");
}
return exist;
}
}
ScheduleDemo.java
//For adding rooms, create a room object and input the room number and number of courses.
//For adding courses, create a course object and input the Name, hour1, room number, and # of students.
//For Deleting rooms, type Room.deleteRoom("room number").
//For Deleting Courses, type Course.deleteCourse("Course number", "Room Number").
package Schedule;
public class ScheduleDemo {
public static void main(String[] args) {
Room.numOfRooms(100);
Room room0 = new Room(0, 1);
Room room1 = new Room(3, 1);
Room room2 = new Room(99, 1);
Course course0 = new Course("Course", 9, 3, 10);
Course course1 = new Course("Course2", 9, 99, 12);
Course.deleteCourse(0, 99);
Course course2 = new Course("Help", 9, 99, 122);
Room.deleteRoom(56);
Room.deleteRoom(99);
Course.deleteCourse(1, 99);
}
}
Output:
Room added
Room added
Room added
Course added to room 3
Course added to room 99
Course Removed
Time already in use, course could not be added.
Room 56 does not exist, could not delete.
Room 99 Deleted
Could not find course to delete.
BUILD SUCCESSFUL (total time: 0 seconds)
UPDATE:
I managed to fix the issues by removing course and room number completely and instead passed the name of the course. Since I was passing in the index (courseNum) of each course, I ended up deleting the wrong course which is why my times didn't delete properly. By searching the name of the course in both my Course list and my room course list, I was able to accurately delete the right course from both list. Here's what I fixed.
Main
Course course1 = new Course("Course2", 9, 99, 12); //Creates Course2 and time slot
Course.deleteCourse("Course2"); //Deletes Course2 and time slot
Course course2 = new Course("Help", 9, 99, 122); //Adds course Help into same hour
/*
New Output
Course added to room 99
Course Removed
Course added to room 99
*/
Course
public static void deleteCourse(String name) {
boolean pass;
pass = Room.removeCourse(name);
if (pass == true) {
for (int i = 0; i < courseList.size(); i++) {
if (courseList.get(i).getName().equals(name)) {
times.clear();
courseList.remove(i);
System.out.println("Course Removed ");
}
}
}
}
public String getName() {
return name;
}
Room
public static boolean removeCourse(String name) {
boolean exist = false;
try {
for (int j = 0; j < roomList.size(); j++) {
for (int i = 0; i < roomList.get(j).courseList.size(); i++) {
if (roomList.get(j).courseList.get(i).getName().equals(name)) {
roomList.get(j).courseList.remove(i);
exist = true;
}
}
}
if (exist == false) {
System.out.println("Could not find course to delete. ");
}
} catch (IndexOutOfBoundsException e) {
System.out.println("Could not find a room or course to delete. ");
}
return exist;
}
Now I can move forward to other things. Thanks!
I think the main issue is you are deleting the CourseList using index. And I think you are assuming that RoomNum 99 is associated with course Num 0. In fact there is no concept of course number in your application. By default it becomes the index of the List.
private static ArrayList < Course > courseList = new ArrayList < > ();
courseList.add(object of type Course);
courseList.remove(courseNum); // Note course Num becomes an index here
So this removes the wrong entry. Course2 which is in Room number 99 still remains in the list thereby saying that the course is still running.
EDIT: This design is very confusing and will not work if you have to remember the relationship between course number and the course name. You have not modeled the relationship anywhere in your design.
When you declare something static it makes the member belong to the class instead of belonging to the instance. Therefore, let's look at your ArrayLists content when you're running the program.
Room room0 = new Room(0, 1);
Room room1 = new Room(3, 1);
Room room2 = new Room(99, 1);
Course course0 = new Course("Course", 9, 3, 10);
// courseList : {course0} | hours : {9}
Course course1 = new Course("Course2", 9, 99, 12);
// courseList : {course0,course1} | hours : {9,9}
Course.deleteCourse(0, 99);
// courseList : {course1} | hours : {9}
Since your Arraylist is static, your deleteCourse method doesn't delete the course 0 of the room 99. It removes the course1 from your Room courseList but not from the staticarray list !
I have a code that atm checks if the array list has reached the size or not, if no I want it to to perform checks before adding anything else to the list. I have attempted it but cannot figure out why it does not work. below is my method.
private static void addToArrayList(String fruit, double no1, int no2, int no3) throws Exception {
try {
if (arraysList.size() <= 5) {
int count = 0;
for (StoringArray item : arraysList)
if (item.equals("Apple")) {
++count;
if (count > 2)
throw new IllegalArgumentException( "You cannot add more than 2 apples." ); //Instead of this I want a Joption pane pop up to give this error if it applies, but at the moment I am not sure but this code with the current code I have is not working.
}
{
if ( arraysList.get( arraysList.size() - 1 ).equals("Banana") )
throw new IllegalArgumentException( "You have just added this please add something else and then add this if you want." ); }
arraysList.add(new StoringArray(fruit, no1, no2, no3));
}else{
JOptionPane.showMessageDialog(contentPane, "You cannot added mroe than 6 elements.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I want the error messages to appear in a Joption Pane and I want to check the following errors;
Say the list includes Apples, Bananas, Oranges, PineApples, Grapes
1; I want to check whether the user given parameters no1, no2 and no3 meet the conditon I want i.e.
for (StoreCommands item : commandsList)
if (item.equals("Apple")) {
}no1 need to be greater then 0, no2 needs to be less than 10 and no 3 needs to be less than 15.
2; If user tries to add two apples together in any order it should not be allowed, directly after one another.
3; If the user adds 2 Oranges, they should not be allowed and error message saying this should come up in JOption Pane message box.
If all the conditions are the array values get added to the array list. Thanks I hope I explained myself properly, I have been working on this problem for ages and cannot figure it out for some reason. Thanks again.
----------------edited-----------------with class that stores the arrayList.
public class StoreCommands {
public String toString(){
return Name + " " + Number1 + " " + Number2 + " " + Number3;
}
private String Name;
private int Number1;
private int Number2;
private int Number3;
public String getCommand() {
return Name;
}
public double getcommandNOS() {
return Number1;
}
public int getcommandVLW() {
return Number2;
}
public int getcommandVRW() {
return Number3;
}
public StoringArray(String fruitsNames, double fno1, int fno2, int fno3) throws Exception{
Name = fruitsNames;
Number1 = (int) fno1;
Number2 = fno1;
Number3 = fno3;
}
}
There are also some problems in your StoreCommands (?StoringArray) class and it doesn't compile.
1) The constructor is called StoringArray while the class is called StoreCommands.
2) You shouldn't accept a double value as second parameter and cast it to an int.
3) "Number2 = fno1;" inside the constructor should be "Number2 = fno2;" instead
4) You cannot compare your StoreCommands instance to a String value using equals. You need to compare to the String returned from the getCommand() method:
if (item.getCommand().equals("Apple"))
no1 need to be greater then 0, no2 needs to be less than 10 and no 3 needs to be less than 15. 2; If user tries to add two apples together in any order it should not be allowed, directly after one another. 3; If the user adds 2 Oranges, they should not be allowed and error message saying this should come up in JOption Pane message box.
perhaps something like this would do the job:
public static String getErrorMessage(List<StoreCommands> commands, String fruitsName, int no1, int no2, int no3) {
if (no1 <= 0 || no2 >= 10 || no3 >= 15) {
return "Some Error message...";
}
String previous = null;
int orangeCount = 0;
for (StoreCommands c : commands) {
if (fruitsName.equals("Apple") && previous != null && previous.equals("Apple")) {
return "Some Error message...";
} else if (c.getCommand().equals("Orange")) {
orangeCount++;
}
previous = c.getCommand();
}
return fruitsName.equals("Orange") && orangeCount == 1 ? "Some Error message" : null;
}
your class name is StoreCommands
but you have declared constructor named StoringArray
public StoringArray(String fruitsNames, double fno1, int fno2, int fno3) throws Exception
{
Name = fruitsNames;
Number1 = (int) fno1;
Number2 = fno1;
Number3 = fno3;
}
replace this by
public StoreCommands(String fruitsNames, double fno1, int fno2, int fno3) throws Exception
{
Name = fruitsNames;
Number1 = fno1; //you do not need to cast int because both are int
Number2 = fno1;
Number3 = fno3;
}
in for loop change the conditional logic
for (StoringArray item : arraysList)
if (item.getCommand().equals("Apple"))
{
}
.. it should works now if your other logic and code is ok
I am working on an algorithm, and I need to be able to pass in a List and see if there are four numbers in a row at any point in the list.
I have been struggling with an easy way to do this... Here is the basic idea.. I would like the fourNumbersInARow() method to return true:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Numbers {
/**
* #param args
*/
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>();
for(int i = 0; i<10; i++){
numbers.add((new Random().nextInt()));
}
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println(fourNumbersInARow());
}
private static boolean fourNumbersInARow() {
}
}
Use two variables: last_value and row_count. Going through the list one by one, always look whether the current value is exactly one bigger than the last_value; if yes, increase row_count, if no, reset it to 1. In any case, set last_value to the current value and loop. If at any point row_count becomes 4, return true. If you reach the end of the list, return false.
EDIT: changed counter range to start at 1
Here's an implementation in Java.
static boolean fourNumbersInARow(List<Integer> list) {
int last = 0xFACADE; // can be any number
int count = 0; // important!
for (int i : list) {
if (i == last + 1) {
if (++count == 4) return true;
} else {
count = 1;
}
last = i;
}
return false;
}
Unlike others, this resets the count of numbers in a row to 1 when the sequence is broken (because a number on its own is 1 number in a row). This allows for easier treatment of the first iteration where technically there is no previous number.
In pseudocode:
consecutiveCount = 1
lastNumber = firstElementInList(list)
for (number in list.fromSecondElement()):
if (number - lastNumber == 1):
consecutiveCount++
else:
consecutiveCount = 1
if (consecutiveCount == 4):
return true
lastNumber = number
return false
The bottom line is, you'll want to keep track of the last number in that was in the list, and compare it with the current number to see if the difference is 1. In order to remember the last number, a variable such as lastNumber is needed.
Then, in order to keep track of how many consecutive numbers there have been there should be a counter for that as well, which in the example about is the consecutiveCount.
When the condition where four consecutive numbers have occurred, then the method should return true.
This sounds a little like a homework question, so I don't want to write out a complete solution. But in your method just iterate through the list. Take the first number and see if the next number comes after the current, if so then set a variable flag with the start position and the current number, on the next iteration through the loop check to see if that value is before the previous the value etc... Once four in a row are found, break out of the loop and return true. If you encounter a number that is no chronologically correct then set a flag(start location) to null or negative and start the process over from the current location in the list.
Check this Code, this will return true if there a sequence of 4 numbers and else false otherwise
public class FindFourSequence {
public boolean isFourinRow(ArrayList seqList) {
boolean flag = false;
int tempValue = 0;
int tempValue2 = 0;
int tempValue3 = 0;
int tempValue4 = 0;
Iterator iter = seqList.iterator();
while(iter.hasNext()){
String s1 = (String)iter.next();
tempValue=Integer.valueOf(s1).intValue();
if(!(iter.hasNext())){
break;
}
String s2 = (String)iter.next();
tempValue2=Integer.valueOf(s2).intValue();
if(((tempValue2-tempValue)==1) || (tempValue-tempValue2)==1){
if(!(iter.hasNext())){
break;
}
String s3 = (String)iter.next();
tempValue3=Integer.valueOf(s3).intValue();
if((tempValue3-tempValue2)==1 || (tempValue2-tempValue3)==1){
if(!(iter.hasNext())){
break;
}
String s4 = (String)iter.next();
tempValue4=Integer.valueOf(s4).intValue();
if((tempValue3-tempValue4==1) || (tempValue4-tempValue3)==1){
flag = true;
return flag;
}
}
}
}
return flag;
}
public static void main(String[] args) throws Exception {
ArrayList aList = new ArrayList();
boolean flag = false;
FindFourSequence example = new FindFourSequence();
Random random = new Random();
for (int k = 0; k < 25; k++) {
int number = random.nextInt(20);
System.out.println(" the Number is :" + number);
aList.add("" + number);
}
/* aList.add("" + 1);
aList.add("" + 2);
aList.add("" + 3);
aList.add("" + 4);*/
flag = example.isFourinRow(aList);
System.out.println(" the result value is : " + flag);
}
}