My code doesn't seem to work when the string token is an int. Here it is:
public class CO2Data {
CO2Data dataSet[] = new CO2Data[10];
String strLine = "Italy 476.08 116.86 2 592";
int lines = 10;
double roadCO2;
public void saveLineInfo(String strLine, int lines) {
StringTokenizer token = new StringTokenizer(strLine);
String str = "hello";
int count = 0;
for (int i = 0; i < lines; i++) {
while (token.hasMoreTokens()) {
str = token.nextToken();
if (count == 3) {
getRoadCO2(str, roadCO2);
dataSet[i].setRoadCO2(roadCO2);
}
count++;
}
}
}
public double getRoadCO2(String str, double roadCO2) {
roadCO2 = Double.parseDouble(str);
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
}
In the rest of the lines, roadCO2 is a double, so I'm guessing my program is getting confused? How do I fix it? Thanks so much!
You are getting NullPointerException because,
You've declared an Array of CO2Data dataSet[] = new CO2Data[10];,
but every element inside this CO2Data[] array is pointing to Null.
Hence, this call: dataSet[i].setRoadCO2(roadCO2); will generate a NullPointerException
because dataSet[i] is pointing to null.
Solution :
Instantiate dataSet[i] = new CO2Data();
then call dataSet[i].setRoadCO2(roadCO2);
I'd recommend changing the names of the parameters to your methods to something slightly different than the class datamember "roadCO2". That might help you sort out the error :)
When I ran your code, I got a NullPointerException at line 22. This is beacuse the array 'data' has not been initialized.
You can initialize your array as follows
for(int i = 0; i < dataSet.length; i++) {
dataSet[i] = new CO2Data();
}
Related
I am trying to write a class that has methods according to a homework assignment. The class input is a string that is turned into an char array. I want to return the char array as a string inside the method originalChar. Here is my code:
public class Problem5 {
public static void main(String[] args) {
CharacterArray array1 = new CharacterArray("Cool");
System.out.println(array1.originalChar());
}
}
class CharacterArray {
char[] storage;
String formForReturn;
CharacterArray() {
}
CharacterArray(String s) {
char[] storage = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
storage[i] = s.charAt(i);
}
}
public String originalChar() {
String formForReturn = new String(storage);
return formForReturn;
}
}
The error I get is NullPointerException, which to my understanding means I am trying to reference something that doesn't exist. I'm not sure how I troubleshoot this and how to resolve this problem. Some help would be much appreciated.
The way to access instance variable char[] storage; is to use this keyword which represents current object. Otherwise, with your current solution, what you return is empty which causes NullPointerException. Because you create another storage instead of using existing one in the class.
Also you can write your originalChar() method in a shorter way:
class CharacterArray {
char[] storage;
CharacterArray() { }
CharacterArray(String s) {
this.storage = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
storage[i] = s.charAt(i);
}
}
public String originalChar() {
return new String(this.storage);
}
}
First off I want to start by saying I'm not just looking for someone to give me the answer to this problem, I am a beginner programmer and am just trying to learn as much as possible. A critique of my code and a friendly nudge in the right direction would be most appreciated! What is really confusing me is my stringParser method. I use this method to loop through the string, picking out the numbers and storing them in a new string to be parsed. What confuses me is how I would be able to add these numbers together? Here is the code:
public static int stringParser(String parsee,int parsed)
{
int indexOfString = parsee.indexOf("="); //Searches for an = sign since there has to be one
String parsee2 = "";
int [] newArray;
String subStringParse = parsee.substring(0,indexOfString); //Substring made to divide string, this one is from 0 index to 1st occurence of =
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
} return parsed;
}
public static int sumInts(int a,int storedSums)
{
//a = new int[20];
for(int i=0;i<a;i++) //loops through parsed string from stringParser
{
storedSums += a; //creates a new value calculating sum
}
return storedSums;
}
As per my guess, you want to parse something like this `12 + 34 = '.
If I'm right, then your for loop is completely wrong. It will return only 34 as integer value. You can debug your code for that.
I suggest you something like this :
int index = 0;
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
newArray[index++] = parsed; //make sure you initialize newArray.
}
return newArray;
Try,
String parsee = "12+13 = 34+45 = 45+-45";
int value = 0;
String parsed = "";
for(String exp : parsee.split("=")){
for(String val : exp.trim().split("\\+")){
value+=Integer.parseInt(val);
}
parsed+=" SUM = "+value;
value = 0;
}
System.out.println(parsed);
Output
SUM = 25 SUM = 79 SUM = 0
Can anyone tell me why I am getting a null pointer exception here? I examined the code and haven't found anywhere that might be doing that, I'm a little stumped. Any help would be appreciated :D.
And by the way, the method is supposed to split strings between specified characters, for example: substringChars("sectionA; sectionB; sectionC;", ';'); would split the string between each semicolon (the specified character to split between) and return a string array with "sectionA" "sectonB" and "sectionC"
Code:
package substringChars;
public class SubstringChars {
public static void main(String[] args) {
substringChars("sectionA; sectionB; sectionC;", ';'); //There is an error on this line
System.out.println(SubstringChars.output[0] + SubstringChars.output[1] + SubstringChars.output[2]);
}
public static String[] output;
public static void substringChars(String iString, char sChar) {
int pChar = 0, outputSlot = 0;
char selectedChar;
for(int i = 0; i <= iString.length(); i++) {
selectedChar = iString.charAt(i);
if(selectedChar == sChar) {
if(i != iString.length()) {
SubstringChars.output[outputSlot] = (iString.substring(pChar, i)); //There is an error on this line
}
if(i == iString.length()) {
SubstringChars.output[outputSlot] = (String)(iString.substring(pChar));
}
pChar = i;
outputSlot++;
}
}
}
}
Error:
Exception in thread "main" java.lang.NullPointerException
at substringChars.SubstringChars.substringChars(SubstringChars.java:16)
at substringChars.SubstringChars.main(SubstringChars.java:5)
Thank you for your help!
Your output array is never initialized.
Your for loop is counting past the bounds of 'iString'.
At the beginning of your substringChars method, add this:
output = new String[3];
And change your for loop to use < instead of <=.
for(int i = 0; i < iString.length(); i++) {
Also, I would recommend using a Vector while generating the list first, and then convert to a normal array after.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
There is a function in String called split(String regex) that does the same thing you are trying to do. you should use this unless you are for some reaosn trying to re-code the wheel.
String str = "hello;my;name;is;saigon"
String a[] = str.split(";")
// a[0] = "hello"
// a[1] = "my"
// a[2] = "name"
// ...
You are using uninitialized variable!
You have
public static String[] output;
which is never uninitialized and when you try to use it to store array, it is working with null (non-existent object).
This creates array of String for up to 1000 strings and store reference in variable output :
public static String[] output = new String[1000];
Your Array output is null, since you have not initialized it,
Instead of
public static String[] output;
do
public static String[] output = new String[3];
I have developed a BlackBerry application where in I am reading in a HEX String values. The values returned are as follows:
String result = response.toString();
where result is:
["AC36C71DF3CB315A35BFE49A17F483B6","CF5B717ACC460E3C4545BE709E9BCB83","E1EE334738CA4FA14620639DD6750DC3","DD40E2822539C2184B652D1FC3D2B4E6","6AF4B1EAC8D8210D64A944BFD487B9F2"]
These are passed into the following split method to separate the values. The method is as follows:
private static String[] split(String original, String separator) {
Vector nodes = new Vector();
int index = original.indexOf(separator);
while (index >= 0) {
nodes.addElement(original.substring(0, index));
original = original.substring(index + separator.length());
index = original.indexOf(separator);
}
nodes.addElement(original);
String[] result = new String[nodes.size()];
if (nodes.size() > 0) {
for (int loop = 0; loop < nodes.size(); loop++) {
result[loop] = (String) nodes.elementAt(loop);
System.out.println(result[loop]);
}
}
return result;
}
The above array is passed is as the String original in the method. This part is working fine. However, when a single value is passed in as String original, i.e. ["6AF4B1EAC8D8210D64A944BFD487B9F2"], I get an error :
Detail formatter error:java.util.Arrays cannot be resolved to a type.
Please help !!! The values posted above are exact values as read including the parenthesis [] and quotations ""
The Blackberry libraries are based on Java ME and not Java SE. In Java ME some classes have been removed to reduce the runtime footprint such as the Arrays class.
Take a look at the Blackberry JDE java.util package, see there is no Arrays class. So in your code you cannot use methods coming from the Arrays class, you must found a workaround or implement the feature yourself.
Try this split method -
public static String[] split(String strString, String strDelimiter) {
String[] strArray;
int iOccurrences = 0;
int iIndexOfInnerString = 0;
int iIndexOfDelimiter = 0;
int iCounter = 0;
//Check for null input strings.
if (strString == null) {
throw new IllegalArgumentException("Input string cannot be null.");
}
//Check for null or empty delimiter strings.
if (strDelimiter.length() <= 0 || strDelimiter == null) {
throw new IllegalArgumentException("Delimeter cannot be null or empty.");
}
if (strString.startsWith(strDelimiter)) {
strString = strString.substring(strDelimiter.length());
}
if (!strString.endsWith(strDelimiter)) {
strString += strDelimiter;
}
while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1) {
iOccurrences += 1;
iIndexOfInnerString = iIndexOfDelimiter +
strDelimiter.length();
}
strArray = new String[iOccurrences];
iIndexOfInnerString = 0;
iIndexOfDelimiter = 0;
while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1) {
strArray[iCounter] = strString.substring(iIndexOfInnerString,iIndexOfDelimiter);
iIndexOfInnerString = iIndexOfDelimiter +
strDelimiter.length();
iCounter += 1;
}
return strArray;
}
I figured out a a problem in my Code. First the code:
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
String[] blablubb = { "a", "b", "c" };
for(String s : blablubb) {
s = "over";
}
printArray(blablubb);
for (int i = 0; i < blablubb.length; i++) {
blablubb[i] = "over";
}
printArray(blablubb);
}
public static void printArray(String[] arr) {
for( String s : arr ) {
System.out.println(s);
}
}
}
The output is:
a
b
c
over
over
over
I assumed the first loop would also overwrite the String in the array. So the output would be over in any case. It seems it creates a copy of the value instead creating a reference.
I never perceived this. Am I doing it wrong? Is there an option to create a reference instead?
//Edit:
Seems like everybody knows about that except me. I'm from C background and doesn't pay enough attention to the term reference which is very different to C.
Fortunately it took me just 10 minutes to figure this out (this time).
This:
for (String s : blablubb) {
s = "over";
}
Is equal to this:
for (int i = 0; i < blablubb.length; i++) {
String s = blablubb[i];
s = "over";
}
This creates a temporary String with a copy of the value from array and you change only the copy. That's why blablubb[] content stays untouched.
If you want to change values in the array, just use your second option:
for (int i = 0; i < blablubb.length; i++) {
blablubb[i] = "over";
}
And, by the way, you can print an array with just one line:
System.out.println(Arrays.toString(blablubb));
Your for(String s : blablubb) loop is equivalent to the following code:
for(int i = 0; i < blablubb.length; i++ ) {
String s = blablubb[i];
s = "over";
}
Hopefully, from this you can see that all you are doing is reassigning a different value to s without changing blablubb[i]. This explains the output you see.
The for-each loop don't modify the objects contained in the Collection of objects it's iterating over. It's passing the value not the reference.
s = "over";
just changes the reference of s and not the String in the array.
blablubb[i] = "over";
changes the value stored at ith location in the array
for(String s : StringArray)
{
}
is like
for(int i = 0; i < StringArray.length; i++)
{
String s = StringArray[i];
}
When you want to do a low level optimization, know how, you have to look inside Java code and inside byte-code either(compiled code)
for(String s : blablubb) {
s = "over";
}
is equals with:
for (int i = 0; i < blablubb.length; i++) {
String s = blablubb[i];
s = "over";
}
and that's why the output as how it is.