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");
}
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.
I have a java program where the following is what I wanted to achieve:
first input: ABC
second input: xyz
output: AxByCz
and my Java program is as follows:
import java.io.*;
class DisplayStringAlternately
{
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
displayStringAlternately(firstC, secondC);
}
public static void displayStringAlternately (String[] firstString, String[] secondString)
{
int combinedLengthOfStrings = firstString.length + secondString.length;
for(int counter = 1, i = 0; i < combinedLengthOfStrings; counter++, i++)
{
if(counter % 2 == 0)
{
System.out.print(secondString[i]);
}
else
{
System.out.print(firstString[i]);
}
}
}
}
however I encounter the following runtime error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
AyC at DisplayStringAlternately.displayStringAlternately(DisplayStringAlternately.java:23)
at DisplayStringAlternately.main(DisplayStringAlternately.java:12)
Java Result: 1
What mistake is in my Java program?
If both arrays have same length for loop should continue while i < anyArray.length.
Also you don't need any counter to determine from which array you should print first. Just hardcode that first element will be printed from firstString and next one from secondString.
So your displayStringAlternately method can look like
public static void displayStringAlternately(String[] firstString,
String[] secondString) {
for (int i = 0; i < firstString.length; i++) {
System.out.print(firstString[i]);
System.out.print(secondString[i]);
}
}
Anyway your code throws ArrayIndexOutOfBoundsException because each time you decide from which array print element you are incrementing i, so effectively you are jumping through arrays this way
i=0 i=2
{"A","B","C"};
{"x","y","z"};
i=1 i=3
^^^-here is the problem
so as you see your code tries to access element from second array which is not inside of it (it is out of its bounds).
As you commented, If both arrays length is same, you can simply do
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
Then
for(int i = 0; i < firstC.length; i++) {
System.out.print(firstC[i]);
System.out.print(secondC[i]);
}
Using the combined length of the Strings is wrong, since, for example, secondString[i] would cause an exception when i >= secondString.length.
Try the below working code with high performance
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < firstC.length; i++) {
builder.append(firstC[i]);
builder.append(secondC[i]);
}
System.out.println(builder.toString());
}
public class concad {
public void main(String[] args) {
String s1 = "RAMESH";
String s2 = "SURESH";
int i;
int j;
for (i = 0; i < s1.length(); i++) {
System.out.print(s1.charAt(i));
for (j = i; j <= i; j++) {
if (j == i) {
System.out.print(s2.charAt(j));
}
}
}
}
}
I have taken two strings as mentioned.Then pass one counter variable in inner for-loop with second string,Then for every even position pass with code "counter%2".Check this out if any concern then comment below.
public class AlternatePosition {
public static void main(String[] arguments) {
String abc = "abcd";
String def = "efgh";
displayStringAlternately(abc, def);
}
public static void displayStringAlternately(String firstString, String secondString) {
for (int i = 0; i < firstString.length(); i++) {
for (int counter = 1, j = 0; j < secondString.length(); counter++, j++) {
if (counter % 2 == 0) {
System.out.print(secondString.charAt(i));
break;
} else {
System.out.print(firstString.charAt(i));
}
}
}
}
}
I am trying to create a Mastermind game in which colors are numbers [] and one number can never repeat itself in the String. The string should be made of 4 characters. I cannot figure out why my code keeps on printing strings with repeated characters.
import java.util.Random;
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
String toGuess="";
while(!IsValidNumber(toGuess));
{
for(int i=0; i<4; i++)
{
Random rando= new Random();
int rd=rando.nextInt(9);
toGuess=toGuess+rd;
}
}
System.out.println(toGuess);
}
public static boolean IsValidNumber(String s) // boolean
{
boolean noRepetition = true;
for(int i = 0; i < s.length(); i++)
{
for(int j = 0; j < i; j++)
{
if(i == j)
{
continue;
}
else if(s.charAt(i) == s.charAt(j))
{
noRepetition = false;
return false;
}
}
}
return noRepetition;
}
}
The boolean IsValidNumber never operates, I tried to print simple check words at different levels of it, and nothing ever prints but the String.
Thanks in advance, cheers
You've got a stray semicolon after the while() declaration, which causes the loop to immediately end. Consequently, your for loop constructs a number, and whatever number it constructs is immediately printed.
Consider the following instead:
public static void main(String[] args)
{
String toGuess="";
do { // Always try to generate at least one number.
toGuess = ""; //Reset each time we loop.
for(int i=0; i<4; i++) {
Random rando= new Random();
int rd=rando.nextInt(9);
toGuess=toGuess+rd;
}
} while(!IsValidNumber(toGuess));
System.out.println(toGuess);
}
That might work better.
Basically, while (exp); is equivalent to while(exp) {} or an empty while loop. Only put a semicolon after your while(exp) when using the do...while construct I illustrate here.
I have an encoded String like this:
17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu
and want to split it on the "/".
In the last part, there is a encoded "/" as "%2F".
The result is
[17298457,abcdef , 17298529,ghijklm , 17298562,opq , rstu]
The problem is, that Java decodes the string on the fly as soon as i pass it to another method (split method e.c.)
Do someone have a good idea how to work around that?
thanks a lot!
monk
Not for me....
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws Exception {
String s = "17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu";
System.out.println(Arrays.toString(s.split("/")));
}
}
gives
[17298457,abcdef, 17298529,ghijklm, 17298562,opq%2Frstu]
public static void main(String[] args) {
String test = "17298457,abcdef/17298529,ghijklm/17298562,opq%2Frstu";
String[] args2 = test.split("/");
for (int i = 0; i < args2.length; i++) {
String[] args3 = args2[i].split("%2F");
for (int j = 0; j < args3.length; j++) {
if(!args3[j].trim().startsWith(",") && j != 0)
System.out.print(" ,");
System.out.print(args3[j]);
}
}
OUT PUT - AS U WRITTEN -
17298457,abcdef17298529,ghijklm17298562,opq ,rstu