java android string and integer functions dont work - java

Hi I'm not sure if this is a problem with Eclipse or Java but recently my code has stopped working. I only changed things like assigning new variables to store things. My program takes a multi-dimensional string array and should return a new array trimmed of nulls.
public void makebuttons(final int n, String equals) {
//does lots of widget functions and id assignments
String[] items=getArray(Integer.parseInt(data.equnits.substring(n*3, n*3+1)));
unitvalues[n]=Integer.parseInt(data.equnits.substring(n*3, n*3+1));
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item, items);
//does more code
}
public static String[] getArray(int selection) {
String[] result;//stores the new array
int x=0,j=0 ,ulength = data.units[0].length;//ints used
String temp="";
while(j < ulength && temp!=null) {
temp= data.units[selection][j][0]; //find the actual array length
j++;
}
if(j==ulength)j--;
result = new String[j+1];//initalise array from check
for(x=0; x<=j; x++) { //add data to array
result[x]=data.units[selection][x][0];
}
return result;//return corrected array
}
Integer.parseInt and Integer.valueOf give value of 0 each time for a string like "01,02,03,04" data.equnits stores the string to be converted to integer by checking 2 digits only to select from a large 3 dimensional array. Since its a 3 dimensional array some nulls are present
Null check for the String doesnt seem to work since the while loop doesnt seem to detect it and it ends up being in the array that gets passed into the array adapter for spinner causing NullPointerException while scrolling.
Restarting eclipse doesn't help.

I can't help with your first problem without more information, but this seems to be the issue with your second:
The function substring is inclusive of the first parameter and exclusive of the second. Since you are only adding 1 to the n*3, you only get one character.
Try using:
substring(n*3, n*3+2)
Edit:
Adding the updated code from my comment above:
while(j < ulength && temp != null && !temp.isEmpty())
{
temp = data.units[selection][j];
j++;
}

Related

Adding elements dynamically in String array but index 0 showing null?

I want to add some values in string array dynamically by using for loop.
when i debug the code at first for loop it is showing values which are adding.I want to check if any one of the string equals to my given value.but in for loop 2 at index 0 it showing null and at index 1 it showing the string value.
for(int i=0;i<someval;i++) {
String[] mylist = new String[someval];
mylist[i]=previousVal;
System.out.println("Previous Value : " +mylist[i]);
}
for (int j = 0; j <=mylist.length; j++) {
if (mylist[j].equals(givenValue) ) { {
System.out.println("your value found in the array");
}
}
The problem is that you are creating a new array using
mylist = new String...
during each loop iteration.
So, it doesn't really matter if you write something to an array, if the next step consists of throwing that array away.
In other words: make sure that you create the array just once; preferable before entering your loop.

Read and print sequences and print merged sequence

I suppose to write a Java program using array and method follows: It reads a sequence of strings, each on a separate line, and stores them in an array, let call it input1, with one string per cell, in the order they were read. The sequence ends with an empty line: one with a String of length 0. Same thing with 2nd sequence.Then prints the 1st sequence and 2nd sequence. And then create an array that contains all of the elements of the above two arrays. Merging is done by alternating between the arrays: that is, the first cell of input1 is copied followed by the first cell of input2. Then the second cell of input1 is copied followed by the second cell of input2. Of course, in general, the two sequences may have different lengths, so after the shorter sequence is finished, all elements of the longer sequence are simply appended to the output array. Finally, prints the merged array with 1 string each line.
import java.util.Scanner;
public class A4 {
public static void readInput(Scanner myScanner, String[] input) {
boolean streamEnded = false;
int index = 0;
while (!streamEnded && myScanner.hasNext()) {
String value = myScanner.nextLine();
if (value.length() == 0) {
streamEnded = true;
input[index] = value;
} else {
input[index] = value;
index++;
}
}
}
public static void main(String[] args) {
int size = 5;
String[] input1 = new String[size];
String[] input2 = new String[size];
String[] store = new String[size*2];
Scanner aScanner = new Scanner(System.in);
readInput(aScanner, input1);
for (int i = 0; i < input1.length; i++) {
System.out.println("input[" + i +"]" + input1[i]);
}
readInput (aScanner, input2);
for (int i = 0; i < input2.length; i++) {
System.out.println("input[" + i +"]" + input2[i]);
}
}
}
i still dont know how to merge those 2 inputs together.Can anyone show me how to do it? Thanks
Declare three arrays for sequence 1, sequence 2 and merged-sequence.
Use a variable whichToUse to store which array to be used and assign array1 to it before the while loop, then store values into array1 on the place of System.out.print, then when first reach value.length()==0 ('=' is not designed for comparing, it's a mistake in your code.), you change the whichToUse point to array2. When the second reach value.length()==0, end the reading loop. One place to be marked, declare streamEnded as a int to count how many times we reach the value.length()==0. Only exit loop while streamEnded==2.
Now you have two arrays which contains the values from file. Next step is to merge them. Use a for loop to iterate items in merged-sequence, and use loop-counter%2 to determine which array to read when assign value to merged-sequence items. after any of the array1 and array2 reaches the end, read the other array in the rest of loop.
As looks like you are new to Java, I think write code by yourself is much better than I provide the code to you. If you've any other question, just comment here.

How do I access and manipulate individual values in a String Array when using a while and for loop

Very new to Java: Trying to learn it.
I created an Array and would like to access individual components of the array.
The first issue I am having is how to I print the array as a batch or the whole array as indicated below? For example: on the last value MyValue4 I added a line break so that when the values are printed, the output will look like this: There has to be a better way to do this?
MyValue1
MyValue2
MyValue3
MyValue4
MyValue1
MyValue2
MyValue3
MyValue4
The next thing I need to do is, manipulate or replace a value with something else, example: MyValue with MyValx, when the repeat variable is at a certain number or value.
So when the repeat variable reaches 3 change my value to something else and then change back when it reaches 6.
I am familiar with the Replace method, I am just not sure how to put this all together.
I am having trouble with changing just parts of the array with the while and for loop in the mix.
My Code:
public static String[] MyArray() {
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
return MyValues;
}
public static void main(String[] args) {
int repeat = 0;
while (repeat < 7) {
for (String lines : MyArray()) {
System.out.println(lines);
}
repeat = repeat + 1;
if (repeat == 7) {
break;
}
}
}
Maybe to use for cycle to be shorter:
for (int i = 0; i < 7; i++) {
for (String lines : MyArray()) {
// Changes depended by values.
if (i > 3) {
lines = MyValx;
}
System.out.println(lines); // to have `\n` effect
}
System.out.println();
}
And BTW variables will start in lower case and not end withenter (\n). So use:
String myValues[] = {"MyValue1", "MyValue2", "MyValue3", "MyValue4"};
instead of:
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
and add System.out.println(); after eache inside cycle instead of this:
MyValues[n] = "value";
where n is the position in the array.
You may consider using System.out.println() without any argument for printing an empty line instead of inserting new-line characters in your data.
You already know the for-each loop, but consider a count-controlled loop, such as
for (int i = 0; i < lines.length; i++) {
...
}
There you can use i for accessing your array as well as for deciding for further actions.
Replacing array items based on a number in a string might be a bit trickier. A regular expression will definitely do the job, if you are familiar with that. If not, I can recommend learning this, because it will sure be useful in future situations.
A simpler approach might be using
int a = Integer.parseInt("123"); // returns 123 as integer
but that only works on strings, which contain pure numbers (positive and negative). It won't work with abc123. This will throw an exception.
These are some ideas, you might try out and experiment with. Also use the documentation excessively. ;-)

Determining if a given string of words has words greater than 5 letters long

So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒     You might want to use: +=
⇒     You might want to use: ==
⇒     You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)

