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];
Related
Hi I am trying to solve a Kata(coding practice exercise) in CodeWars which is called "Your order, please" (there is a BIG chance that my code won't solve it but I am really just trying to get rid of the error..and there's a link to the exercise at the end in case you want to check it out)
Either way what the Kata basically says is that you will be given a String such as
"4of Fo1r pe6ople g3ood th5e the2"
and you have to order the words by getting the int and returning in the correct order so
"Fo1r the2 g3ood 4of th5e pe6ople"
Now what I coded is supposed to go through each element and get the number to then order it, so I tried to use parseInt and it did not work. I read on another article that trim() would get rid of...
java.lang.NumberFormatException: For input string: "4of" //trim did not fix it
I am not sure whether I did not implement trim() correctly or parseInt() or what is wrong, any help would be very much appreciated and thank you for taking your time to read this. Without further ado here's the code.
public class Kata {
public static String order(String words) {
String[] unordered = words.split(" ");
String[] order = new String[unordered.length];
System.out.println(unordered.length);
for(int i = 0; i < unordered.length; i++){
int correctIndex = (Integer.parseInt(unordered[i].trim())) -1;
order[correctIndex] = unordered[i];
System.out.println(unordered[i]);
}
return "I will return order concatenated";
}
public static void main(String[] args) {
System.out.println(order("4of Fo1r pe6ople g3ood th5e the2"));
}
}
And the error... (6 is the output before it)
6
Exception in thread "main" java.lang.NumberFormatException: For input string: "4of"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Kata.order(Kata.java:8)
at Kata.main(Kata.java:17)
https://www.codewars.com/kata/55c45be3b2079eccff00010f/train/java
(the link to the Kata)
4of is not an integer string and therefore, you can not parse it into an int. You can replace its non-digit characters (\D) with "" and then you can parse it to an int. Learn more about regex patterns from the documentation of java.util.regex.Pattern.
The problem can be solved in the following simple steps:
Split the sentence on space (which you have already done).
Create an int[] original and populate it with embedded numeric values from the resulting, String[] unordered.
Create a clone of original[] and sort the same. Let's say this clone is int[] order.
Populate a String[] ordered based on order[].
Join the elements of ordered[] on space.
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String words = "4of Fo1r pe6ople g3ood th5e the2";
String[] unordered = words.split(" ");
String[] ordered = new String[unordered.length];
int[] original = new int[unordered.length];
// Populate order with embedded numeric values
for (int i = 0; i < unordered.length; i++) {
original[i] = Integer.parseInt(unordered[i].replaceAll("\\D", ""));
}
// Create a clone of original[] and sort it
int[] order = original.clone();
Arrays.sort(order);
// Populate ordered[] based on order[]
for (int i = 0; i < order.length; i++) {
for (int j = 0; j < original.length; j++) {
if (order[i] == original[j]) {
ordered[i] = unordered[j];
break;
}
}
}
// Join the elements of ordered[] on space
String result = String.join(" ", ordered);
System.out.println(result);
}
}
Output:
Fo1r the2 g3ood 4of th5e pe6ople
Just remove all non-numeric characters (by using regex replacement) and then parse the resulting value to an integer.
for (int i = 0; i < unordered.length; i++){
String wordNum = unordered[i].trim().replaceAll("\\D+", "");
int correctIndex = (Integer.parseInt(wordNum)) - 1;
order[correctIndex] = unordered[i];
}
NumberFormatException is thrown when
The input string provided might be null. Example-
Integer.parseInt(null);
The input string might be empty. Example-
Integer.parseInt("");
The input string might be having trailing space. Example-
Integer.parseInt("123 ");
The input string might be having a leading space. Example-
Integer.parseInt(" 123");
The input string may be alphanumeric.Example-
Long.parseLong("b2");
There are other reasons also. You are trying to pass unordered[i] in parseInt.
int correctIndex = (Integer.parseInt(unordered[i].trim())) -1;
It is an alphanumeric String. So the compiler gives NumberFormatException.
Try using this function to calculate the index instead.
//Method to find the correctIndex
static int findIndex(String s)
{
char ch;
//Access all the characters of the String and the find the digit
for (int i = 0;i < s.length();i++)
{
ch = s.charAt(i);
if (Character.isDigit(ch))
{
return ch-49; //Convert the character to index
}
}
return -1;
}
I am trying to take the input and if there is an # symbol in the input then it finds the maximum of the integers before and after the # symbol. The maximum part I have no problem with but I do not know how to access and find the values before and after the # symbol.
import java.util.Scanner;
public class Max_Min {
public static void main(String[] args) {
//gets keyboard
Scanner keyboard = new Scanner(System.in);
//puts input into string
String inputString = keyboard.nextLine();
//splits string between characters
String[] splitInput = inputString.split("");
for (String s : splitInput) {
if(s.equals("#")){
//computes the maximum of the two integers before and after the #
}
}
//close keyboard
keyboard.close();
I did do a search to find something simliar (and im sure there is something) but could not find anything. If someone could help that would be great!
Try with this:
for (int i = 0; i < splitInput.length; i++){
if (splitInput[i].equals("#") && i != 0 && i != splitInput.length -1){
int max = Math.max(Integer.parseInt(splitInput[i - 1]), Integer.parseInt(splitInput[i + 1]));
}
//...
}
You could try:
String[] splitInput = inputString.split("#");
which would split your string at the #s.
Then you can do a iteration over your splitInput array and do a .length on each index.
You have written the simple for loop, with which you can only access the string, but not its index in the array. If you had the index, you could write:
int possibleMax = Integer.parseInt(splitInput[i - 1]) + Integer.parseInt(splitInput[i + 1]);
To get the index, there are two ways:
for (int i = 0; i < splitInput.length; i++) {
String s = splitInput[i];
...
}
Or:
int i = 0;
for (String s : splitInput) {
…
i++;
}
I don't like either version because both are more complicated than absolutely necessary, in terms of written code. If you would use Kotlin instead of Java, it would be:
splitInput.forEachIndexed { i, s ->
…
}
In Java this could be written:
forEachIndexed(
splitInput,
(i, s) -> …
);
The problem in Java is that the code inside the … cannot update the variables of the enclosing method. I'm not sure whether this will ever change. It would be possible but needs a lot of work by the language committee.
A simple way to do this would be
String input = "12#23";
String [] arr = input.split("#");
if (arr.length == 2) {
System.out.println("Max is "+Math.max(Integer.valueOf(arr[0]),Integer.valueOf(arr[1])));
}
Heres my code that takes a string and returns an array of the ascii values for each character in the array in order. Compile error is 'array required, but java.lang.String found'
public class Q1E {
int[] stringToCodes(String characters){
int characterLength= length(characters);
int[] array=new int[characterLength];
for(int i=0;i<characterLength;i++) {
array[i] =(int) characters[i];
}
}
}
You can't use array syntax on a String, use character.charAt(i)instead. Also, you need to return the array at the end.
Java uses Unicode/UTF-16 for strings, not ASCII.
If want to restrict your method to processing characters in the ASCII range, it should throw an exception when it encounters one outside that range.
If you want a sequence of "character codes" (aka codepoints), you have to use the String.codePointAt() at method. Because String holds a counted sequences of UTF-16 code-units and there might be one or two code-units per codepoint, you only know that String.length() is an upper bound of the number of codepoints in advance.
public class Q1E {
int[] stringToCodes(String s) {
int[] codepoints = new int[s.length()]; // there might be fewer
int count = 0;
for(int cp, i = 0; i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
// for debugging, output in Unicode stylized format
System.out.println(String.format(
cp < 0x10000 ? "U+%04X" : "U+%05X", cp));
codepoints[count++] = cp;
}
int[] array = java.util.Arrays.copyOf(codepoints, count);
return array;
}
}
Try it with this Wikipedia link on an English word:
stringToCodes("http://en.wikipedia.org/wiki/Résumé");
Your code appears to have a few bugs, it's String#length() and I would suggest you add a null check. Finally (since characters isn't an array), I think you want to use String#charAt(int)
int[] stringToCodes(String characters) {
int characterLength = 0;
if (characters != null) {
characterLength = characters.length();
}
int[] array = new int[characterLength];
for (int i = 0; i < characterLength; i++) {
array[i] = characters.charAt(i);
}
return array;
}
Of course, you could shorten it with a ternary
int characterLength = (characters != null) ? characters.length() : 0;
int[] array = new int[characterLength];
try this:
public class Test {
public static void main(String[] args) {
int []ascii=stringToCodes("abcdef");
for(int i=0;i<ascii.length;i++){
System.out.println(ascii[i]);
}
}
public static int [] stringToCodes(String characters){
int []ascii=new int[characters.length()];
for(int i=0;i<characters.length();i++){
ascii[i]=(int)characters.charAt(i);
}
return ascii;
}
}
Just simple reverse string method.
FYI, correct methods are reverseString1 and reverseString2,
but revereStirng3() doesn't give me correct output.
I think this is because of method args and return values are stored in the Stack and related with this concept. But I don't clearly understand why revereStirng3() doesn't work correctly.
Please let me know whey this is not working.
This is what I understand, and please correct me if I'm wrong.
1. main() calls revereStirng3(A) where this passing argument array A is stored in the stack frame for the main().
revereStirng3(char[] A) where this passed argument array A is stored in revereStirng3's method frame which means main's A[] is copied to revereStirng3's stack frame's method argument A[].
After reverse, revereStirng3 creates new String(A) for return String.
Then, I thought, in the main, returned new String(A) is correctly print reversed string, but actually not.
// Given a string "abcdef", reverse it. so output should be "fedcba"
import java.util.*;
public class ReverseString {
static String revereStirng3(char[] A) {
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
return new String(A);
}
static void revereStirng1(char[] A) {
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
}
static String revereStirng2(String str) {
char[] A = str.toCharArray();
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
return String.valueOf(A);
}
public static void main(String[] args) {
String s = "abcdef";
char[] A = s.toCharArray();
System.out.print( revereStirng3(A) + "\n" ); **// print out "abcdef"**
System.out.println( "" );
revereStirng1(A); // print out "fedcba"
for(int i=0; i<A.length; i++)
System.out.print( A[i] );
System.out.println( "" );
System.out.print( revereStirng2(s) + "\n" ); // print out "fedcba"
System.out.println( "" );
}
}
Ok, given that zenbeni has got the real results, here is what is happening.
An array in Java is an object, so in revereString1 and revereString3 you get a copy of the reference to the array. So, your changes modify the original array, which (after the first method execution) has been reversed. Of course, the second execution reverses it again, so you get the reverse of the reverse, which is the original String.
Try using a new, locally defined array to create the reversed String and everything will work fine.
From apache commons:
StringUtil.reverse(str);
I have copied your method and executed it
System.out.println(revereStirng3("abcdef".toCharArray()));
on the result was
fedcba.
The problem is located in the main function:
public static void main(String[] args) {
String s = "abcdef";
char[] A = s.toCharArray();
System.out.println( revereStirng3(A)); // print out "abcdef"**
revereStirng1(A);
System.out.print(Arrays.toString(A)); // print out "fedcba"
System.out.println(revereStirng2(s)); // print out "fedcba"
}
Your comments do not show the true.
The valid output for it would be
fedcba
[a,b,c,d,e,f]
fedcba
And this is because you operate on the same array for three test cases. In the second step you pass allready reversed array as input. This results that the order has not changed.
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();
}