JAVA GET API - 2D Array, Unable to retrieve? - java

I am getting a data varilable through an API like this (notice square brackets):
[
["2018-09-03",287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35],
["2018-08-31",286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41],
["2018-08-30",286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03]
]
What I am doing wrong in the below script? I am new to Java and need to print this block in table. Please help me, thanks in advance
public class ArrayLoopTest{
public static void main(String []args){
String[] data = new String[
["2018-09-03",287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35],
["2018-08-31",286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41],
["2018-08-30",286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03]
];
for (i=0;i < data.length;i++) {
System.out.println(data[i]);
}
}
}

Welcome to the wold of java.
Here are some things that you seem not to be doing well, as you know java is a strongly typed language. However from your code you are using a float in your array . perhaps you have declared that your array will contain strings only.
More so you are not declaring your array in a right way.
I will recommend that you work through this tutorial quickly Arrays in java.
But to resolve your issue you can do this instead
p
ublic static void main(String []args){
String[][] data = new String[][]{
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
};
for (int i=0;i < data.length;i++) {
for (int j = 0; j < data[i].lenght(); i++){
` System.out.print(data[i][j] + " ");
}
System.out.println("--------------")
}
}

While using an array keep in mind that array data structure can hold data of one type only. This essentially means that if a array is declared as String then it can have String type data only.
So, you can use the following code defining and printing the 2D array.
public static void main(String[] args) {
String[][] data = {
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"}
,{"2018-08-31","286.25","290.5","285.0","285.5","285.95","3716997.0","10691.41"}
,{"2018-08-30","286.45","290.55","284.6","286.05","285.6","3861403.0", "11097.03"}
};
for(int i=0;i<data.length;i++) {
for(int j=0;j<data[i].length;j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
// or you can print like this
for(int i=0;i<data.length;i++) {
System.out.println(Arrays.toString(data[i])+",");
}
}
Edit:
You can use the com.google.gson library as shown below to get a 2D array:
//String apiResponse = get Api Response
JsonParser parser = new JsonParser(); // parser converstthe api response to Json
JsonObject obj = (JsonObject) parser.parse(apiResponse);
JsonObject obj1 = obj.getAsJsonObject("dataset");
JsonArray arr = obj1.get("data").getAsJsonArray();
String[][] newString = new String[arr.size()][arr.get(0).getAsJsonArray().size()];
for(int i=0;i<newString.length;i++) {
for(int j=0;j<newString[i].length;j++) {
newString[i][j] = arr.get(i).getAsJsonArray().get(j).getAsString();
}
}
System.out.println(Arrays.deepToString(newString));

It can be solved in two ways, one dimensional and two dimensional, if you are thinking to put different data types in a single array, that is not possible in java.You can put only one type of data type inside defined array type.
Two dimensional array code:
public class ArrayLoopTest{
public static void main(String []args){
String[][] data =
{
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{ "2018-08-31","286.25","290.5","285.0","285.5","285.95","3716997.0","10691.41"},
{ "2018-08-30","286.45","290.55","284.6","286.05","285.6","3861403.0", "11097.03"}
};
for (int i=0;i < data.length;i++) {
{
for(int j=0;j<data[i].length;j++)
{
System.out.print(data[i][j]+" ");
}
System.out.println();
}
}
}}
One dimensional array code
public class ArrayLoopTest{
public static void main(String []args){
String[] data ={"2018-09-03,287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35",
"2018-08-31,286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41",
"2018-08-30,286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03"};
for (int i=0;i < data.length;i++)
{
System.out.println(data[i]);
}
}}

This won't compile as your array isn't of the correct format and the variable i is not defined. You need to loop over the items in each subarray and print them instead.
String[][] data = new String[][]{
{ "2018-09-03", "287.5", "289.8", "286.15", "287.3", "287.65", "1649749.0", "4750.35" },
{ "2018-08-31", "286.25", "290.5", "285.0", "285.5", "285.95", "3716997.0", "10691.41" },
{ "2018-08-30", "286.45", "290.55", "284.6", "286.05", "285.6", "3861403.0", "11097.03" }
};
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.print("\n");
}

Related

replacing elements of an array change by change

I'm trying to do some basics concerning an array of elements, specifically characters. My question is, how do I get the program to print my changes one by one? for example (I do not want my output going from "moon" to "mOOn" in one instance, but from "moon" to "mOon" to "mOOn", like that. Here is my code.
import java.util.*;
public class Practice
{
public static void main(String[] args)
{
String array[] = {"uuuuuuuupppppppssssssssss"};
System.out.println(Arrays.toString(array));
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i] = array[i].replace('p', 'P'));
//trying to print each change here
}
}
}
Thanks again!
EDIT/Update: I got the output to get the loop right, but the output is still not what I want (basically output: uPPPPPPS, uPPPPPPs, uPPPPPs, etc until the length of p ends). Any hints on what I could do? Thanks!
public static void main(String[] args){
String array = "uuuuuuuupppppppssssssssss";
System.out.println(array);
char[] chars = array.toCharArray(): //converted
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'p') {
System.out.println(array.replace('p', 'P'));
}
}
}
public static void main(String[] args)
{
String array = "uuuuuuuupppppppssssssssss";
System.out.println(array);
while ( array.contains("p") )
{
array = array.replaceFirst("p", "P");
System.out.println(array);
}
}

Compare strings in array after split in Java

I have a string that I use split function on it in order to split it to the different parts.
Then I want to check if the array contain a certain value, I tried using a for loop and also converting the array to a List and using the contain options but I get the same result - the text is not in the array.
P.S.
I edited the code to show a better example.
String categories = "C1-C-D-A-1-В";
String[] cat = categories.split("-");
String catCode = "B";
//always return false
if (Arrays.asList(cat).contains(catCode))
{
//do somthing
}
for (int idxCat = 0; idxCat < cat.length; idxCat++) {
//always return false
if ((cat[idxCat]).equals(catCode))
{
//do somthing
break;
}
}
I made a quick demo of what it seems you are asking.
If you are trying to see if any of the strings in your array contain a certain value:
public class HelloWorld
{
public static void main(String[] args)
{
String[] strings = new String[] {"bob", "joe", "me"};
for (int i = 0; i < strings.length; i++)
{
if (strings[i].contains("bob"))//doing "b" will also find "bob"
{
System.out.println("Found it!");
}
}
}
}
The console output is: Found it!
I would suggest trying to use equalsIgnoreCase() as mentioned in the comments. You may also want to show the values in your array:
import java.util.Arrays;
public class HelloWorld
{
public static void main(String[] args)
{
String[] strings = new String[] {"bob", "joe", "me"};
System.out.println(Arrays.toString(strings));
for (int i = 0; i < strings.length; i++)
{
if (strings[i].contains("bob"))
{
System.out.println("Found it!");
}
}
}
}
Output:
[bob, joe, me]
Found it!
This can help you to figure out if the values in the strings in your array are actually the values that you think they are.

Issue with string array

The below code gives result as test:[someproduct, someproduct, someproduct, someproduct, someproduct]. I am expecting result as ["someproduct", "someproduct", "someproduct", "someproduct", "someproduct"] so that I will push the string array into json response
String[] Id = new String[5];
for (int i = 0; i < 5; i++) {
Id[i] ="someproduct";
}
System.out.println("test:"+Arrays.toString(Id));
writer.key("product").value(Arrays.toString(Id));
When I try access the jsonresponse like response.product[0], i am getting first character '[' alone. I suppose to get first item(someproduct) of the array.
Please help me to resolve.
the problem is the method you are using is not sufficient.
one way of doing this, is to use another type of array (e.g. ArrayList) then Override its toString method.
here is an example:
public static void main(String... args) throws Exception{
ArrayList<String> array=new ArrayList<String>(){
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean isFirst=true;
for(String s : this){
if(!isFirst){
sb.append(",");
}
isFirst=false;
sb.append("\""+s+"\"");
}
sb.append("]");
return sb.toString();
}
};
for (int i = 0; i < 5; i++) {
array.add("someproduct");
}
System.out.println(array);
}
output:
["someproduct","someproduct","someproduct","someproduct","someproduct"]
NOTE:
There are many ways to make this code reusable, e.g.
creating a new class ArrayListWithNicePrint that extends ArrayList
creating a static method that returns you a fresh ArrayList with nice Print (I prefer this one really)
EDIT: (Based ON comment):
public class ArrayListWithNicePrint<E> extends ArrayList{
#Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean isFirst=true;
for(Object s : this){
if(!isFirst){
sb.append(",");
}
isFirst=false;
sb.append("\""+s.toString()+"\"");
}
sb.append("]");
return sb.toString();
}
}
Testing:
public class Testing{
public static void main(String... args){
ArrayListWithNicePrint<String> list= new ArrayListWithNicePrint<String>();
list.add("hi");
list.add("hello");
System.out.println(list);
}
}
Try this :
String[] Id = new String[5];
for(int i = 0; i < 5; i++)
{
Id[i] =" **\"someproduct\"** ";
}
hope it will work
You can use some JSON converter library, or as a quickfix you could use something like this:
String[] Id = new String[5];
for (int i = 0; i < 5; i++) {
Id[i] ="\"someproduct\"";
}
String arrOutput = Arrays.toString(Id).replaceAll("\\[", "{").replaceAll("\\]", "}");
System.out.println("test:"+ arrOutput);
writer.key("product").value(arrOutput);
Depending on the content on your array elements more workaround would be needed. Maybe if you write more information we can help you better.
why dont u try putting it into a List and then use Gson to convert the whole list into json format, dig a bit to get the correct format of json u want. for retrieving u can retrieve easily with the tag names associated with each element. What u require is not very clear so this is the best guess i can make
Try with this code. it will resolve your issue.
String[] Id = new String[5];
for (int i = 0; i < 5; i++) {
Id[i] ="\"someproduct\"";
}
System.out.println("test:"+Arrays.toString(Id).replace('[', '{').replace(']', '}'));
When usin the JSONWriter object, you should use the built in array() and endArray() methods like this:
writer.key("product").array();
for (int i=0; i<5; i++) {
writer.object();
writer.key("name").value("someproductname" + i);
writer.endObject();
}
writer.endArray();
http://www.json.org/javadoc/org/json/JSONWriter.html

Java fill 2d array with 1d arrays

Whats the nicest way to fill up following array:
From main:
String[][] data = new String[x][3];
for(int a = 0; a < x; a++){
data[a] = someFunction();
}
Function I am using..:
public String[] someFunction(){
String[] out = new String[3];
return out;
}
Is it possible to do something like this? Or do I have to fill it with for-loop?
With this code im getting error "non-static method someFunction() cannot be refferenced from static content ---"(netbeans) on line data[a] = someFunction();
You have to specify how many rows your array contains.
String[][] data = new String[n][];
for(int i = 0; i < data.length; i++){
data[i] = someFunction();
}
Note that someFunction can return arrays of varying lengths.
Of course, your someFunction returns an array of null references, so you still have to initialize the Strings of that array in some loop.
I just noticed the error you got. Change your someFunction to be static.
Change your someFunction() by adding "static".
You also should consider using an ArrayList for such tasks, those are dynamic and desinged for your purpose (I guess).
public static void main(String[] args){
int x = 3;
String[][] data = new String[x][3];
for(int a = 0; a < x; a++){
data[a] = someFunction();
}
}
public static String[] someFunction(){
String[] out = new String[3];
return out;
}
Greetings Tim

Convert JSON array of strings to Java?

I am trying to convert a JSON String array to Java which is given from this piece of javascript:
javaFunction(["a1", "a2"]); <--- This is called in javascript
In Java
public static void javaFunction(<What here?> jsonStringArray){ //<---- This is called in Java
//Convert the JSON String array here to something i can iterate through,
//For example:
for(int index = 0; index < convertedArray.length; index++){
System.out.println(convertedArray[index];
}
}
You can use this :
List<String> list = new ArrayList<String>();
for(int i = 0; i < jsonStringArray.length(); i++){
list.add(jsonStringArray.getJSONObject(i).getString("name"));
}
I solved it using this:
In the JavaScript:
javaFunction(JSON.Stringify(["a1", "a2"]));
In Java
public static void javaFunction(String jsonArrayString){
JSONArray jsonArray = new JSONArray(jsonArrayString);
List<String> list = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++){
list.add(jsonArray.getString(i));
}
}
Trim first and last bracket;
i.e.
jsonArrayString = jsonArrayString.subStr(1,jsonArrayString.length()-1);
you will get "a1","a2","a3","a4"
Then use String's split function.
String[] convertedArray= jsonArrayString.split(",");

Categories