I am trying to create a double string. I thought that this is one way to assign values. I know there are better ways, but it was suggested by my teacher to do it this way. However when I put this in I get errors for each one stating:
can't find symbol cellPhoneNumbers
']' expected
Ultimately what I am trying to do is create a graph that looks something like this
Chile *******
Sweden *
Peru ***************
public class GraphNumbers
{
String[][] cellPhoneNumbers = new String[5][1];
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
}
Why am I receiving this message?
Some of the code must be placed in a method for example:
public class GraphNumbers
{
//changed the size of the array so you could do what you want
//you must have had a misscount when you originally made it
String[][] cellPhoneNumbers = new String[5][2];
//put in constructor or another appropriately named method
public GraphNumbers()
{
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
}
}
As per Java language syntax, you cannot put executable statements in class. Those should be put in either method/constructor/code blocks.
So you need to move these statements:
cellPhoneNumbers[0][0] = "Chile";
cellPhoneNumbers[0][1] = "21";
cellPhoneNumbers[1][0] = "Sweden";
cellPhoneNumbers[1][1] = "11";
cellPhoneNumbers[2][0] = "Peru";
cellPhoneNumbers[2][1] = "33";
cellPhoneNumbers[3][0] = "Bulgaria";
cellPhoneNumbers[3][1] = "10";
cellPhoneNumbers[4][0] = "Guatemala";
cellPhoneNumbers[4][1] = "18";
to appropriate place, maybe in a constructor.
Also your code is overflowing the array in stamens such as :
cellPhoneNumbers[0][1] = "21";
so you need the second dimension of array to be of size 2 and not 1. Change this
String[][] cellPhoneNumbers = new String[5][1];
to
String[][] cellPhoneNumbers = new String[5][2];
Related
So i've been trying to solve this issue for hours but cant seem to find an answer which would work.
i have an object array which stores flight information and i had to remove flights which had Valstybe: "Maldyvai"
so i made a new object array without them, but when i try to print it i get a memory location.
How do i convert the object array to string array?
even though i have a tostring method in my java class
package com.company;
import java.util.*;
import com.company.Isvestine.OroUostasKeleivis;
public class Main {
public static void main(String[] args) {
// write your code here
OroUostasKeleivis Keleiviai1 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5465);
OroUostasKeleivis Keleiviai2 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5466);
OroUostasKeleivis Keleiviai3 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5467);
OroUostasKeleivis Keleiviai4 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5468);
OroUostasKeleivis Keleiviai5 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5469);
OroUostasKeleivis Keleiviai6 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5470);
OroUostasKeleivis Keleiviai7 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5475);
OroUostasKeleivis Keleiviai8 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5476);
OroUostasKeleivis Keleiviai9 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5477);
OroUostasKeleivis Keleiviai10 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5488);
OroUostasKeleivis[] keleiviai = new OroUostasKeleivis[10];
keleiviai[0] = Keleiviai1;
keleiviai[1] = Keleiviai2;
keleiviai[2] = Keleiviai3;
keleiviai[3] = Keleiviai4;
keleiviai[4] = Keleiviai5;
keleiviai[5] = Keleiviai6;
keleiviai[6] = Keleiviai7;
keleiviai[7] = Keleiviai8;
keleiviai[8] = Keleiviai9;
keleiviai[9] = Keleiviai10;
for (OroUostasKeleivis keleiveliai:keleiviai) {
System.out.println(keleiveliai);
}
System.out.println("test debug");
OroUostasKeleivis[] keleiviaibemaldyvu = new OroUostasKeleivis[10];
for (int i = 0; i < 10; i++) {
}
System.out.println(IsstrintiMaldyvus(keleiviai));
String convertedStringObject = IsstrintiMaldyvus(keleiviai) .toString();
System.out.println(convertedStringObject );
}
static Object[] IsstrintiMaldyvus(OroUostasKeleivis[] keleiviai){
OroUostasKeleivis[] keleiviaiBeMaldyvu = new OroUostasKeleivis[10];
int pozicija = 0;
for ( OroUostasKeleivis keleiveliai: keleiviai) {
if (keleiveliai.getValstybe() != "Maldyvai"){
keleiviaiBeMaldyvu[pozicija] = keleiveliai;
pozicija++;
}
}
return keleiviaiBeMaldyvu;
}
}
but when i try to print it i get a memory location
Yes, you will NOT have result as you expected, especially calling toString() with any array. See documentation of java.lang.Object.toString() for more details.
So how can we solve problem?
first, override toString() method in OroUostasKeleivis like this:
class OroUostasKeleivis {
#Override
public String toString() {
// your implementation here
return null; // TODO: change here
}
}
Second, you may do either way:
If you're interested in just print out, you can do that with System.out.println(keleiveliai) in for-each loop like you do.
If you're interested in converting OroUostasKeleivis[] to String[], you can:
// this requires Java 8 or later
String[] converted = Arrays.asList(keleiviai)
.stream()
.map(OroUostasKeleivis::toString)
.toArray(String[]::new);
// then use `converted`
Use System.out.println(Arrays.toString(IsstrintiMaldyvus(keleiviai)))
https://www.geeksforgeeks.org/arrays-tostring-in-java-with-examples/
It will print the array contents similar to how ArrayList would get printed if it had the same content.
Think of it as:
[ obj1.toString(), obj2.toString(), ... ]
Using java.util.Arrays#stream(T[]) filter and convert object array to string array and use java.util.Arrays#toString(java.lang.Object[]) convert array to readable string.
final String[] oroUostasKeleivis = Arrays.stream(keleiviai)
.filter(
k -> k.getValStybe() != "Maldyvai"
)
// or other convert code
.map(OroUostasKeleivis::toString)
.toArray(String[]::new);
System.out.println(Arrays.toString(oroUostasKeleivis));
I am working on a JSF based Web Application where I read contents from a file(dumpfile) and then parse it using a logic and keep adding it to a list using an object and also set a string using the object. But I keep getting this error. I am confused where I am wrong. I am a beginner so can anyone be kind enough to help me?
List<DumpController> FinalDumpNotes;
public List<DumpController> initializeDumpNotes()
throws SocketException, IOException {
PostProcessedDump postProcessedDump = (PostProcessedDump) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("postProcessedDump");
List<DumpController> FinalNotes = new ArrayList<>();
if (postProcessedDump.getDumpNotes() == null) {
dumpNotes = new DumpNotes();
}
DumpListController dlcon = (DumpListController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dumpListController");
DumpInfo dumpinfo = dlcon.getSelectedDumpInfo();
String fileName = dumpinfo.getDate() + dumpinfo.getTime() + dumpinfo.getSeqNo() + dumpinfo.getType() + dumpinfo.getTape() + dumpinfo.getDescription() + ".txt";
if (checkFileExistsInWin(fileName)) {
postProcessedDump.setDumpnotescontent(getFileContentsFromWin(fileName));
String consolidateDumpnotes = getFileContentsFromWin(fileName);
String lines[];
String content = "";
lines = consolidateDumpnotes.split("\\r?\\n");
List<String> finallines = new ArrayList<>();
int k = 0;
for (int i = 0; i < lines.length; i++) {
if (!lines[i].equalsIgnoreCase("")) {
finallines.add(lines[i]);
k++;
}
}
for (int j = 0; j < finallines.size(); j++) {
if (finallines.get(j).startsWith("---------------------SAVED BY")) {
PostProcessedDump dump = new PostProcessedDump();
dump.setDumpMessage(content);
content = "";
FinalDumpNotes.add(dump);
} else {
content = content + finallines.get(j);
}
}
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("postProcessedDump", postProcessedDump);
return FinalDumpNotes;
}
I get the following error:
If you want to add instances of type PostProcessedDump to your List you should change it's type. Also, don't forget to initialize it. Something like,
List<PostProcessedDump> FinalDumpNotes = new ArrayList<>();
Also, Java naming convention is to start variable names with a lower case letter. FinalDumpNotes looks like a class, I would suggest something like
List<PostProcessedDump> processedList = new ArrayList<>();
Problems with your code:
List<DumpController> FinalDumpNotes;
You declare FinalDumpNotes to be a List of DumpController objects, but you never initialize it. In addition, your IDE is barfing on the following line of code:
FinalDumpNotes.add(dump);
because you are attempting to add a PostProcessedDump object to the List instead of a DumpController object.
For starters, you need to initialize your list like this:
List<DumpController> finalDumpNotes = new ArrayList<DumpController>();
Notice that I have made the variable name beginning with lower case, which is the convention (upper case is normally reserved for classes and interfaces).
I will leave it to you as a homework assignment to sort out the correct usage of this List.
I am interestig in how to get value from Object from List<>.
Here is code example with Objects
#Override
public List<ListObject> initChildren() {
//Init the list
List<ListObject> mObjects = new ArrayList<ListObject>();
//Add an object to the list
StockObject s1 = new StockObject(this);
s1.code = "Системне програмування-1";
s1.num = "1.";
s1.value = "307/18";
s1.time = "8:30 - 10:05";
mObjects.add(s1);
StockObject s2 = new StockObject(this);
s2.code = "Комп'ютерна електроніка";
s2.num = "2.";
s2.value = "305/18";
s2.time = "10:25 - 11:00";
mObjects.add(s2);
StockObject s3 = new StockObject(this);
s3.code = "Психологія";
s3.num = "3.";
s3.value = "201/20";
s3.time = "11:20 - 13:55";
mObjects.add(s3);
StockObject s4 = new StockObject(this);
s4.code = "Проектування програмного забезпечення";
s4.num = "4.";
s4.value = "24";
s4.time = "14:15 - 16:50";
mObjects.add(s4);
return mObjects;
}
You can use get() method like follows
mObjects.get(index)
where index is the zero based index of your List, just like an array.
To directly access object, you do for example,
mObjects.get(index).code
you use like below
List<ListObject> mObjects = new ArrayList<ListObject>();
.......................your program...........
//access using enhanced for loop
for(ListObject myObj : mObjects){
System.out.println(myObj.code);
System.out.println(myObj.num);
System.out.println(myObj.value);
}
//access using index
int index=0;
System.out.println(mObjects.get(index).code);
You can iterate over the collection and type cast to the data type you know its in there.
List<ListObject> listOfObjects = initChildren();
for (Iterator iterator = listOfObjects.iterator(); iterator.hasNext();) {
StockObject so = (StockObject) iterator.next();
// do whatever you want with your StockObject (so)
System.out.println("Code:" + so.code);
}
You can use for each syntax as well like following
List<ListObject> listOfObjects = initChildren();
for (ListObject listObject : listOfObjects) {
StockObject so = (StockObject) listObject;
// do whatever you want with your StockObject (so)
System.out.println("Code:" + so.code);
}
I have some xml data I am looping through. I would like to store each "entry" in an array spot in order to see it with an intent.putExtras(). My data has 3 elements: latlon,name,description. I would like to put each in my array. So I am setting it up like so: markerInfo[i][0] = Loc; etc... like so:
final List<XmlDom> entries = xml.tags("Placemark");
int i = entries.size();
int j=0;
for (XmlDom entry : entries) {
XmlDom lon = entry.tag("longitude");
XmlDom lat = entry.tag("latitude");
XmlDom name = entry.tag("name");
XmlDom desc = entry.tag("description");
String cdatareplace = desc.toString();
String description = cdatareplace.replace("<![CDATA[", "");
description = description.replace("]]>", "");
final String firename = name.text();
final String firedesc = description;
String geoLon = lon.text();
String geoLat = lat.text();
String coor = lat + "," + lon;
// Log.e("COORS: ", coor);
double lati = Double.parseDouble(geoLat);
double lngi = Double.parseDouble(geoLon);
LOCATION = new LatLng(lati, lngi);
String Loc = LOCATION.toString();
String[][] markerInfo = new String[i][3];
markerInfo[j][0] = Loc;
markerInfo[j][1] = firename;
markerInfo[j][2] = firedesc;
Log.e("MARKERINFO",markerInfo[j][0]);
Log.e("MARKERINFO",markerInfo[j][1]);
Log.e("MARKERINFO",markerInfo[j][2]);
map.addMarker(new MarkerOptions()
.position(LOCATION)
.title(markerInfo[j][1])
.snippet(markerInfo[j][2])
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.wfmi_icon48)));
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// Show full description in new activity.
// fireDesc(arg0.getTitle(), arg0.getSnippet());
Intent i = new Intent(Map.this, MapSingleActivity.class);
i.putExtra("name", arg0.getTitle())
.putExtra("description", arg0.getSnippet())
.putExtra("lat", arg0.getPosition().latitude)
.putExtra("lon", arg0.getPosition().longitude);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
j++;
}
I am getting array index out of bounds. I figured if I filled it with the entries.size() that would not be the problem, so maybe i am not telling it how big correctly?
Thanks for any help
You need to make sure that the second dimension is also big enough
Fix it by changing the declaration of markerInfo to:
String[][] markerInfo = new String[i][3];
At the moment you are only creating i empty String arrays. With the above code you will create i arrays that can hold three String objects each.
Also, at the moment you are writing to the last location which is outside of the array bounds.
You need to change it to write to an available location. If you are trying to write to the last available location that would be i-1.
markerInfo[i-1][0] = Loc;
markerInfo[i-1][1] = firename;
markerInfo[i-1][2] = firedesc;
Looking at your code however, it seems like you may want to declare markerInfo outside of the loop and create a counter variable that you increment at each step of the loop.
Second size of the array is 0 - new String[i][0]. Then you try to insert something on position 0,1,2, which are not available.
Even if you write new String[i][3], then the maximum index is i-1.
I an tryin to convert a string array to a double array, depending on what weather station was chosen from database - some weather stations have no data, so the whole string array is filled with nulls(12 of them in fact) So obviosly if one of them stations is chosen I get an exception. I realy have no time to write a lot of code to work around it, since I have to submit my work very soon... Is there any solution to catch it and display an error message to user insted of lines and lines explaining an error? Thanks!
Here is the loop to convert a string array into a double array
for(int i = 0; i<12; i++)
{
avMaxTempOptimised[i] = Double.parseDouble(avMaxTempSplit[i]);
avMinTempOptimised[i] = Double.parseDouble(avMinTempSplit[i]);
meanTempOptimised[i] = Double.parseDouble(meanTempSplit[i]);
highestTempOptimised[i] = Double.parseDouble(highestTempSplit[i]);
lowestTempOptimised[i] = Double.parseDouble(lowestTempSplit[i]);
maxWindOptimised[i] = Double.parseDouble(maxWindSplit[i]);
totalRainfallOptimised[i] = Double.parseDouble(totalRainfallSplit[i]);
maxDayRainfallOptimised[i] = Double.parseDouble(maxDayRainfallSplit[i]);
rainDaysOptimised[i] = Double.parseDouble(rainDaysSplit[i]);
totalSunshineOptimised[i] = Double.parseDouble(totalSunshineSplit[i]);
mostSunshineDayOptimised[i] = Double.parseDouble(mostSunshineDaySplit[i]);
avMaxTemp2Optimised[i] = Double.parseDouble(avMaxTemp2Split[i]);
avMinTemp2Optimised[i] = Double.parseDouble(avMinTemp2Split[i]);
meanTemp2Optimised[i] = Double.parseDouble(meanTemp2Split[i]);
highestTemp2Optimised[i] = Double.parseDouble(highestTemp2Split[i]);
lowestTemp2Optimised[i] = Double.parseDouble(lowestTemp2Split[i]);
maxWind2Optimised[i] = Double.parseDouble(maxWind2Split[i]);
totalRainfall2Optimised[i] = Double.parseDouble(totalRainfall2Split[i]);
maxDayRainfall2Optimised[i] = Double.parseDouble(maxDayRainfall2Split[i]);
rainDays2Optimised[i] = Double.parseDouble(rainDays2Split[i]);
totalSunshine2Optimised[i] = Double.parseDouble(totalSunshine2Split[i]);
mostSunshineDay2Optimised[i] = Double.parseDouble(mostSunshineDay2Split[i]);
}
if you do try/catch outside for loop, you'll stop processing the rest of the loop. Try/catch inside for loop is probably closer, as long as you don't mind the unassigned values left in the array. Something like this might be best, changing Optimized arrays to type Double[]:
for(int i = 0; i<12; i++)
{
avMaxTempOptimised[i] = safeDouble(avMaxTempSplit[i]);
avMinTempOptimised[i] = safeDouble(avMinTempSplit[i]);
meanTempOptimised[i] = safeDouble(meanTempSplit[i]);
highestTempOptimised[i] = safeDouble(highestTempSplit[i]);
lowestTempOptimised[i] = safeDouble(lowestTempSplit[i]);
maxWindOptimised[i] = safeDouble(maxWindSplit[i]);
totalRainfallOptimised[i] = safeDouble(totalRainfallSplit[i]);
maxDayRainfallOptimised[i] = safeDouble(maxDayRainfallSplit[i]);
rainDaysOptimised[i] = safeDouble(rainDaysSplit[i]);
totalSunshineOptimised[i] = safeDouble(totalSunshineSplit[i]);
mostSunshineDayOptimised[i] = safeDouble(mostSunshineDaySplit[i]);
avMaxTemp2Optimised[i] = safeDouble(avMaxTemp2Split[i]);
avMinTemp2Optimised[i] = safeDouble(avMinTemp2Split[i]);
meanTemp2Optimised[i] = safeDouble(meanTemp2Split[i]);
highestTemp2Optimised[i] = safeDouble(highestTemp2Split[i]);
lowestTemp2Optimised[i] = safeDouble(lowestTemp2Split[i]);
maxWind2Optimised[i] = safeDouble(maxWind2Split[i]);
totalRainfall2Optimised[i] = safeDouble(totalRainfall2Split[i]);
maxDayRainfall2Optimised[i] = safeDouble(maxDayRainfall2Split[i]);
rainDays2Optimised[i] = safeDouble(rainDays2Split[i]);
totalSunshine2Optimised[i] = safeDouble(totalSunshine2Split[i]);
mostSunshineDay2Optimised[i] = safeDouble(mostSunshineDay2Split[i]);
}
...
safeDouble( String str){
return str== null ? null : Double.parseDouble(str);
}
Add in quick null checks where you read Optimized arrays and you're golden.