Hello we are developing a Quiz game in Java.In our project we use Hashmap that consist of countries and their details.Each time in the loop we want to get three random countries with a random method, and we want User to answer questions related to that random country.Everytime user answers the questions related to the country we get another random country from hashmap.But we don't want these three random countries to be the same.How can we avoid that?
import java.util.HashMap;
import java.util.Random;
public class Countries {
private HashMap<String, String[]> countrieseasy;
private HashMap<String, String[]> countriesmedium;
private HashMap<String, String[]> countrieshard;
private String previousEasyCountry;
private String secondPreviousEasyCountry;
private String previousMediumCountry;
private String secondPreviousMediumCountry;
private String previousHardCountry;
private String secondPreviousHardCountry;
private Random random;
public Countries() {
countrieseasy = new HashMap<>();
countriesmedium = new HashMap<>(); // create a new HashMap object
countrieshard = new HashMap<>();
previousEasyCountry = null;
secondPreviousEasyCountry = null;
previousMediumCountry = null;
secondPreviousMediumCountry = null;
previousHardCountry = null;
secondPreviousHardCountry = null;
random = new Random();
}
public void addCountryeasy(String name, String capital, String language, String continent, String currency) {
String[] details = {name, capital, language, continent, currency};
countrieseasy.put(name, details);
}
public void addCountrymedium(String name, String capital, String language, String continent, String currency) {
String[] details = {name, capital, language, continent, currency};
countriesmedium.put(name, details);
}
public void addCountryhard(String name, String capital, String language, String continent, String currency) {
String[] details = {name, capital, language, continent, currency};
countrieshard.put(name, details);
}
public String[] getCountryeasyDetails(String name) {
return countrieseasy.get(name);
}
public String[] getCountrymediumDetails(String name) {
return countriesmedium.get(name);
}
public String[] getCountryhardDetails(String name) {
return countrieshard.get(name);
}
private String getRandomCountryName(HashMap<String, String[]> countries, String previousCountry, String secondPreviousCountry) {
Object[] countryNames = countries.keySet().toArray();
int randomIndex = random.nextInt(countryNames.length);
String countryName = (String) countryNames[randomIndex];
while (countryName.equals(previousCountry) || ( countryName.equals(secondPreviousCountry)) || (secondPreviousCountry != null && secondPreviousCountry.equals(previousCountry))) {
randomIndex = random.nextInt(countryNames.length);
countryName = (String) countryNames[randomIndex];
}
return countryName;
}
public String getRandomCountryeasyName() {
String secondPreviousCountry = previousEasyCountry;
previousEasyCountry = secondPreviousEasyCountry;
secondPreviousEasyCountry = secondPreviousCountry;
String countryName = getRandomCountryName(countrieseasy, previousEasyCountry, secondPreviousEasyCountry);
return countryName;
}
public String getRandomCountrymediumName() {
String secondPreviousCountry = previousMediumCountry;
previousMediumCountry = secondPreviousMediumCountry;
secondPreviousMediumCountry = secondPreviousCountry;
String countryName = getRandomCountryName(countriesmedium, previousEasyCountry, secondPreviousEasyCountry);
return countryName;
}
public String getRandomCountryhardName() {
String secondPreviousCountry = previousMediumCountry;
previousHardCountry = secondPreviousHardCountry;
secondPreviousHardCountry = secondPreviousCountry;
String countryName = getRandomCountryName(countriesmedium, previousEasyCountry, secondPreviousEasyCountry);
return countryName;
}
}
So here is our code we tried to give each country a string value previousName , and ckecked if it is equal to the next random country we get from hashmap but it didn't work.
Related
When I run this code, it gives an error saying cannot involve get__() on the array type Book[].. In the main method, I have a book array with the information from a text file -- title, isbn, price, qty, forsale.
public static int searchByTitleOrISBN(Book[] b)
{
int i = 0;
// print a message "Enter the Title or ISBN of the book: "
System.out.println("Enter the Title or ISBN of the book: ");
String input = scan.next();
// use a while loop to search through the array books using a counter and as long as no match is found
while (i < b.length) {
// if there's a match for the title or a match for the isbn and the book quantity > 0 and the book is for sale
if ((b.getTitle().equals(title) || b.getISBN().equals(isbn)) & b.getQty() > 0 && b.isForSale()) {
Basically what you want is to search the entire list.If you want to keep up your present implementation, then the solution given by #Jens works.
But If you go by searching one by one it would be O(n) but if you leverage inbuilt HashMaps you can do it with O(1) using hashCode and equals and no need of looping through all the objects for each and every search.
the Book class which keeps the data of the book. hashCode and equals is implemented here.
public final class Book{
private final String title;
private final String isbn;
private double price;
private int quantity;
private boolean forSale;
public final Key key;
public Book(String title, String isbn, double price, int quantity,boolean forSale){
this.title = title;
this.isbn = isbn;
this.price = price;
this.quantity =quantity;
this.forSale = forSale;
this.key = makeKey(title,isbn);
}
private static Key makeKey(String title,String isbn) {
return new Key(title,isbn);
}
public Key getKey() {
return this.key;
}
public String getTitle(){
return this.title;
}
public String getISBN(){
return this.isbn;
}
#Override
public final String toString(){
String s = this.title +"; "+ this.isbn+ "; "+this.price+"; "+this.quantity;
return s;
}
public static final class Key{
private final String title;
private final String isbn;
private Key(String title,String isbn) {
this.title = title;
this.isbn = isbn;
}
private String getTitle() {
return this.title;
}
private String getISBN() {
return this.isbn;
}
//calculates the hash of the entry, if we don't override this it will
//use the hash of the reference. so we need to change it for comparision
#Override
public final int hashCode(){
return this.title.hashCode()+this.isbn.hashCode();
}
//if two components have same hash code, then we can use extra criterion
//to check if the two objects are same. in the book case the hash is
//unique.since we are using the title and the isbn;
#Override
public final boolean equals(Object obj){
if(this==obj){
return true;
}
if(obj!=null && this.getClass()==obj.getClass()){
Key tempObj = (Key)obj;
return (this.title == tempObj.getTitle()) && (this.isbn == tempObj.getISBN());
}
return false;
}
}
}
BookMap class which stores all the book objects in form of Map<Book.Key,Book>. This will help with the easy retrival of book data.
public final class BookMap{
private final Map<Book.Key,Book> map;
private final String name;
public BookMap(String name){
this.name = name;
this.map = new HashMap<>();
}
public final String getName(){
return this.name;
}
public final Map<Book.Key,Book> getMap(){
return Collections.unmodifiableMap(this.map);
}
public final void addBook(Book book){
this.map.put(book.getKey(),book);
}
public final Book getBook(Book book){
Book.Key tempKey = book.getKey();
return this.map.get(tempKey);
}
public final boolean findBook(Book book){
if(book != null) {
return this.map.containsKey(book.getKey());
}
return false;
}
#Override
public final String toString() {
String s ="Books list : \n";
for(Map.Entry<Book.Key,Book> b:this.map.entrySet()) {
s= s+b.getValue()+"\n";
}
return s;
}
}
Now a sample Main.js with static main method to retrieve the book list.
public class Main {
public static BookMap list = new BookSet("General list");
public static void main(String[] args) {
Book temp = new Book("Journey to the center of the earth","isbn-001-002-0455",9.99,15,false);
list.addBook(temp);
temp = new Book("The Time Machine","isbn-001-002-0456",9.99,15,false);
list.addBook(temp);
temp = new Book("The War of the Worlds","isbn-001-002-0457",8.99,15,false);
list.addBook(temp);
temp = new Book("Brave New World","isbn-001-002-0458",11.99,15,false);
list.addBook(temp);
temp = new Book("Ninteen Eighty-four","isbn-001-002-0459",19.99,15,false);
list.addBook(temp);
temp = new Book("Ray Bradbury","isbn-001-002-0460",14.99,15,false);
list.addBook(temp);
temp = new Book("I, Robot","isbn-001-002-0461",12.99,15,false);
list.addBook(temp);
temp = new Book("Foundation","isbn-001-002-0462",12.99,15,false);
list.addBook(temp);
temp = new Book("The Martial Chronicles","isbn-001-002-0463",3.99,15,false);
list.addBook(temp);
temp = new Book("Fahrenheit 451","isbn-001-002-0464",6.99,15,false);
list.addBook(temp);
//testing with the book already in the list;
temp = new Book("Fahrenheit 451","isbn-001-002-0464",0,0,false);
//prints book detail
System.out.println(list.getBook(temp));
//testing with the book already in the list;
temp = new Book("I am not in the list","isbn-001-002-0464",0,0,false);
//prints null as the book is not in the list
System.out.println(list.getBook(temp));
System.out.println(list);
}
}
The above is a rough idea, you can develop more on it, i have used final for classes in order to prevent subclassing, as it would become complex with inheritence to understand and debug.i like avoiding complexity as much as i can. If some common pattern is there, then i will try to use abstract classes.
You have to acces an element in your loop not the array itself:
while (i < b.length) {
// if there's a match for the title or a match for the isbn and the book quantity > 0 and the book is for sale
if ((b[i].getTitle().equals(title) || b[i].getISBN().equals(isbn)) & b[i].getQty() > 0 && b[i].isForSale()) {
The Tableview does not completely output data from the sql table, although there are no errors. That is, the problem is that the program outputs only part of the data, although there are some in the sheet itself
SQL query class (sqlworker)
public List<String> gettableManagmet() throws SQLException {
resSet = statmt.executeQuery("PRAGMA TABLE_INFO('Users');");
List<String> ls = new ArrayList<>();
while (resSet.next()) {
ls.add(resSet.getString("name"));
}
System.out.println(ls);
return ls;
}
public ObservableList<Users> getdatausermanagment() throws SQLException {
ObservableList<Users> res = FXCollections.observableArrayList();
resSet = statmt.executeQuery("SELECT * FROM Users");
while (resSet.next()) {
String id = String.valueOf(resSet.getInt("id"));
String Login = resSet.getString("Login");
String Pass = resSet.getString("Pass");
String Otel = resSet.getString("Otel");
String isManager = String.valueOf(resSet.getInt("isManager"));
String isAdmin = String.valueOf(resSet.getInt("isAdmin"));
String isBlocked = String.valueOf(resSet.getInt("isBlocked"));
String CauseBlocking = resSet.getString("CauseBlocking");
System.out.println(id+ Login+Pass+Otel+isManager+isAdmin+isAdmin+CauseBlocking);
res.add(new Users(id,Login,Pass,Otel,isManager,isAdmin,isBlocked,CauseBlocking));
}
for(Users s : res){
System.out.println(s);
}
return res;
}
public void adddata(TableView table) throws SQLException {
ObservableList<Users> res = FXCollections.observableArrayList();
resSet = statmt.executeQuery("SELECT * FROM Users");
while (resSet.next()) {
String id = String.valueOf(resSet.getInt("id"));
String Login = resSet.getString("Login");
String Pass = resSet.getString("Pass");
String Otel = resSet.getString("Otel");
String isManager = String.valueOf(resSet.getInt("isManager"));
String isAdmin = String.valueOf(resSet.getInt("isAdmin"));
String isBlocked = String.valueOf(resSet.getInt("isBlocked"));
String CauseBlocking = resSet.getString("CauseBlocking");
System.out.println(id+ Login+Pass+Otel+isManager+isAdmin+isAdmin+isBlocked+CauseBlocking);
table.getItems().add(new Users(id,Login,Pass,Otel,isManager,isAdmin,isBlocked,CauseBlocking));
}
}
Users class
private final String id;
private final String login;
private final String pass;
private final String otel;
private SimpleStringProperty isManager;
private final String isAdmin;
private final String isBlocked;
private final String causeBloocking;
public Users(String id, String login, String pass, String otel, String isManager, String isAdmin, String isBlocked, String causeBlocking) {
this.id = id;
this.login = login;
this.pass = pass;
this.otel = otel;
this.isManager = new SimpleStringProperty(isManager);
this.isAdmin = isAdmin;
this.isBlocked = isBlocked;
this.causeBloocking = causeBlocking;
}
public String getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPass() {
return pass;
}
public String getOtel() {
return otel;
}
public String getisManager() {
return isManager.get();
}
public String getisAdmin() {
return isAdmin;
}
public String getisBlocked() {
return isBlocked;
}
public String getCauseBloocking() {
return causeBloocking;
}
Class where i parse data
public TableView table;
#Override
public void initialize(URL location, ResourceBundle resources) {
SQLWorker sqlWorker = new SQLWorker();
table.setEditable(true);
try {
for (String s: sqlWorker.gettableManagmet()) {
TableColumn<Users, String> tb = new TableColumn<>(s);
tb.setCellValueFactory(new PropertyValueFactory<>(s));
tb.setCellFactory(TextFieldTableCell.forTableColumn());
tb.setVisible(true);
table.getColumns().addAll(tb);
System.out.println(tb.getProperties());
}
System.out.println(table.getColumns().size());
sqlWorker.adddata(table);
} catch (SQLException e) {
e.printStackTrace();
}
}
fxml file
enter image description here
when programme in work
enter image description here
sql database enter image description here
The issues here are
you do not adhere to the Java naming conventions for 3 of your getters; PropertyValueFactory relies on those: the property passed to the constructor is modified by converting the first letter to upper case and then PropertyValueFactory checks for methods with that modified name prefixed with get or is. It e.g. looks for getIsManager() or isIsManager() not for getisManager(). (Note that this is much easier to read btw.)
There's a typo in one of your getter (and the corresponding field) names: It should be getCauseBlocking(), not getCauseBloocking()
I have defined 3 methods in which there are String[] as parameters. I would like to set these ones from another function, with some strings, and printing each one.
When I try to call these methods from another function(the start() function), to set the values of String[] parameters Eclipse says:
Type mismatch: cannot convert from String
to String[]
public class logistics2 {
private static String plane;
private static String truck;
private static String airport[];
private static String loc[];
private static String city[];
private static String pack[];
public static void at_obj_place(String object, String[] place) {
object = truck;
object = plane;
place = loc;
place = city;
place = airport;
return;
}
public static void in_pk_vehicle(String[] Pack, String vehicle) {
Pack = pack;
vehicle = truck;
vehicle = plane;
return;
}
public static void in_city(String[] place, String[] City ) {
place = loc;
City = city;
return;
}
public static void start() {
// HERE I RECEIVE THE ERROR MESSAGE
in_city(airport = "cdg", city = "paris");
in_city(airport = "lhr", city = "london");
in_city(loc = "north", city = "paris");
in_city(loc = "south",city = "paris");
at_obj_place(plane = "plane", airport = "lhr");
at_obj_place(truck = "truck", airport = "cdg");
at_obj_place(pack1 = "p1", airport = "lhr");
at_obj_place(pack2 = "p2", airport = "lhr");
for(int i = 0; i < airport[].length(); ) {
System.out.println(airport + " " + city);
}
return;
I would like to print each of the values that I have set with the for condition, based on the count of the values number that I have inserted in the String[]
In all the methods you have to passed strings you have to pass array of strings. Like this for all arrays:
airport[0] = "cdg";
airport[1] = "lhr";
city[0] = "paris";
city[1] = "london";
then pass this to methods like:
in_city(airport,city);
And in for loop you have to mention only array name like airport not airport[] and add increment for i.
{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111}
{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111}
Now I want to convert the above JSON into my POJO instances that maps to each part of the String. Suppose the POJO is called userList. Then I need to split up the JSON String to 2 userListObjects.
Your Pojo class will look like:
public class userList{
private String countryName;
private String countryCode;
private Long phoneNo;
private Integer campaignId;
//Getters,Setters
}
You can also use this_link to generate pojo just by copying and pasting your json.
Use the following snippet to generate the list.
JsonParser jsonParser = new JsonParser();
String jsonData = "[{\"countryName\":\"USA\",\"countryCode\":\"+41\",\"phoneNo\":4427564321,\"campaignId\":111},{\"countryName\":\"USA\",\"countryCode\":\"+41\",\"phoneNo\":4427564321,\"campaignId\":111}]";
JsonElement parsedJsonElement = jsonParser.parse(jsonData);
if(parsedJsonElement.isJsonArray()){
JsonArray parsedJsonArray = parsedJsonElement.getAsJsonArray();
List<User> userList = new ArrayList<User>();
for(JsonElement jsonElement : parsedJsonArray){
String countryName = "";
String countryCode = "";
long phoneNo = 0;
int campaignId = 0;
Iterator<Entry<String, JsonElement>> iterator = jsonElement.getAsJsonObject().entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JsonElement> next = iterator.next();
String key = next.getKey();
if(key.equals("countryName")){
countryName = next.getValue().getAsString();
}else if(key.equals("countryCode")){
countryCode = next.getValue().getAsString();
}else if(key.equals("phoneNo")){
phoneNo = next.getValue().getAsLong();
}else if(key.equals("campaignId")){
phoneNo = next.getValue().getAsInt();
}
}
userList.add(new User(countryName, countryCode, phoneNo, campaignId));
}
}
public class User {
String countryName;
String countryCode;
long phoneNo;
int campaignId;
public User(String countryName, String countryCode, long phoneNo, int campaignId) {
super();
this.countryName = countryName;
this.countryCode = countryCode;
this.phoneNo = phoneNo;
this.campaignId = campaignId;
}
}
I know this question is kind of repetitive But still I can't get an answer.
I have 2 arraylists containing name and description respectively as
final ArrayList<String> arrayOne = new ArrayList<String>(); // containing names
final ArrayList<String> arraytwo = new ArrayList<String>(); // containing description
I need a view like
I have tried
arraytwo.add(arrayOne);
&
arrayThree.addAll(arrayOne);
arrayThree.addAll(arrayTwo);
But can't a desired arraylist.
Regards
POJO class
public class Model
{
String name;
String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
desc = desc;
}
}
For Storing to arraylist
ArrayList<Model> arrayModel = new ArrayList<Model>();
for(int i=0;i<arrayOne.size();i++)
{
Model model=new Model();
model.setName(arrayOne.get(i));
model.setDesc(arrayTwo.get(i));
arrayModel.add(model);
}
If you don't want to create POJO, try this:
List<String> nameList;
List<String> desList;
//for storing
Map<String, String> map = new HashMap<>();
for(int i=0;i<nameList.size();i++) {
map.put(nameList.get(i), desList.get(i));
}
//for retrieving
for(Map.Entry<String, String> m : map.entrySet())
String nameListItem = m.getKey();
String desListItem = m.getValue();
}