ArrayList and Loop - java

ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
int num2 = 0;
while (num<5){
gradeN.get(0).concat("*");
num2++;
}
System.out.println(gradeN.get(0));
This is not working.
I want output like this:
one*****
and do this in a loop..

There are 2 mistakes in your code:
The variable incremented in your while loop is different to the one used in the condition.
Strings are immutable. String.concat returns a different String object and does not modify the original String. That means the value in your List is not modified. To fix this, use List.set to replace the old value in the list with a new one.
int num2 = 0;
while (num2 < 5) {
String newValue = gradeN.get(0).concat("*");
gradeN.set(0, newValue);
num2++;
}

Your question is somewhat unclear. Do you always want to add 5 stars to the string? If so, a constant string with 5 stars in it makes more sense than a loop. And I assume you really meant to do this for every element of gradeN? So something like this:
ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
for (int i = 0; i < gradeN.size(); i++) {
gradeN.set(i, gradeN.get(i) + "*****");
System.out.println(gradeN.get(i));
}
If the number of stars added may vary and you really wanted to append them in a loop, then you could use StringBuilder to build it up:
ArrayList<String> gradeN = new ArrayList<String>();
gradeN.add("one");
gradeN.add("two");
int num = 5;
for (int i = 0; i < gradeN.size(); i++) {
StringBuilder stars = new StringBuilder(gradeN.get(i));
for (int j = 0; j < num; j++) {
stars.append('*');
}
gradeN.set(i, stars.toString());
System.out.println(gradeN.get(i));
}

One solution is to get the value of gradeN.get(0) on every loop and append * to it.
i.e.:
int num2 = 0;
while (num2<5){
gradeN.set(0, gradeN.get(0)+"*");
num2++;}
Output:
one*****
Demo:
http://ideone.com/XQvWqX

Related

How to retrivew elements of an Array of unkown size in android studio

I have created an app which will find the common factors of 2 or more numbers entered by the user. I have used a single Edit Text field to get user input. Different numbers are separated by comma (,). All the numbers are stored in an array.
My question is that how can I access the elements of the array of n size. Following is the code. I want to find the factors of all the user entered numbers. I can find the the factors of integernumbers[0] index but after that the code thorws ArrayIndexOutOfBoundsException.
int factors1 = 0;
int factors12 = 0;
StringBuilder sb = new StringBuilder();
String value = edtCommonFact.getText().toString()
String[] stringsNumber = value.split(",");
Integer[] integersNumbers = new Integer[stringsNumber.length];
for (int i = 0; i<stringsNumber.length; i++){
integersNumbers[i] = Integer.parseInt(stringsNumber[i]);
}
Arrays.sort(integersNumbers);
for (int i = 1; i<=integersNumbers[0]; i++){
if (integersNumbers[0]%i == 0){
factors1 = i;
sb.append(factors1).append(" ");
for (int j = 1; j<=integersNumbers.length; j++){
if (integersNumbers[j]%j == 0){
factors12 = j;
sb.append(factors12).append(" ");
}
}
}
}
String result = sb.toString();
commonFactResult.setText("Common factors are: " + result);
Thanks in Advance
You can use ArrayList because not like an array it doesn't need a size declaration. As an example if we wants an String array with size 10 we need to declare it as
String[] s = new String[10]
but in ArrayLists you can define the ArrayList and use it for any no of items.
List<String> s = new ArrayList<>()

display array values in one jlabel

