Extending String Array - java

I have a String array defined and read some values from a table into it:
String[][] ssRet = null;
ssRet = new String[tblRoDe.getNumRows()+1][2];
ssRet[0][0] = "AGR_NAME";
ssRet[0][1] = "TEXT";
for(int j=0; j<tblRoDe.getNumRows(); j++ )
{
tblRoDe.setRow( j );
ssRet[j+1][0] = tblRoDe.getString( "AGR_NAME" );
ssRet[j+1][1] = tblRoDe.getString( "TEXT" );
logger.debug("------- Start Entry #" + (j+1) + " -------");
logger.debug(ssRet[0][0] + ": " + ssRet[j+1][0]);
logger.debug(ssRet[0][1] + ": " + ssRet[j+1][1]);
logger.debug("------- End Entry #" + (j+1) + " -------");
}
My task now is: depending on a function param I will have to read values from a different table into the same string array (append this). There are still only two columns but I have to add more lines.
How can I achieve that?

You will have problems when you stick with arrays, as they are fix in their size.
For a more dynamic solution you will need a Collection, such as List - this grow with the data.

Arrays cannot be expanded once created.
So, there are the following solutions.
Create array of needed size. You can achieve this if you know the array size before reading the data.
create new array once you have to "expand" it and copy data from the small array to the bigger one. Then continue to fill the bigger array. You can use System.arraycopy() or implement the logic yourself
Use any implementation of java.util.List instead of array.
BTW unless this is a school exercise avoid using 2 dimensional array in this case. I'd recommend you to define your custom class with 2 fields name and text and then use 1 dimensional array or list according to your choice.

