When I am printing contents of a string array the output is printing 'null' as well. I am not sure what's wrong with this. Here is the output, what I expect is the output without 'null'
null(wa?>=0)nullnull*(wo?>=0)nullnull*(4*wa?+7*wo?>=50)nullnull*(d1=10)nullnull*((d2=1)+(k=2))nullnull
Thanks and appreciate your help. I would say my skill in Java in beginner level and I started two weeks back.
Here is the actual code:
String[] arrStr = new String[50];
int countStr = 0;
for (int i = 0; i < para.length; i++) {
if (para[i] == '(') {
count = count + 1;
}
if (para[i] == ')') {
count = count - 1;
}
if (count > 0) {
arrStr[countStr] = arrStr[countStr] + para[i];
} else {
if (para[i] == ')') {
arrStr[countStr] = arrStr[countStr] + para[i];
countStr += 1;
} else {
countStr += 1;
arrStr[countStr] = arrStr[countStr] + para[i];
// System.out.println(para[i]);
}
}
}
System.out.println(countStr);
for (int i = 0; i < countStr; i++) {
System.out.print(arrStr[i]);
}
Before this part, I am reading the following string from a word document:
(wa?>=0)AND(wo?>=0)AND(4*wa?+7*wo?>=50)AND(d1=10)AND((d2=1)+(k=2))
I think the problem may be due to the line:
arrStr[countStr] = arrStr[countStr] + para[i];
Since arrStr[countStr] is null initially and I add an element to it, it saves it as null+para[i]. Do you think it is possible?
Like when I try: System.out.println(arrStr[0]); I get the output as
null(wa?>=0)
System.out.println(null + "Bla");
prints nullBla. A null represented as String is "null". The issue here is that initially all your String[] is made of null. You need to initialize them first. Typically,
Arrays.fill(arrStr, "");
Should do.
If any element in arrStr is null while printing, it will print that faithfully.
Without knowing specifics in your code, you can either ensure that no element in your array becomes null (ensure that the lengths match up and you're not skipping element in arrStr, or check for null before printing the element.
You don't initialize the values of the arrStr array, you just allocate size for it, so each element of the array is null. When you assign a value to an element of the array, you concatenate its value (which is null) with the value of para[i].
You should initialize your array before using it:
String[] arrStr = new String[50];
for (int i = 0; i < arrStr.length; i++) {
arrStr[i] = "";
}
Related
I am having one problem that is preventing my entire code from working. It is having an array index out of bounds error, but it matches the file array perfectly, so I'm not sure what the problem is..
public void Menu() {
prompt.welcomeMsg();
prompt.nGramOptionMsg();
String userInput = input.next();
while (userInput.charAt(0) != 's' || userInput.charAt(0) != 'S') {
if (userInput.charAt(0) == 'n' || userInput.charAt(0) == 'N') {
prompt.nGramLengthMsg();
int userIntut = input.nextInt();
nGram = new NGram(userIntut);
prompt.fileUpload();
String userFilePut = input.next();
FileOpener file = new FileOpener(userFilePut);
String[] fileArray = file.openFile();
for (int i = 0; i < fileArray.length; i++) {
String[] splitedFileArray = fileArray[i].split("\\s+");
list.add(splitedFileArray[i]);
}
String[] listToStringArray = (String[]) list.toArray(new String[0]);
String[] nGrams = nGram.arrayToNGram(fileArray);
for (int i = 0; i < nGrams.length; i++) {
Word word;
if (!hashMap.containsKey(nGrams[i])) {
word = new Word(nGrams[i], 1);
hashMap.put(word.getNGram(), word);
} else {
Word tempWord = hashMap.remove(nGrams[i]);
tempWord.increaseAbsoluteFrequency();
hashMap.put(tempWord.getNGram(), tempWord);
}
}
HashMapFiller fill = new HashMapFiller();
fill.hashMap(hashMap);
fill.print();
prompt.goAgain();
}
}
The problem occurs when the list.add is trying to add the splitedFileArray. I tried doing fileArray.length-1 but it had a similar error, except -1.
The root cause for this problem is that you are trying to access the array in following line. What actually happening in behind the scenes is that you actually try to access unknown sized array which is returned from the split() method. returned array size might be less than the defined index (in your case i).
list.add(splitedFileArray[i]);
You can resolve this problem as follows..
for (int i = 0; i < fileArray.length; i++) {
String[] splitedFileArray = fileArray[i].split("\\s+");
list.addAll(Arrays.asList(splitedFileArray));
}
Hope this answer will help you to resolve your problem...
I'm trying to get all of the indexes of a Boolean array to be printed out where its element is true. The end goal is to be able to find a prime number of the indexes (where I change each index number that isn't prime to false in the array) then print out only what is left of the prime numbers of the indexes of the array.
The very first step I'm just trying to do is at least to get some integer index to print out, but nothing seems to be working and I don't know what is wrong.
public class PriNum{
private boolean[] array;
public PriNum(int max){
if (max > 2){ //I don't have any problems with this if statement
throw new IllegalArgumentException();
}
else{
array = new boolean[max];
for(int i = 0; i < max; i++){
if(i == 0 || i == 1){ //Automatically makes 0 and 1 false
//because they are not prime
array[i] = false;
}
else{
array[i] = true;
}
}
toString(); //I know for sure the code gets to here
//because it prints out a string I have
// there, but not the index
}
}
public String toString(){
String s = "test"; //this only prints test so I can see if
//the code gets here, otherwise it would just be ""
for (int i = 0; i < array.length; i++){
if(array[i] == true){
s = s + i; //Initially I tried to have the indexes returned
//to be printed and separated by a comma,
//but nothing comes out at all, save for "test"
}
}
return s;
}
}
EDIT: Included is the driver class that's requesting the print of the class PriNum
class Driver{
public static void main(String [] args){
PriNum theprime = null;
try{
theprime = new PriNum(50);
}
catch (IllegalArgumentException oops){
System.out.println("Max must be at least 2.");
}
System.out.println(theprime);
}
}
I tried running this, and the first change that needs to happen is to set this argument:
if(max < 2)
Then, if I'm reading this correctly: 0 and 1 are false. Every index after that is true. The output is fine as I see it. Just all the numbers crunched as a continuous list.
To get a better output, put a space between indexes:
if(array[i] == true){
s = s + " " + i;
}
You may even just output to screen directly as
if(array[i])
System.out.print( i );
numbers is initialized without declaration, array is declared but not initialized anywhere in your code. You have also a syntax error after array[i] = true, should be curly brace...
The code below is a simplified version of a method I am working on for a java project. The method will sort through a list of items(two different categories), in this case 0,s and 1's. The code reads through an array of numbers stops at either 0 or 1 and then prints out both the 0 or one and the string of numbers following the 0 or 1. If a preceding string is a 1 or a zero then it will stop and switch to another if statement. However it only executes each statement once. However there is more in the array that it needs to read through and organize. I would like to set up some sort of loop so that it loops through the set of if statements until it has read through the entire array.
public class tester
{
public static void main(String[] args )
{
String flags[] = {"0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i,j,k,h;
int count = 0;
for (i = 0; i<flags.length; i++)
{
if (flags[i].equals("0"))
{
for (j=0; !flags[j].equals("1") ; j++)
{
count = j+1;
array[j] = flags[j];
zeros[j] = flags[j];
}
} else
if (flags[count].equals("1"))
{
j = 0;
for(k=count; !flags[k].equals("0");k++)
{
array[k] = flags[k];
j++;
ones[j-1] = flags[k];
}
}
}
for(i=0; i<zeros.length; i++)
{System.out.println(zeros[i]);}
System.out.println();
for(i=0; i<ones.length; i++)
{System.out.println(ones[i]);}
}
}
What it prints out now:
0
23
25
34
null
null
null
null
null
null
null
null
1
9
12
13
null
null
null
null
null
null
null
null
String flags[] = {"9","0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i;
boolean addingZeroes = false;
boolean addingOnes = false;
int zeroCount = 0;
int onesCount = 0;
for (i = 0; i<flags.length; i++) {
if (flags[i].equals("0")) {
zeros[zeroCount] = flags[i];
zeroCount++;
addingZeroes = true;
addingOnes = false;
} else if (flags[i].equals("1")) {
ones[onesCount] = flags[i];
onesCount++;
addingZeroes = false;
addingOnes = true;
} else if (addingZeroes) {
zeros[zeroCount] = flags[i];
zeroCount++;
} else if (addingOnes) {
ones[onesCount] = flags[i];
onesCount++;
}
}
for(i=0; i<zeroCount; i++) {
System.out.println(zeros[i]);
}
System.out.println();
for(i=0; i<onesCount; i++) {
System.out.println(ones[i]);
}
Hey, couple things were wrong. Basically, you need a little state machine where you need to know whether you are in the midst of storing the sequence after a 1 or a 0. I used the boolean values (eg addingZeroes) for that.
Then, you need to separately keep track of your element count (eg zeroCount) for each of the storage arrays. You might have 20 digits after a 0 and just 2 after a 1.
Finally, at the end, your length of your storage arrays is not what you want - you want the amount of values you ended up storing. That's why you got all those "nulls".
One other thing I noticed is that your j value is initialized always to 0 in the 0 block, so you would always be using the lowest values of the start array.
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 am needed find number of mismatching characters between two strings. Currently i m doing it by converting strings into char Arrays and comparing element by element.
Is there any other way to achieve above requirement.
Note: consider string as lower case
Inputs :
input
utput
Output :
2
StringUtils in Apache commons.lang has a method for getting the Levenshtein distance of two strings.
If the two string are of different size the following code you return the total mismatch of alphabets.
You can try this -
String ip1 = "input"; // input1
String ip2 = "utput"; // input2
int count = 0; // difference in string
String ipx2 = ip2;
for (int j = 0; j <= ip2.length(); j++) {
int value = ip1.indexOf(ipx2);
if (value != -1) {
if (("").equals(ipx2)) { // if the second string is blank after continous reducing
count = ip1.length() + ip2.length();
} else {
count = ip1.length() + ip2.length() - 2 * ipx2.length();
}
break;
} else {
count = ip1.length() + ip2.length(); // if there is no match at all
}
ipx2 = ip2.substring(j);
}
System.out.println("" + count);
}
You will have to check whether the inputs have some data or not. I have not done that check.
This is the way you are describing, but it is the simplest way of implementing:
int counter = 0;
for(int i = 0; i < str1.length(); i++) if(str1.charAt(i) != str2.charAt(i)) counter++;
They can be fit on just two lines of code, without explicitly creating a whole new character array.