I would like display the values of my String array in one Jlabel.
I've tried with a loop (for) but, the result is the new letter overwrites the previous.
I do not understand how I could displaying the letters following.
labelWord is the variableName of my Jlabel.
String myArray[] = new String[4];
myArray[0] = "h";
myArray[1] = "e";
myArray[2] = "l";
myArray[3] = "l";
myArray[4] = "o";
and my loop :
for (int j = 0; j <= myArray.length; j++) {
labelWord.setText(myArray[j]);
}
You are replacing the text each time you call labelWord.setText().
Just build the whole string before you set it
StringBuilder builder = new StringBuilder();
for (int j = 0; j <= myArray.length; j++) {
builder.append(myArray[j]);
}
labelWord.setText(builder.toString());
Your code does not work because you set the label value with the 1st String, then the second one, then the 3rd one... You need to concatene all your String into one then set the label text with this value:
String value ="";
for (int j = 0; j <= myArray.length; j++) {
value += myArray[j];}
labelWord.setText( value );
Note: you can also use a StringBuilder instead of concatenating directly to the String.
You are overwriting it yourself by calling setText() everytime in loop. you need to append it to the text by doing:
labelWord.setText(labelWord.getText() + myArray[j]);
Hope this helps.
The easiest way to do this without using StringBuilder or anything like that would be to use another string variable
String myLabelText = "";
for (int j = 0; j <= myArray.length; j++) {
myLabelText = myLabelText + myArray[j];
}
labelWord.setText( myLabelText );
You were essentially just changing the value of the label for every item in the array, not adding it to the end
One More Interesting Way you would like to know(In your CASE)
String arr[]={"h","e","l","l","o"};
System.out.println(Arrays.toString(arr).replaceAll("[\\]\\[,\\s]", ""));
OUTPUT
hello
So directly,
jlabel.setText(Arrays.toString(arr).replaceAll("[\\]\\[,\\s]", ""));
NOTE:
This will not be applicable if array elements contains space(Sorry for that).

Java loop output keep on repeating