If you have a different amount of Rows, and you can't excatly say how much rows it will be you should use ArrayList instead of an array with an fixed size. To an ArrayList you can add as muchs values as you want. The Problem is, that an Array, once it is created, cant be resized.
To this List you could save Objects of your own type(to handle your data) like this:
public class TableRow {
private String agr_name;
private String text;
private int entryNr;
public TableRow(String agr_name, String text, int entryNr) {
this.agr_name = agr_name;
this.text = text;
this.entryNr = entryNr;
}
public String getAgr_name() {
return agr_name;
}
public void setAgr_name(String agr_name) {
this.agr_name = agr_name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getEntryNr() {
return entryNr;
}
public void setEntryNr(int entryNr) {
this.entryNr = entryNr;
}
}
This used to your code should look like that:
ArrayList<TableRow> allRows = new ArrayList<>();
for (int j = 0; j < tblRoDe.getNumRows(); j++) {
tblRoDe.setRow(j);
TableRow trow = new TableRow(tblRoDe.getString("AGR_NAME"), tblRoDe.getString("TEXT"), j);
allRows.add(trow);
logger.debug("------- Start Entry #" + trow.getEntryNr() + " -------");
logger.debug("AGR_Name: " + trow.getAgr_name());
logger.debug("TEXT: " + trow.getText());
logger.debug("------- End Entry #" + trow.getEntryNr() + " -------");
}
Hope that helps!

You can't manipulate the array size after creating it , so Use List as it can grow and it's considered as a dynamic solution
List<List<String>> ssRet = new ArrayList<ArrayList<String>>();
List<String> temp=ArrayList<String>(); //creating temp list
temp.add("AGR_NAME");
temp.add("TEXT");
ssRet.add(temp);
for(int j=0; j<tblRoDe.getNumRows(); j++ )
{
tblRoDe.setRow( j );
temp.clear();//clear list instead of creating new one
temp.add(tblRoDe.getString("AGR_NAME"));
temp.add(tblRoDe.getString("TEXT"));
ssRet.add(temp);
}
To get the data :-
for(int i = 0 ; i < ssRet.size() ; i++){
for(int j = 0 ; j < ssRet.get(i).size() ; j++){
System.out.println("The "+(i+1) + " array data");
System.out.println(ssRet.get(i).get(j));
}
}

Related

Printing out values of different rows and column in 2d array using for loops

I have this 2d array of the first row being first names and the second being last names.
String[][] ladrones2 = {
{"Phil", "Kim", "Phil", "Perry"},
{"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};
the prefered out come of this would be to have them printend out like e.g
Phill Garcia
Kim Gimena
etc...
Now I was able to do this by catching the ArrayIndexOutOfBoundsException exception and it works and the output is:
name Phil Garcia
name Kim Gimena
name Phil Basinger
name Perry Ornitorrinco
Which is great but I wondered if there was a way to do this without having to catch the exception? I've been searching to make this cleaner but wasn't able to do so.
Code at the moment:
public static void robo2() {
String[][] ladrones2 = {
{"Phil", "Kim", "Phil", "Perry"},
{"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};
try {
for (int i = 0; i < ladrones2.length; i++) {
for (int j = 0; j < ladrones2[i].length; j++) {
System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("");
}
}
as you can see I used in the inner for loop a +1 on the i variable which in turn throws the exception.
Any ideas? I would like just to keep this way of working at the moment with 2 forloops due to being new to Java.
If you are sure that ladrones2 array always has 2 rows, then below code would be simpler:
public static void main(String[] args) {
String[][] ladrones2 = {
{"Phil", "Kim", "Phil", "Perry"},
{"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};
for (int i = 0; i < ladrones2[0].length; i++) {
System.out.println("name: " + ladrones2[0][i] + " " + ladrones2[1][i]);
}
}
On this line :
System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
You are taking an element from the first and second array at the same time but you are looping over all the elements in the sequence on this line :
for (int i = 0; i < ladrones2.length; i++)
To correct this problem, you simply have to reduce the range of i to ladrones.length-1, otherwise you will reach the end of the array and try to access the next element which doesn't exist here.
You'll end up with this line instead :
for (int i = 0; i < ladrones2.length-1; i++) {

I want to print a formatted array in java

I haven't been able to find any questions similar to my situation so I hope I'm not missing something.
I have an array of strings. I want to print every 3 strings on their own line with commas and spacing.
Here is my method:
public static void Modify(String stringSearch)
{
ArrayList<String> records = new ArrayList<String>();
try {
File file = new File("Temp.txt");
input = new Scanner(file);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
if (input.hasNext()) {
while (input.hasNext())
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
if ((Objects.equals(firstName, stringSearch)) || (Objects.equals(lastName, stringSearch)) || (Objects.equals(phoneNumber, stringSearch))) {
records.add(firstName);
records.add(lastName);
records.add(phoneNumber);
}
} // end while
}
int size;
size = (records.size()) / 3;
System.out.printf("Found %d records:%n", size);
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
}
I am converting an arrayList to a string array in order to try and format it. I'm very new to java and am working on a project in a time crunch.
I need it to print exactly like this:
Found 2 records:
1) Garcia, John 505-338-2567
2) John, Joseph 212-780-3342
It is printing like this:
Found 2 records:
GarciaJohn505-338-2567JohnJoseph212-780-3342
Java is an Object-Oriented language, and you should use it.
Create a class representing your Person, with firstName, lastName, and phoneNumber as fields.
Then you create a List<Person> with 2 objects in it, and write a method for printing that list. The System.out.printf() you're already using can help output values in columns like you want.
You probably need to create you own data-structure, with a toString() method that suits your needs.
Something like:
public class PersonalCustomerData {
private String firstName;
private String lastName;
private String phoneNumber;
...
#Override
public String toString() {
return lastName + "," + " " + firstName + " " + phoneNumber;
}
}
And, as #Andreas mentioned in his answer, you also need a Collection<PersonalCustomerData>, that when you iterate over it, you print your fully formatted output:
private Collection<PersonalCustomerData> col;
// init the collection + do stuff...
public void printCustomerData() {
int lineNumber = 0;
for(PersonalCustomerData pcd : col) {
lineNumber++;
System.out.println(lineNumber + ")" + " " + pcd);
}
}
If you don't want to use object to contain your values and stick with your plan of doing. you can use this code to print it with format.
Replace this:
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
to this:
int numberOfLine = 1; // Counter of words per line
String[] Array = records.toArray(new String[0]);
for(String str : Array) {
String strSperator = "";
switch (numberOfLine) {
case 1:
strSperator = ", ";
numberOfLine++;
break;
case 2:
strSperator = " ";
numberOfLine++;
break;
case 3:
strSperator = "\n";
numberOfLine = 1;
break;
}
System.out.printf("%s%s",str,strSperator);
}
replace this line
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);`
to something like this. I didn't test out the code so there might be small typos or what not. I think this will do what you want.
As Andreas said, it would be better if you make a person class. It will look more organized and probably easier to understand.
int counter = 1;
System.out.print(records.get(0) + ",\t")
while (counter !=records.size())
{
if(counter %3 ==0)
System.out.println(records.get(counter));
else if(counter% 3== 1)
System.out.print(records.get(counter) + ",\t");
else
System.out.print(records.get(counter)+ "\t");
counter ++;
}
Since your first element will always be first name , 2nd element will be last name and 3rd element is the phone number, I print the first one initially then the modding and the while loop should handle everything I believe.

Finding Largest String in ArrayList

// Im trying to find the largest String in my ArrayList and print it out and also to include what index the largest element resides at and to print that to screen too. Im just wondering where Im going wrong.
Thanks.
import java.util.Scanner;
import java.util.ArrayList;
public class ArraylistString
{
public static void main(String [] args)
{
// Instance of Scanner class
Scanner keyboardIn = new Scanner(System.in);
// Declare an array list of Strings
ArrayList<String> Str = new ArrayList<>();
// Add names to ArrayList
Str.add("Jim Bob");
Str.add("Bobby Jones");
Str.add("Rob Stiles");
int largestString = Str.size();
int index = 0;
// Use for loop to print out elements from ArrayList
for(int i = 0; i < Str.size(); i++)
{ // Test which String is the largest
if(Str[i].size() > largestString)
{
largestString = Str[i].size();
index = i;
}
}
// Output largest String and index it was found at
System.out.println("Index " + index + " "+ Str[index] + " " + "is the largest and is size " + largestString);
}
}
You can also use java.util.Collections.max or the Stream version:
Java 8
String max = Collections.max(strings, Comparator.comparing(String::length)); // or s -> s.length()
OR
String max = strings.stream().max(comparing(String::length)).get();
Prior Java 8
String max = Collections.max(Str, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
Then
System.out.println("Index " + arr.indexOf(max) + " " + max + " " + "is the largest and is size " + max.length());
Please try these code . Here i am trying with get() to access the ArrayList elements, which is working correctly.
import java.util.Scanner;
import java.util.ArrayList;
class ArraylistString
{
public static void main(String args[])
{
ArrayList<String> Str = new ArrayList<String>();
Str.add("Jim Bob");
Str.add("Bobby Jones");
Str.add("Rob Stiles");
int largestString = Str.get(0).length();
int index = 0;
for(int i = 0; i < Str.size(); i++)
{
if(Str.get(i).length() > largestString)
{
largestString = Str.get(i).length();
index = i;
}
}
System.out.println("Index " + index + " "+ Str.get(index) + " " + "is the largest and is size " + largestString);
}
}
You have the correct idea, but wrong syntax. In Java, only arrays support the [] syntax. An ArrayList isn't an array, it's a class that implements the List interface, and you should use the get method to access its members. Similarly, a String doesn't have a size() method, it has a length() method.
I would set your largestString variable to your first String that you add:
int largestString = Str.get(0).length();
Then you should use the following to check for the largest String:
if(Str.get(i).length() > largestString) {
largestString = Str.get(i).length();
index = i;
}
You cannot index into an ArrayList with [] as you were trying to do.
I would also suggest better variable names. If I saw Str as a variable I would think it was a String. Maybe try strList or something like that.
From Java-8 and onwards:
List<Integer> numList = Arrays.stream(Str).map(String::length).collect(Collectors.toList());
Integer m = numList.stream().mapToInt(i->i).max().orElse(4000); //get strings with their length
int k = numList.indexOf(m); //index of String with Maximum Length
System.out.println(Str.get(k)); //get your longest string
Using Java 8:
Optional<String> op = Str.stream().sorted((e1,e2)-> e1.length() > e2.length() ? -1 :1).findFirst();
What are you getting as output?
also, the line
int largestString = Str.size()
is setting largestString as the number of elements in the array Str so that may cause errors. I would set it to 0 or even -1 as a baseline, or maybe Str[0].size() so that you can start your for loop with your first element as your baseline.
EDIT:
I didn't even realize this was Java so like what people are saying, you cannot use the [] operator as you can in most languages and you should use string.length() not str.size()

Java array --> string, but .equals() not working (Or: is there an easier way to do this?)

I'm working on a program which takes in a file with the name of an item of produce, its type (Broccoli, Vegetable), and then another item and its type on a different line. It randomly takes 3 items and puts them in a "boxOfProduce" array. I turn that into a string separated by commas, and then that into a different list. I look at the items at indexes 1,3,5 to see if its a fruit or a vegetable and increase the according count.
But the count is staying at 0 and not increasing. What could I be doing wrong? Or is there an easier was to do this?
Random random = new Random();
String firstProduceType = produce[random.nextInt(size)];
String secondProduceType = produce[random.nextInt(size)];
String thirdProduceType = produce[random.nextInt(size)];
BoxOfProduce boxOfProduce = new BoxOfProduce(firstProduceType, secondProduceType, thirdProduceType);
String produceString = firstProduceType + ", " + secondProduceType + ", " + thirdProduceType;
String[] produceStringArray = produceString.split(",");
int fruitCount = 0;
int vegetableCount = 0;
System.out.println(produceStringArray);
if (produceStringArray[1].trim().equals("Fruit")) {
fruitCount += 1;
}
else if (produceStringArray[1].trim().equals("Vegetable")) {
vegetableCount += 1;
}
if (produceStringArray[3].trim().equals("Fruit")) {
fruitCount += 1;
}
else if (produceStringArray[3].trim().equals("Vegetable")) {
vegetableCount += 1;
}
if (produceStringArray[5].trim().equals("Fruit")){
fruitCount += 1;
}
else if (produceStringArray[5].trim().equals("Vegetable")) {
vegetableCount += 1;
}
EDIT: firstProduceType, secondProduceType, and thirdProduceType are entirely random, so they'll be (item, type).
Try lowercasing everything as well. Equals works if strings are equal
Also you can use
String[] produceStringArray = {firstProduceType, ...};
Should be more safe
Also I think it should be produce[random.nextInt(size-1)];
As indexing starts from 0

Java String format

I am trying to create an array of Strings to use with JList, I have a array of objects from my Book class which contains the Author name, Tittle etc... But when I use string.format and send it to my JList the text doesn't come out aligned like when I use system.out.format.
Code:
final static String FORMAT = "|%1$-25s|%2$-25s|$%3$-10.2f|%4$-15s|%5$-13s|\n";
static String[] createStringList(Book[] dataBase)
{
String[] list = new String[dataBase.length];
for (int i = 0; i < dataBase.length; i++)
{
list[i] = String.format(FORMAT, dataBase[i].getTittle(), dataBase[i].getAuthor(),
dataBase[i].getBookPrice(), dataBase[i].getNumberInStock(),
dataBase[i].getISBNNumber());
}
return list;
}
static void printout(Book[] dataBase)
{
System.out.println(" Tittle" + "\t" + " Author" + "\t" + " Price" + "\t" + "Number In Stock" + "\t" + " ISBN Number");
System.out.println("_____________________________________________________________________________________________");
for (int i = 0; i < dataBase.length; i++)
{
System.out.format(FORMAT, dataBase[i].getTittle(), dataBase[i].getAuthor(),
dataBase[i].getBookPrice(), dataBase[i].getNumberInStock(),
dataBase[i].getISBNNumber());
}
}
Result Screenshot:
As you can see, the print method aligns it fine but when I try to send it to my JList it messes up even though I am using the same code. How would I go about aligning it? I have tried playing with the values in String format = "|%1$-25s|%2$-25s|$%3$-10.2f|%4$-15s|%5$-13s|\n"; but it doesn't seem to help.
The reason for your messed up alignment in the JList is because it uses (hopefully) a proportional font. You could use a monospaced one, but that will be ugly. You need to use columns in the JList (i.e. a table control).

Categories