I am trying to add a default constructor to my data type. Right below the default constructor is the problem,"ingredients = " " ; ". It gives me an error saying String cannot be converted to String[]. What do I put after the equals sign to make it compile?
import java.util.Arrays;
class Recipes {
private String[] ingredients = new String[20];
private String[] instructions = new String[20];
public Recipes(){
ingredients = "" ;
instructions = "" ;
}
public String[] getIngredients() {
return ingredients;
}
public void setIngredients(String[] inIngredients) {
ingredients = inIngredients;
}
public String[] getInstructions() {
return instructions;
}
public void setInstructions(String[] inInstructions) {
instructions = inInstructions;
}
public void displayAll() {
System.out.println("The ingredients are " + ingredients);
System.out.println("The instructions are " + instructions);
}
}
It doesn't make sense to assign a String ("") to String[] (an array of Strings).
You may want to do one of the following in your default constructor, depending on your requirements:
Do nothing. The arrays were already initialized when they were declared, even if they are full of null elements.
Assign the empty string "" to every element. You can use a for loop for that, or an array initializer.
Assign null to the arrays. You are presumably replacing the array references later by calling setIngredients and setInstructions.
You are initializing a String array reference to a single string value thats why the compiler is going nuts.
You can do this
class Recipes {
private String[] ingredients = null;
private String[] instructions = null;
public Recipes(){
ingredients = new String[5]{"","","","",""};
instructions = new String[5]{"","","","",""};
}
I've reduced the size of the array for brevity. You can also use a for loop to assign fill in empty strings in the array if the array size is too large.
class Recipes {
private String[] ingredients = new String[20];
private String[] instructions = new String[20];
public Recipes(){
for(int i=0;i<ingredients.length;i++)
{
ingredients[i]="";
instructions[i]="";
}
}
Related
I'm working with a large set of imported data and retrieving certain parts of it in the main method with 2 classes(WeatherStation, WeatherReading).The data is temperature readings at loads of weather stations(station id, name, lat, lon, year, time, temp etc) I made a third class (SoloSiteIds) whose sole purpose was to return a whole and complete ArrayList of the site ids with no duplication. But I cannot import the ArrayList from the other class into my main method. My SoloSiteIds class looks like this:
public class SoloSiteIds {
static ArrayList <Integer> siteIds = new ArrayList <Integer>();
public SoloSiteIds() {
}
public SoloSiteIds( ArrayList <Integer> siteIds) {
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ",
String siteid = elements[0]; // convert all the site id's at index 0 to integers
int id = Integer.parseInt(siteid);
if(!siteIds.contains(id)) {
siteIds.add(id);
}
this.siteIds=siteIds;
}
}
}
public static ArrayList<Integer> getSiteIds() {
return siteIds;
}
public ArrayList<Integer> setSiteIds(ArrayList<Integer> siteIds) {
return this.siteIds = siteIds;
}
}
The main method where I am trying to import the ArrayList "siteIds" looks like this:
WeatherStation thisStation = new WeatherStation (id, name, lat, lon);
WeatherReading thisReading = new WeatherReading(year, month, date, hour, windSpeed, temp);
SoloSiteIds siteList= new SoloSiteIds();
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ","
String siteid = elements[0]; // convert all the site id's at index 0 to integers
id = Integer.parseInt(siteid);
thisStation.setId(id);
thisStation.setName(elements[1]);
//parse the different elements into different data types
String stringLat = elements[2];
lat= Double.parseDouble(stringLat);
lat = thisStation.setLat(lat);
lat=thisStation.setLat(lat);
String stringLon = elements[3];
lon= Double.parseDouble(stringLon);
lat = thisStation.setLon(lon);
lat=thisStation.setLon(lon);
String stringTemp=elements[9];
temp=Double.parseDouble(stringTemp);
temp=thisReading.setTemp(temp);
Only the top part is relevant. I have tried lots of different variation of .set and .get using "thisList" instance and a new ArrayList like
ArrayList<Integer> siteIds = thisList.setSiteIds();
ArrayList<Integer> siteIds= SoloSiteIds.getSiteIds();
thisList=Siteids.setSiteIds();
thisList=SingleSoloSites.setSiteIds();
etc etc. This might look stupid but im just showing Ive tried numerous things and i am stuck
Thanks
I believe your problem is that you are initializing siteIds as an empty Arry list but you are not setting the data in a static way (the set Method is not static).
As far as I am aware of your situation, I belive that the SoloSiteIds class is unnescessary. I would solve your problem with an ArrayList declared in your main class and initialize with a getSoleIds() method also declared in your main class.
The getSoleIds() Method should contain the code currently in the SoleSiteIds initializer.
I am trying to figure out why my program says my array is null and cannot be written to. I created an Element class to determine what elements would be in the array, so the array is type Element[]. The array takes in data from a file and then is supposed to add it to the array. The program seems to read the data from the file but it will not add it to the array.
class Array extends Element
{
//Global Variables
public static Element[] array;
//Max number of entries
private int numMax;
public int numElements;
//Constructors
public Array()
{
}
public Array(int numMax)
{
//Instantiate the array
array = new Element[numMax];
numElements = 0;
}
This is a function to insert the data into the array:
public void insertValue(String firstName, String lastName,
String company, String address, String city, String state,
String county, String phone, int zip, long key, int rowNum)
{
try
{
//Add elements to array
System.out.println(numElements);
array[numElements].setFirstName(firstName);
array[numElements].setLastName(lastName);
array[numElements].setCompany(company);
array[numElements].setAddress(address);
array[numElements].setCity(city);
array[numElements].setState(state);
array[numElements].setCounty(county);
array[numElements].setPhone(phone);
array[numElements].setZip(zip);
array[numElements].setKey(key);
array[numElements].setRowNum(rowNum);
//Increment number of elements in the array
numElements++;
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}
This is my input function:
public static void readInputFile()
{
//Create a new instance of the array class so that the array can be
//written to without creating a new array for either merge or insert
//sort
Array arr = new Array(1000010);
Element[] array = arr.getArray();
try
{
fileRead = new FileReader(fileLocation);
br = new BufferedReader(new FileReader(fileLocation));
//Allows the first line of the file that includes the titles to
//not be added to the array
String line = br.readLine();
//Counter for iterating through array
int elemCntr = 0;
while (elemCntr != 10)
{
//Variables
String lineline = br.readLine();
//This will split the line into sections based on the
//placement of comas: split data into sections
String[] readLine = lineline.split(",");
firstName = readLine[0];
lastName = readLine[1];
company = readLine[2];
address = readLine[3];
city = readLine[4];
county = readLine[5];
state = readLine[6];
zip = Integer.parseInt(readLine[7]);
phone = readLine[8];
key = Long.parseLong(readLine[9]);
rowNum = arr.numElements + 1;
//Insert data into array
arr.insertValue(firstName, lastName, company, address, city,
state, county, phone, zip, key, rowNum);
}
} catch (Exception e){
// do something
}
}
Can you identify any problems, please?
Try with using ArrayList
You are trying to make dynamic array of class Element which is possible.But it is bad practice as u have to write initialization statement for every element.Initialization are meant to be done in constructors.
Declaration: Element element[] = new Element[5];
Initialization: element[0] = new Element();
;
It is possible to make dynamic arrays of int , string etc easily then of Class.
PS: Try giving different names you are having Arrays as class and arrays as variable also.
your code is n't clear, but if you call readInputFile method first, it will instantiate array and then when you call insertValue method it should work properly, because array is static.
Could anyone help me understand the difference? I need to understand for my class and they seem the same to me.
String or String[]
String is -> a series of characters in your code that is enclosed in double quotes.
More details a bout String
String[] -> An array is a container object that holds a fixed number of values of a Strings.
More about Arrays
The difference between String and String[] is that String is used to declare a single instance of a String object:
String name = "Cupcake";
On the other hand, String[] is used to declare an array of multiple strings:
String[] names = new String[] { "Joe", "Alice" };
In Java generally, arrays of type <Type> are declared using the following syntax:
<Type>[] types;
From the official Java documentation for arrays:
An array's type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array.
String is used to create a single object of type String
String[] is an Array, containing a specified number of String objects.
String is a class, and String a represents an object of this class (the String class represents an object containing a sequence of characters). While String a[] represents an array of objects of this type.
An array is a kind of container. It can contain various objects inside. In this case with String[] you are specifying that this container has only String objects
String a = "abc"; /*this is a String, notice it references only to one
object, which is a sequence of characters*/
String b[] = new String[]{"abc", "def"}; /*this is a String array.
It is instantiated with 2 String objects, and it cannot
contain anything else other than String or its sub classes (i.e: no Integers or neither Object). */
Similar to array, String[] is used to store more than one string at a time.
Following is a sample program for String[]
public class JavaStringArrayExample {
public static void main(String args[]) {
// declare a string array with initial size
String[] schoolbag = new String[4];
// add elements to the array
schoolbag[0] = "Books";
schoolbag[1] = "Pens";
schoolbag[2] = "Pencils";
schoolbag[3] = "Notebooks";
// this will cause ArrayIndexOutOfBoundsException
// schoolbag[4] = "Notebooks";
// declare a string array with no initial size
// String[] schoolbag;
// declare string array and initialize with values in one step
String[] schoolbag2 = { "Books", "Pens", "Pencils", "Notebooks" }
// print the third element of the string array
System.out.println("The third element is: " + schoolbag2[2]);
// iterate all the elements of the array
int size = schoolbag2.length;
System.out.println("The size of array is: " + size);
for (int i = 0; i < size; i++) {
System.out.println("Index[" + i + "] = " + schoolbag2[i]);
}
// iteration provided by Java 5 or later
for (String str : schoolbag2) {
System.out.println(str);
}
}
}
Hope this will give you an idea.
This is a drive method for two other classes. which i posted here
https://codereview.stackexchange.com/questions/33148/book-program-with-arraylist
I need some help for the
private static ArrayList getAuthors(String authors) method. I am kind a beginner. so please help me finish this drive method. or give me some directions.
Instruction
some of the elements of the allAuthors array contain asterisks “*” between two authors names. The getAuthors method uses this asterisk as a delimiter between names to store them separately in the returned ArrayList of Strings.
import java.util.ArrayList;
public class LibraryDrive {
public static void main(String[] args) {
String[] titles = { "The Hobbit", "Acer Dumpling", "A Christmas Carol",
"Marley and Me", "Building Java Programs",
"Java, How to Program" };
String[] allAuthors = { "Tolkien, J.R.", "Doofus, Robert",
"Dickens, Charles", "Remember, SomeoneIdont",
"Reges, Stuart*Stepp, Marty", "Deitel, Paul*Deitel, Harvery" };
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
for (int i = 0; i < titles.length; i++) {
authors = getAuthors(allAuthors[i]);
Book b = new Book(titles[i], authors);
books.add(b);
authors.remove(0);
}
Library lib = new Library(books);
System.out.println(lib);
lib.sort();
System.out.println(lib);
}
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
// need help here.
return books;
}
}
try this
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
String[] splitStr = authors.split("\\*");
for (int i=0;i<splitStr.length;i++) {
books.add(splitStr[i]);
}
return books;
}
What I would suggest is to use String.split like here (but keep in mind that this method uses a regex as parameter):
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
String[] strgArray = authors.split("\\*");
books.addAll(Arrays.asList(strgArray));
return books;
}
or
private static ArrayList<String> getAuthors(String authors) {
String[] strgArray = authors.split("\\*");
ArrayList books = Arrays.asList(strgArray);
return books;
}
Try this one but actually i do not understant why you remove zero indexed element of ArrayList in for loop.
private static ArrayList<String> getAuthors(String authors) {
ArrayList<String> array = new ArrayList<String>();
String[] authorsArray = authors.split("\\*");
for(String names : authorsArray );
array.add(names);
return array;
}
Take a look at String#split method, this will help you to separate authors by asterisk. This method returns an array so you will need to check how many authors are in this array and then store each of them into the ArrayList.
Here's how you can go about doing it.
Split the authors string you're getting as the method param based on the asterisk symbol. (Using String.split(delim) method)
The resultant string[] array needs to be iterated over using a for loop and each iterated element should be added to your list. (Using List.add(elem) method)
Once done, return that list(you are already doin that).
Now that you know how to do it, you need to implement the code by yourself.
I have a series of String[] arrays which are list of words. Something like:
String[] ListOne = new String[100];
String[] ListTwo = new String[100];
/*And so on with other lists */
ListOne[0] = "word00";
ListOne[1] = "word01";
/*And so on till*/
ListLast[99] = "word 99 from last list";
Now I want a function for each list that, given a number returns the corresponding element (word):
public String GetFromListOne(int key) { return ListOne[key];}
Is there a way to avoid manually writing each of this getter functions?
In PHP, for example, I would just use the magic method __call,
or pass as an argument with the list name and reference it dynamically.
Is there a way to do something similar in Java?
Or an alternative strategy to achieve the same result?
You should look into inheritance.
What you basically must do is define an interface (or extend a List class)
public interface ListTest{
//**Gets keys from lists*//
GetFromListOne(int key);
}
then
public class Listone implements ListTest{
/** methods **//
GetFromListOne(int key);
/** methods **//
}
Have fun extending
http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
You could use a 2 dimensional array, or a list of arrays and have your function take 2 parameters. One for the array that you want and the other for the element in the array.
2 dimensional array:
String[][] ListN = new String[100,100];
String getFromList(int n, int key) {
return ListN[n][key];
}
Or list of arrays:
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(new String[100]);
listOfArrays.add(new String[100]);
String getFromList(int n, int key) {
return listOfArrays.get(n)[key];
}
Could you have a function that takes as input the key and the list number:
public String GetFromListOne(int list, int key) {
switch(list):
case 1:
return ListOne[key];
break;
case 2:
return ListTwo[key];
break;
...
}
or even better make an array of arrays:
String[][] ListOfLists = new String[10];
ListOfLists[0] = new String[100];
...
public String GetFromList(int list, int key) {
return ListOfLists[list][key];
}
Otherwise I don't know of a function to override like __call
String[] ListFour=new String[100];
String[] ListTwentyThree=new String[100];
String[] ListNine=new String[100];
String[] ListOne=new String[100];
Hashtable<Integer,String[]> yourlist=new Hashtable<Integer,String[]>();
yourlist.put(4, ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(9, ListNine);
yourlist.put(1, ListOne);
System.out.println(yourlist.get(4)[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(9)[1]);//first stringin ListNine
another version:
Hashtable<Object,String[]> yourlist=new Hashtable<Object,String[]>();
yourlist.put("two multiplied by two", ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(0.03, ListNine);
yourlist.put(true, ListOne);
System.out.println(yourlist.get("two multiplied by two")[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(true)[1]);//first stringin ListNine
Based in the __call PHP method, you can achieve this implementing a method that receives the list and the index, and using generics you can get something like this.
public class Utility {
public <T> T getElementFromArray(T[] array, int index) {
if (index >= array.length || index < 0) return null;
return array[index];
}
}
The pitfall of this method is that can't be used for primitive array holders, like int[]. The solution for these cases would be using the wrapper classes for primitive types.
public static void main(String[] args) {
Utility u = new Utility();
String[] ss = new String[2];
ss[0] = "Hello";
ss[1] = "world!";
System.out.println(u.getElementFromArray(ss, 0));
System.out.println(u.getElementFromArray(ss, 1));
int[] ii = new int[2];
ii[0] = 5;
System.out.println(u.getElementFromArray(ii, 0)); //compile error
//Solution: use wrapper classes
Integer[] ii2 = new Integer[2];
ii2[0] = 5;
System.out.println(u.getElementFromArray(ii2, 0));
}
Try this code
List<String[]> lists = new ArrayList<String[]>();
public String getFromLists(int key) {
List<String> res = new ArrayList<String>();
for (String[] s: lists){
res.add(s[key]);
}
return res.get(key);
}
or better
public String getFromLists(int key) {
return lists.get(key)[key];
}