String[] month = {"Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"};
int[] monthArray = new int[12];
String[][] itemArray = new String[12][10];
Variables
monthArray[i] = input.nextInt();
itemArray[monthArray[i]-1][e] = input.next();
Store a maximum of 5 String values on user input's month.
for(int i=0;i<e;e++){
System.out.println(itemArray[monthArray[i]-1][i]);
}
Having a problem displaying the String values (it just keep repeating the first String value) under user input's month.
You are increasing e instead of i in the last loop. e is the limit and not the variable you use for the iteration and thus the loop will not terminate until you overflow int.
for(int i = 0; i < e; i++ /* Note the usage of i here*/) {
use i++ instead of e++
here e stands for the limit
and i stands for the variable.
Since you have a 2D array, maybe you want something more like this, to print out the values, once, the array has been populated.
String[][] itemArray = new String[12][10];
for(int i = 0; i < itemAreray.length; i++){
for (int j = 0; j < itemArray[i].legnth; j++){
System.out.println(itemArray[i][j]);
}
}
Unless you're having difficulty populating the array. Then that's a different problem

How do you add two int arrays with different lengths?

I've been working on a Java lab that wants us to have the user enter two digits up to 50 digits long and add them together. I've successfully been able to complete everything except for when the two arrays have a different length. I've been toying around with the code for a while, but I keep coming up short. Can anyone look at the code for this and have any suggestions? Thanks!
int[] number1 = new int[input1.length()];
int[] number2 = new int[input2.length()];
int[] answer = new int[input1.length()];
if(number1.length > number2.length){
number2 = new int[number1.length];
for(int i = 0; i < number2.length - number1.length; i++){
number2[i] = 0;
}
}
if(number2.length > number1.length){
number1 = new int[number2.length];
for(int i = 0; i < number1.length - number2.length; i++){
number1[i] = 0;
}
}
Whenever I add, say 120 and 12, it says there's an Array out of bounds error.
First thing you need to do is get the numbers into an int array. Do that by Splitting string to char array. Then convert to int array. Then add.
String input1 = scanner.nextLine().trim(); <-- get input as String
String input2 = scanner.nextLine().trim();
char[] array1 = input1.toCharArray(); <-- split to char array
char[] array2 = input2.toCharArray();
// convert to int array
int[] intArray1 = new int[array1.length]; <-- declare int array
int[] intArray2 = new int[array2.length];
for (int i = 0; i < array1.length; i++){
intArray1[i] = Integer.parseInt(String.valueOf(array1[i])); <-- convert to int
}
for (int i = 0; i < array2.legnth; i++){
intArray2[i] = Integer.parseInt(String.valueOf(array2[i]));
}
// check which one is larger and add to that one
if (intArray1.length > intArray2.length){
for (int i = 0; i < intArray2.length; i++){
intArray1[i] += intArray2[i]; <-- add values
}
System.out.println(Arrays.toString(intArray1); <-- print largest
} else {
for (int i = 0; i < intArray1.length; i++){
intArray2[i] += intArray1[i];
}
System.out.println(Arrays.toString(intArray2);
}
If you want to get the number representation printed instead of an array, instead of the System.out.println(), use this
StringBuilder sb = new StringBuilder();
for (int i : intArray1){
sb.append(String.valueOf(i));
}
System.out.println(sb.toString());
So 123 and 12 will print out 233
My understanding of your code is, you try to pre-append (push from head) 0s to the shorter array. Look at the first if-block. The length of number1 is larger than what of number2. Thus, number2.length - number1.length is negtive. Then, in the for loop, i < number2.length - number1.length is always ture. (I am not familiar with java. I guess array's length is an integer.) And you still have to copy the rest of array.
The correct code should be,
if(number1.length > number2.length) {
int[] number3 = new int[number1.length];
for(int i = 0; i < number1.length - number2.length; ++i) {
number3[i] = 0;
}
for(int i = 0; i < number2.length; ++i) {
number3[i + number1.length - number2.length] = number2[i];
}
number2 = number3;
}
BTW, the second if-block should be changed in a similar way. Perhaps, java provides an API link insert(0, 0) for array object. It will be easier to implement.

Efficient methods for Incrementing and Decrementing in the same Loop

Suppose some situations exist where you would like to increment and decrement values in the same for loop. In this set of situations, there are some cases where you can "cheat" this by taking advantage of the nature of the situation -- for example, reversing a string.
Because of the nature of building strings, we don't really have to manipulate the iterate or add an additional counter:
public static void stringReversal(){
String str = "Banana";
String forwardStr = new String();
String backwardStr = new String();
for(int i = str.length()-1; i >= 0; i--){
forwardStr = str.charAt(i)+forwardStr;
backwardStr = backwardStr+str.charAt(i);
}
System.out.println("Forward String: "+forwardStr);
System.out.println("Backward String: "+backwardStr);
}
However, suppose a different case exists where we just want to print a decremented value, from the initial value to 0, and an incremented value, from 0 to the initial value.
public static void incrementAndDecrement(){
int counter = 0;
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(counter);
counter++;
}
}
This works well enough, but having to create a second counter to increment seems messy. Are there any mathematical tricks or tricks involving the for loop that could be used that would make counter redundant?
Well it looks like you just want:
for(int i = 10; i >= 0; i--){
System.out.println(i);
System.out.println(10 - i);
}
Is that the case? Personally I'd normally write this as an increasing loop, as I find it easier to think about that:
for (int i = 0; i <= 10; i++) {
System.out.println(10 - i);
System.out.println(i);
}
Note that your string example is really inefficient, by the way - far more so than introducing an extra variable. Given that you know the lengths involved to start with, you can just start with two char[] of the right size, and populate the right index each time. Then create a string from each afterwards. Again, I'd do this with an increasing loop:
char[] forwardChars = new char[str.length()];
char[] reverseChars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
forwardChars[i] = str.charAt(i);
reverseChars[reverseChars.length - i - 1] = str.charAt(i);
}
String forwardString = new String(forwardChars);
String reverseString = new String(reverseChars);
(Of course forwardString will just be equal to str in this case anyway...)
You can have multiple variables and incrementers in a for loop.
for(int i = 10, j = 0; i >= 0; i--, j++) {
System.out.println(i);
System.out.println(j);
}

Categories