Understanding Array Indexing in Java

I have a brief question about how Java handles arrays. Below is my code:
//import java.util.Arrays;
import static java.lang.System.out;
public class Arrays
{
public static void main(String[] args)
{
String [][] multiArray = new String[10][8];
int k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println ();
for (int i = 0; i < multiArray.length; i++)
{
for (int j = 0; j < multiArray[i].length; j++)
{
multiArray[i][j] = i + "" + j;
out.print ("| " + multiArray[i][j] + " ");
}
out.println ("|");
}
k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println();
}
}
I understand that you have to create a double "for" loop to print out values for both dimensions and that you have to have:
multiArray[i].length
so that it knows to reference the length of the second dimension. I just don't understand how it works.
What I'm confused about is this: At the very beginning of the program, directly after I declare my array, if I write a statement like:
system.out.println (multiArray.length);
It will print the value of 10, which is the length I declared in the first dimension. If I, however, create some random variable like "int a = 0" or "int idontgetthis = 0" and then I write:
system.out.println (multiArray[a].length);
it somehow knows to print the length of the second dimension, 8. So my question is, how does it know how to do this? It's killing me!! lol
Because multiArray is really an array of arrays. So multiArray[a] is a reference to an object. That object is itself an array. That array has a length (8), and a property called length which can be used to return that length.
Basically, it is a concept confusion, by doing:
String[] array;
you are declaring that you will have an array of Strings with an unknown lenght.
A call to: System.out.println(array.length) at this moment will fail with a compilation error because array is not yet initialized (so the compiler can't know how long it is).
By doing:
String[] array = new String[8]
you declare that you will have and array of String and initialize it, specifying it will have space for 8 Strings, the compiler then allocates space for this 8 Strings.
Something important to notice is that even when the compiler now knows that you will store 8 Strings in your array, it will fill it with 8 nulls.
So a call to System.out.println(array.length) at this point will return 8 (Compiler knows the size) but a call to System.out.println(array[1]) will return a Null Pointer Exception (You have 8 nulls in it).
Now, in the example you presented, you are declaring a bidimensional array, this is, an array that will contain other arrays.
Bidimensional arrays are initialized as String[][] multiarray = new String[10][8]; and the logic is the same as in simple arrays, the new String[10][8]; indicates the lenght of the array that contains the other arrays, and the new String[10][8]; indicates the length of the contained arrays.
So doing system.out.println(multiArray[x].length); after initializing multiarray is translated as "What is the length of the Xth contained array?", which the compiler, thanks to your initialization, now knows is 8 for all the contained arrays, even when they are full of nulls at the moment.
Hope it helps to add a bit more understanding!
You could try looking at it like this.
public class Arrays{
public static class EightStrings {
public String[] strings = new String[8];
}
EightStrings[] tenOfThem = new EightStrings[10];
}

Categories