I have a task where I need to create a program for "TotalCompetitions", which consists of multiple "Competition". I need to create an application which allows user to do various options related to TotalCompetition.
If the first option ("Create a new competition") is selected, by typing "1" and then pressing Enter,
the program should call the addNewCompetition method of the TotalCompetitions class to add
a new competition with a given name. After creating a new competition, the program should goes
back to the main menu.
The second option is to add entries to the competition. However, when I try to call the addEntry() method located in the Competition class to the newly created competition, it doesn't work as it is still of TotalCompetitions type. How can I access the newly created competition to access the required method?
At the moment, this is my code:
public class TotalCompetitions {
private ArrayList<Competition> competitions;
public TotalCompetitions() {
this.competitions = new ArrayList<Competition>();
}
public ArrayList<Competition> getCompetitions() {
return competitions;
}
public void setCompetitions(ArrayList<Competition> competitions) {
this.competitions = competitions;
}
public Competition addNewCompetition(String name, int id) {
Competition newCompetition = new Competition(name, id);
return newCompetition;
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
TotalCompetitions sc = new TotalCompetitions();
int competitionId = 0;
while (true) {
System.out.println("Please select an option. Type 5 to exit.");
System.out.println("1. Create a new competition");
System.out.println("2. Add new entries");
System.out.println("3. Draw winners");
System.out.println("4. Get a summary report");
System.out.println("5. Exit");
String command = keyboard.next();
if (command.equals("1")) {
keyboard.nextLine();
System.out.println("Competition name:");
String name = keyboard.nextLine();
competitionId += 1;
sc.addNewCompetition(name, competitionId);
System.out.println("A new competition has been created!");
System.out.println("Competition ID: " + competitionId + ", Competition Name: " + name);
}
else if (command.equals("2")) {
sc.addEntry();
}
else if (command.equals("5")) {
System.out.println("The end");
break;
}
}
sc.addNewCompetition(name, competitionId); returns a new object of the type Competition, however, this new object is not used by your program. The variable sc is still of the type TotalCompetition which is not related to the type Competition. Furthermore, your method addNewCompetition(String id, int id) does not add the new Object to the ArrayList. The solution would be to store the object which is returned by the sc.addNewCompetition(...) call and call addEntry() on this object.
Related
I doing a bigger school project (first part of basic objective programming in java - so not touched extended, polyphorism etc yet, thats next part), but run in to a small problem and tried for couple of days to find solution (thru books and internet). I constructed different ArrayLists in one class and different classes (at least two) should get access to them.
public class Customer
{
public void subMenuCustomer()
{
............code............
int subMenuCust;
ServiceLogic addCustomer = new ServiceLogic();
ServiceLogic listAllCustomers = new ServiceLogic();
while(true)
{
System.out.println("Please Choose your preference: ");
System.out.println("Create account, press \"1\": ");
System.out.println("Get list of clustomers, press \"2\": ");
System.out.println("Log out, press \"0\": ";
subMenuCust = input.nextInt();
switch(subMenuCust)
{
case 1 ://Call method createCustomer in class ServiceTech to add new customers
addCustomer.createCustomer(name, lastname, ssNo);
break;
case 3
listAllCustomers.getCustomer();
............more code..............
}
}
When user has added details (social secuity number, name and lastname) it is stored in seperate ArrayList. These three ArrayList are added(merge/concat) together to a fourth ArayList, listCustomer , so that all elements from the three ArrayList end up in same index [101 -54 Clark Kent, 242-42 Linus Thorvalds, ...].
import java.util.ArrayList;
import java.util.Scanner;
public class ServiceLogic
{
//Create new ArrayLists of Strings
private ArrayList<String> listSSNoCustomers = new ArrayList<>();
private ArrayList<String> listNameCustomers = new ArrayList<>();
private ArrayList<String> listLastnameCustomers = new ArrayList<>();
private ArrayList<String> listCustomers;
Scanner input = new Scanner(System.in);
public boolean createCustomer(String name, String lastname, String ssNo) //
{
System.out.println("Write social security number; ");
ssNo = input.next();
//loop to check that it is a uniq social security number
for(String ssNumber : listSSNoCustomers)
{
if (ssNumber.equals(ssNo))
{
System.out.println("This customer already exist. Must be uniq social security number.");
return true;
}
}
//If social security number is not on list, add it
//and continue add first name and surname
listSSNoCustomers.add(ssNo);
System.out.println(ssNo);
System.out.println("Write firstname; ");
name = input.next();
listNameCustomers.add(name);
System.out.println(name);
System.out.println("Write lastnamame; ");
surname = input.next();
listSurnameCustomers.add(lastname);
System.out.println(lastname);
return false;
}
public void setListCustomer(ArrayList<String> listCustomers)
{
this.listCustomers = listCustomers;
}
public ArrayList<String> getCustomer()
{
//ArrayList<String> listCustomers = new ArrayList<>();
for(int i = 0; i <listSSNoCustomers.size(); i++)
{
listCustomers.add(listSSNoCustomers.get(i) + " " + listNameCustomers.get(i) + " " + listFirstnameCustomers.get(i));
}
System.out.println("customer" + listCustomers);
return listCustomers;
}
}
According to the specification we got, when user want to see list of all customer the outputs should be in format [666-66 Bruce Wayne, 242-42 Linus Thorvalds, ...].
When user (staff) choose to enter details in class Customer ( Case 1 ) it works and elements get stored in the Arraylists for social security numbers, name and lastname (have checked that) .
The problem: when I run I can add customers, but when I try to get a list of customer the output: [] . I tried different solution, but same output only empty between the brackets.
So the question, how do I get ouput to work when user choose case 2 to get a list of all cutomers?
I am testing a class that has a list items in it. The values are getting inserted via scanner from user input. I want to test the list just before the add method to check if there's null values. I am providing you what I've done so far. I am completely new to Spock and Groovy.
CLASS TO BE TESTED
package inventory;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Menu {
static Scanner scanner = new Scanner(System.in);
static ArrayList<Item> items = new ArrayList<>();
public static void printMenu(String[] options) {
for (String option : options) {
System.out.println(option);
}
System.out.print("Choose your option : ");
}
private static final String[] options = {
"1- Adding an Item ",
"2- Create and Print the Json file of Items",
"3- Create and Print the Html file of Items",
"4- Create and Print the Xml file of Items",
"5- Create and Print the Csv file of Items",
"6- Exit"
};
public static void addingItemsFromUserInput() {
int option = 1;
while (option != 7) {
printMenu(options);
try {
option = scanner.nextInt();
switch (option) {
case 1:
System.out.print("Please enter the Name of the Item: ");
String name = scanner.next();
System.out.print("Please enter the Serial Number of the Item: ");
String serialNumber = scanner.next();
System.out.println("Please enter the Item Value");
BigDecimal amount = scanner.nextBigDecimal();
Item item = new Item(name, serialNumber, amount);
addingAnItem(item);
break;
case 2:
TrackingFile tFileJson = new JsonFile(items);
tFileJson.createTheFile();
tFileJson.writingTheFile();
break;
case 3:
TrackingFile tFileHtml = new HtmlFile(items);
tFileHtml.createTheFile();
tFileHtml.writingTheFile();
break;
case 4:
TrackingFile tFileXml = new XmlFile(items);
tFileXml.createTheFile();
tFileXml.writingTheFile();
break;
case 5:
TrackingFile tFileCsv = new CsvFile(items);
tFileCsv.createTheFile();
break;
case 6:
scanner.close();
System.out.println("Have A Nice Day!");
return;
}
} catch (Exception ex) {
System.out.println("Please enter an integer value between 1 and " + options.length);
scanner.next();
}
}
}
// Options
public static void addingAnItem(Item item) {
items.add(item);
}
public List<Item> getItems() throws RuntimeException {
if (items.contains(null)){
throw new RuntimeException("Name cannot be null");
}
return items;
}
}
ACTUAL TEST
def "cannot save if name is null"(){
given:
Menu menu = new Menu()
menu.items.contains(null)
when:
menu.getItems()
then:
RuntimeException e = thrown()
e.message == "Name cannot be null"
}
I am receiving the following stack trace. Can please someone help me, to overcome this.
Expected exception of type 'java.lang.RuntimeException', but no exception was thrown
Expected exception of type 'java.lang.RuntimeException', but no exception was thrown
at org.spockframework.lang.SpecInternals.checkExceptionThrown(SpecInternals.java:81)
at org.spockframework.lang.SpecInternals.thrownImpl(SpecInternals.java:64)
at inventory.MenuSpec.cannot save if name is null(MenuSpec.groovy:55)
given:
Menu menu = new Menu()
menu.items.contains(null)
contains does not modify the list and simply returns true/false. The return value is never used.
You really want to add the item to the list, not check if it is there (it isn't, you have never added it):
given:
Menu menu = new Menu()
menu.items.add(null)
Somehow I try to make a user selection of which cook has to prepare the food. I already created the variable whichcook and place that where cook1 used to stay. But I don't know how to carry on. I want to let the user select between either "Jan de Vries" or "SinBad" to prepare. So the methode deliverer.delivered(whichcook, customer); carries on with the selected name. I figure if have to use instanceof I guess, but don't know how to really do that. I know how to make a user-input and cases etc that's not the problem. It's more about how to isolate the right instance!!
Someone a key suggestion???
java
package KebabStore;
public class DamascusKebab
{
public static int cooksnumber;
public static int deliverersnumber;
#SuppressWarnings("unused")
public static void main(String[] args)
{
Cook cook1 = new Cook ("Jan de Vries", "Butcherknife 1", "1212-IS", "Allahmelo", 123456);
Cook cook2 = new Cook ("Sinbad", "Camelhumb 2","2323-IS", "Halal-lem", 654321);
Deliverer deliverer1 = new Deliverer ("Ali Baba", "Helmgras 11", "3434-JH", "Ji-Hattem",456789);
Deliverer deliverer2 = new Deliverer ("Muammar", "Zadeldreef 22", "4545-JH", "Moskemenade", 987654);
Customer customer = new Customer ("Piet Hein", "Klantlaan 25", "5656-KL", "Darmstadt");
cooksnumber = Cook.numberofcooks;
deliverersnumber = Deliverer.numberofdeliverers;
Cook whichcook = cook1;
deliverer.delivered(whichcook, customer);
}
}
How are going to get the user input?
if it's from the Scanner
Cook whichcook;
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt()
if (choice == 1)
whichcook = cook1;
else
whichcook = cook2;
deliverer.delivered(whichcook, customer);
The exercise is, to create an arraylist for a class, where a User can enter "Guestnumber" + "Guestname" + "Guestemail".
In the menu you could remove an existing "Guest" with all the Information. Thats the code for it: (it works)
public void gastAendern() {
System.out.println("Guestnumber to delete:");
Scanner sc = new Scanner(System.in);
String input = sc.next();
for (Gast test : verwaltungG) {
int nummer = Integer.parseInt(input);
if (test.getgNr() == nummer) {
verwaltungG.remove(test);
a = 1;
break;
}
}
if(a==0) {
System.out.println("Guestnumber is not used");
verwaltungG is the ArrayList
Gast is the class for get+set
But now I got a problem to change an existing Guest, like for example:
I ask to type in the Guestnumber OR the Guestname OR the Guestmail to change it (I have to do it for all 3). So I have really no idea how to change it. I looked through Stackoverflow, google etc. but it only shows how to change them with List.set, but I don't know if it works with my kind of Problem, because I don't know how to use it.
You can do something similar as you are doing for delete, instead of remove - you need to change the details you need update :
System.out.println("Guestnumber to update :");
Scanner sc = new Scanner(System.in);
String input = sc.next();
for (Gast test : verwaltungG) {
int nummer = Integer.parseInt(input);
if (test.getgNr() == nummer) {
System.out.println("Enter new guest name for guest number : "+nummer );
String name = sc.nextLine();
System.out.println("Enter new guest email for guest number : "+nummer );
String email = sc.nextLine();
// now update the details
test.setName(name);
test.setEmail(email);
break;
}
}
I have a version of a login for an employee system i would like to make, I have a for loop which should go through the entire list of Accounts, then see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!! What am i doing wrong? Also my list contains Employees and Managers which inherit from Account, the if statement uses the getName in Account to compare if it equals to the user input. Sorry if this is ridiculously stupid/bad! thanks.
List <Account> Accounts = new LinkedList<Account>();
Here is where i populate my Account, the main method calls this and the list() is called whihc contains the problematic loop
public void add() {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
problem:
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
}
}
System.out.println("Employee does not exist!");
login();
}
I am doing the print statement in the for loop to see what it is findng, and unfortunalty it is only the first account
EDIT: I have included more code here, my after my initial if statement i want to check if the code the user enters is also correct.
see if the name of an employee matches one in the list then the if
statement continues, further questions asked etc... it seems to only
iterate once and then stop as it will only find the first user and
tell me the other accounts do not exisit, even though they do!!
If it works for one employee and tells that others don't exist then your for loop does not iterate once.
The output you get is exactly what the code looks like. You get username once then try to match the same name with every employee in the list. If the names are equal you ask for password, otherwise you print out that employee doesn't exist. Everything right as it is in the code. You should add to your question the expected behaviour so I, or someone else can fix your code without guessing the purpose of your methods.
Here's one of those guesses:
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
userFound = true;
break;
}
}
}
if(userFound) {
login();
} else {
System.out.println("User not found.");
}
This is a possible solution that doesn't use your Account class (since I do not know what it looks like) and instead uses a Map:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = input.nextLine();
boolean found = false;
Map<String, String> accounts = new HashMap<String, String>();
accounts.put("Geoff", "password1");
accounts.put("Bob", "password2");
accounts.put("John", "password3");
Set<String> names = accounts.keySet();
for (String a : names)
{
if (!a.equals(empName))
{
continue;
}
found = true;
// three tries to login
boolean success = false;
for(int i = 0; i < 3; i++)
{
System.out.println("Please enter your passcode: ");
String code = input.nextLine();
if (accounts.get(a).equals(code))
{
System.out.println("logged in");
success = true;
}
else
{
System.out.println("Wrong password... try again");
}
}
if(!success)
{
System.out.println("User failed to authenticate after 3 attempts. User has been locked out!");
}
}
if(!found)
{
System.out.println("Employee does not exist!");
}
}
Since I do not know what the login() method does, I just simply added that into the code. This solution iterates three times in an attempt to get the correct password. If that fails, a message is displayed.