How to call a string array into a method - java

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.

Related

Random string generator gets the same result in Java

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.

How can i put an Arraylist into Arraylist

i have an exercise which i must write a programm in which i manage the timetable of trains.I write all the programm put i can not write the main class, because i must make an Arraylist with 3 passengers and i dont know what i must put in the blank
Code:
public class Route {
private int id;
private int aeroplane;
private String departure;
private String arrival;
private ArrayList<Ticket> Tickets = new ArrayList<>() ;
public Route(){
id = 0 ;
aeroplane = 0 ;
departure = " ";
arrival = " ";
Tickets = new ArrayList<>();
}
public Route(int ID, int aerop, String depar,String arriv,ArrayList<Ticket> tick ){
id=ID;
aeroplane=aerop;
departure=depar;
arrival=arriv;
Tickets=tick;
}
public static void main(String[] args) {
ArrayList <Train> train=new ArrayList<>();
Route d1= new Route(0051,50,"Greece","Italy",);// what i have to write in the last blank?
}}
I suppose you have those three classes:
Train
Ticket - which is valid for multiple trains
Route - which could contain multiple Tickets
Then you should model your Route like that:
public class Route {
private final int id;
private final int aeroplane;
private final String departure;
private final String arrival;
private final List<Ticket> tickets;
public Route(int id, int aeroplane, String departure, String arrival, List<Ticket> tickets) {
this.id = id;
this.aeroplane = aeroplane;
this.departure = departure;
this.arrival = arrival;
this.tickets = tickets;
}
}
Your route class does not have, and should not have a list of lists of trains. It is perfectly fine, that you have it has a list of tickets.
To the question of how to add the list of Trains to the Route instantiation, you should create a ticket first, or multiple if you like.
public static void main(String[] args) {
// create trains
Train train1 = new Train(1202, "Piraeus", "Athens");
Train train2 = new Train(1302, "Athens", "Thessaloniki");
Train train3 = new Train(1502, "Thessaloniki", "Rome");
// create ticket(s)
Ticket ticket = new Ticket(95, List.of(train1, train2, train3));
// create route and pass tickets
Route myRoute = new Route(0051, 50, "Greece", "Italy", List.of(ticket));
}
To create the lists here I used the factory method java.util.List.of (available since Java 9). Your route class is also a good candidate for a record (since Java 18). As an record it would look like:
public record RouteRecord(int id, int aeroplane, String departure, String arrival, List<Ticket> tickets) {}
Also, think about the concept of immutability.
In your main method ( it's not a class ) :
List<Ticket> tickets = new ArrayList<>();
tickets.add( new Ticket());
Route d1 = new Route(0051,50,"Greece","Italy",tickets);
and as it was mentined before you need to define a constructor :
public Route(int id, int aeroplane, String departure, String arrival, List<Ticket> tickets ){
this.id = id;
this.aeroplane = aeroplane;
this.departure = departure;
this.arrival = arrival;
this.Tickets = tickets;
}

Java - Enumeration as Optional

My program works if I initialize my Enum Cities as null but I want it to be Optional. I can make it Optional but then the class Address which is supposed to take Cities as one of it's parameters won't do so because Cities is not defined as Optional in the class Address but I can't change it so that the Optional is the parameter of this class and that it works
This is my enum class
public enum Cities {
NEWYORK("New York",10000),
LOSANGELES("Los Angeles",90000),
CHICAGO("Chicago",60000),
NEWORELANS("NEW Orlans",70000),
DALLAS("Dallas",75000);
private final String name;
private final Integer postalCode;
Cities(String name, Integer postalCode) {
this.name=name;
this.postalCode=postalCode;
}
It works like this
private static Address addressInput (Scanner scanner) {
ArrayList<Cities> cityList = new ArrayList<>();
Cities city = null;
do {
for (Cities cities : Cities.values()) {
System.out.println(cities);
cityList.add(cities);
}
String cityInput = dataInput(scanner, "Type in the name of one of the cities: ");
for (int j = 0; j < cityList.size(); j++) {
if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
city = cityList.get(j);
}
}
if (city == null) {
System.out.println("Please select one of the cities on the list.");
}
} while (city == null);
String street = dataInput(scanner, "Name of the street: ");
String houseNumber = dataInput(scanner, "House number: ");
return new Address.Builder(city)
.atStreet(street)
.atHouseNumber(houseNumber)
.build();
}
But Adress constructor now won't accept city if it's Optional because it is defined differently in Adress class
private static Address addressInput (Scanner scanner) {
ArrayList<Cities> cityList = new ArrayList<>();
Optional<Cities> city = Optional.empty();
do {
for (Cities cities : Cities.values()) {
System.out.println(cities);
cityList.add(cities);
}
String cityInput = dataInput(scanner, "Unesite naziv jednog od ponuđenih gradova: ");
for (int j = 0; j < cityList.size(); j++) {
if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
city = Optional.ofNullable(cityList.get(j));
}
}
if (city.isEmpty()) {
System.out.println("Molimo odabrati jedan od ponuđenih gradova.");
}
} while (city.isEmpty());
public class Address {
private String street;
private String houseNumber;
private Cities city;
public Address(Cities city,String street, String houseNumber) {
this.street = street;
this.houseNumber = houseNumber;
this.city=city;
}
public static class Builder {
Cities city;
String street;
String houseNumber;
public Builder (Cities city){
this.city=city;
}
public Builder atStreet (String street){
this.street=street;
return this;
}
public Builder atHouseNumber (String houseNumber){
this.houseNumber=houseNumber;
return this;
}
public Address build (){
Address address = new Address();
address.city=city;
address.houseNumber=houseNumber;
address.street=street;
return address;
}
}
How to edit class to accept Optional?
Using Optional here is probably not the best idea as other have mentioned in the comments above, but if you really wish as it's for learning purposes you can do something like this:
ArrayList<Cities> cityList = new ArrayList<>();
Optional<Cities> city = Optional.empty();
do {
for (Cities cities : Cities.values()) {
System.out.println(cities);
cityList.add(cities);
}
String cityInput = dataInput(scanner, "Type in the name of one of the cities: ");
for (int j = 0; j < cityList.size(); j++) {
if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
city = Optional.ofNullable(cityList.get(j));
}
}
if (!city.isPresent()) {
System.out.println("Please select one of the cities on the list.");
}
} while (!city.isPresent());
String street = dataInput(scanner, "Name of the street: ");
String houseNumber = dataInput(scanner, "House number: ");
return new Address.Builder(city.get())
.atStreet(street)
.atHouseNumber(houseNumber)
.build();
By using optionals get() method you'll get it's value immediately but note that it will throw NoSuchElementException if no value is present. Usually it's not recommended to use get() to get Optional's value, but in this case it can be used as you're sure that Optional will be present because of the while condition.
Anyway, when you are not sure if optional is present then it's best to use alternative Optional methods to get it's value:
orElse() - Return the value if present, otherwise return other.
orElseGet(Supplier<? extends T> other) - Return the value if present, otherwise invoke other and return the result of that invocation.
orElseThrow(Supplier<? extends X> exceptionSupplier) - Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

Object that contains ArrayList

I am doing a program to sell games. Now in my code it will show only the last review the customer writes, but instead I would like it to contain a list of all reviews the game got. I was thinking if it would be possible to have an ArrayList as a variable instead of the String review. Here is an example of how it looks like now.
public class Game {
private String gameName;
private int gamePrice;
private String gameReviews;
public Game(String gameName, int gamePrice, String gameReviews) {
this.gameName = gameName;
this.gamePrice = gamePrice;
this.gameReviews = gameReviews;
}
}
and then if I want to create an object how it would look like to replace the old one I had?
public class Games {
public static void main(String[] args) {
String gameN = "Name";
int gameP = 10;
String gameR = "Review";
Game game = new Game(gameN, gameP,gameR);
}
}
It is possible to use ArrayList instead of String.
import java.util.ArrayList;
class Game {
private String gameName;
private int gamePrice;
private ArrayList<String> gameReviews;
public Game(String gameName, int gamePrice, ArrayList<String> gameReviews) {
this.gameName = gameName;
this.gamePrice = gamePrice;
this.gameReviews = gameReviews;
}
public static void main(String[] args) {
String gameN = "Name";
int gameP = 10;
ArrayList<String> gameReviews = new ArrayList<String>();
gameReviews.add("Review 1");
gameReviews.add("Review 2");
gameReviews.add("Review 3");
gameReviews.add("Review 4");
Game game = new Game(gameN, gameP,gameReviews);
}
}
If the relationship between your game and the reviews is one-to-many, the data type of your reviews can be List<String>
public class Game {
private String gameName;
private int gamePrice;
private List<String> gameReviews;
public Game(String gameName, int gamePrice, List<String> gameReviews) {
this.gameName = gameName;
this.gamePrice = gamePrice;
this.gameReviews = gameReviews;
}
public Game(String gameName, int gamePrice) {
this.gameName = gameName;
this.gamePrice = gamePrice;
this.gameReviews = new ArrayList<>();
}
public void addGameReview (String gameReview) {
this.gameReviews.add(gameReview);
}
}
Then if you have the list of reviews at initialization you'd just pass it into the constructor:
List<String> reviews = new ArrayList<>();
Game game = new Game(gameN, gameP, reviews);
Otherwise, you could have a constructor that initializes gameReviews to an empty ArrayList, and add the review after the initialization
Game game = new Game(gameN, gameP);
game.addGameReview("This is a review of Game ...");

How to construct an array of arrays from Resultset

I am working on Google charts API and
Google Visualization Candlestick Charts expects data to be an array of arrays for it to work .
For example the below format
[
[ "2011-08-01", 136.65, 136.96, 134.15, 136.49 ],
[ "2011-08-02", 135.26, 135.95, 131.50, 131.85 ],
[ "2011-08-05", 132.90, 135.27, 128.30, 135.25 ]
]
This is my SQL by which i am retrieving the data from database
String selectsql = "select current_day , open_val , high_val , low_val , close_val from historical_data where symbol_name = ?";
while(Rset.next())
{
String current_day = SgxRset.getString("current_day");
String open_val = SgxRset.getString("open_val");
String high_val = SgxRset.getString("high_val");
String low_val = SgxRset.getString("low_val");
String close_val = SgxRset.getString("close_val");
}
Could you please tell me how to construct how to construct an array of arrays ??
sample program
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
public class TestJSON {
public static void main(String[] args) throws JSONException {
Employee emp1 = new Employee();
emp1.setName("Ravi");
emp1.setName("20");
Employee emp2 = new Employee();
emp2.setName("Kiran");
emp2.setName("20");
List<Employee> histList = new ArrayList<Employee>();
Object[] arrayResultData = histList.toArray();
}
}
public class Employee {
String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
String age ;
}
Create a class which will held all these data together in an object like this with getters and setters:
public class Data {
private String current_day;
private double open_val;
private double high_val;
private double low_val;
private double close_val;
public Data(String current_day, double open_val, double high_val,
double low_val, double close_val) {
this.current_day = current_day;
this.open_val = open_val;
this.high_val = high_val;
this.low_val = low_val;
this.close_val = close_val;
}
public String getCurrent_day() {
return current_day;
}
public void setCurrent_day(String current_day) {
this.current_day = current_day;
}
public double getOpen_val() {
return open_val;
}
public void setOpen_val(double open_val) {
this.open_val = open_val;
}
public double getHigh_val() {
return high_val;
}
public void setHigh_val(double high_val) {
this.high_val = high_val;
}
public double getLow_day() {
return low_val;
}
public void setLow_day(double low_day) {
this.low_val = low_day;
}
public double getClose_day() {
return close_val;
}
public void setClose_day(double close_day) {
this.close_val = close_day;
}
}
Now, store the data in array of objects which you are getting from SQL.
String selectsql = "select current_day , open_val , high_val , low_val ,close_val from historical_data where symbol_name = ?";
List<Data> myList = new ArrayList(Data);
while(Rset.next())
{
String current_day = SgxRset.getString("current_day");
String open_val = SgxRset.getString("open_val");
String high_val = SgxRset.getString("high_val");
String low_val = SgxRset.getString("low_val");
String close_val = SgxRset.getString("close_val");
Data data = new Data(current_day,open_val,high_val,low_val,close_val);
myList.add(data);
}
For reading data, you can write:
String a = "[ ";
for (int i = 0; i < myList.size(); i++) {
String b = "[ \"" + myList.get(i).getCurrent_day() + "\" , "
+ myList.get(i).getOpen_val() + "],";
if(i==myList.size() -1)
a += b;
else
a += b+",";
}
a += " ]";
Now, for me the output is:
[ [ "2011-08-01" , 136.65],[ "2011-08-02" , 135.26] ]
I recommend a List. You don't know what your columns are and how many you have:
List<HistData> histList = new ArrayList<HistData>();
//.. query db
while(Rset.next()){
HistData histData = new HistData();
histData.setCurrentDay( SgxRset.getString("current_day"));
histData.setOpenVal( SgxRset.getString("open_val"));
histData.setHighVal( SgxRset.getString("high_val"));
histData.setLowVal( SgxRset.getString("low_val"));
histData.setCloseVal( SgxRset.getString("close_val"));
histList.add(histData);
}
HistData is just a POJO, but you can change the datatypes in the bean and the SgxRset retrieval type, so you are not locked in to any array type. Using a List as opposed to an array provides more flexibility in case you are returning many results of unknown length.
public class HistData {
public HistData(){}
String currentDay;
public setCurrentDay(String currentDay){
this.currentDay = currentDay;
}
public getCurrentDay(){
return currentDay;
}
// .. etc.
}
Use a List and the toArray Method
String selectsql = "select current_day , open_val , high_val , low_val , close_val from historical_data where symbol_name = ?";
List<String[]>resultData = new ArrayList<Stirng[]>();
while(Rset.next())
{
String[] array = new String[5];
array[0] = SgxRset.getString("current_day");
array[1] = SgxRset.getString("open_val");
array[2] = SgxRset.getString("high_val");
array[3] = SgxRset.getString("low_val");
array[4] = SgxRset.getString("close_val");
}
Object[] arrayResultData = resultData.toArray();

Categories

Resources