Java get a specific data in jsonarray - java

{"a":"AAA","b":32.4,"c":34.65},
{"a":"AAM","b":10.8,"c":11.55}
I use JSONArray to get jsonarray above. I want to use this code get data b:10.8 if a:AAM.
public static void main(String[]args) throws Exception{
String get = sql.getQuote();
JSONArray jsonarray = new JSONArray(get);
for (int i = 0; i<jsonarray.length();i++){
JSONObject obj = jsonarray.getJSONObject(i);
String symbol = obj.getString("a");
if (symbol.equals("AAM")){
double price = obj.getDouble("b");
System.out.println(price);
} else {
break;
}
}
}
Please help me to fix it. Thank you in advance.

The problem is with else statement in for-loop.
Remove else block i.e.
else {
break;
}
In your code, else block stops the for-loop on very first iteration. Because here "a":"AAA". Since the condition if (symbol.equals("AAM")) is false so else block is executing which further breaks the loop iteration.

The problem is the break in the else, just take it out.
If anywhere, it would be most appropriate in the if part:
if (symbol.equals("AAM")) {
System.out.println(obj.getDouble("b"));
break; // or leave it out if there might be a second AAM entry
}

Related

Java check if something was added to a string

I periodically check if a string which I get from a web service changed. This works just fine but if an old string is deleted from my method triggers, too.
For Example:
//I get this at the beginning
"One,Two,Three"
//And at the next check I get this
"Two,Three"
So the String changed and my method returned true like it is supposed to do.
But I only want to return true if e.g. "Four" is added to the string.
Can anyone give me a solution for this problem?
Thank you a lot,
Freezed
if (!oldstring.contains(newstring)))
return true;
Perhaps you could use split like so
public class MyClass {
public static void main(String args[]) {
String oldString = "This,Is,A,Test";
String[] oldItems = oldString.split(",");
String newString = "This,Is,A,New";
String[] newItems = newString.split(",");
// For each new item, check all old items
for (String newItem: newItems)
{
Boolean foundItem = false;
for (String oldItem: oldItems)
{
// Item was already in the old items
if (newItem.equals(oldItem))
{
foundItem = true;
break;
}
}
// New item is not in the old list of items
if (!foundItem)
{
System.out.println("New item added: " + newItem);
}
}
}
}
Something like
newString.contains(oldString) && !newString.equals(oldString)
Why not just trigger when the length of the string increases? The question doesn't state that what is being added matters--only whether something is being added at all.
boolean result = false;
if(newString.length() > oldString.length()) {
result = true;
break;
}
return result;
EDIT: Based on further clarification, I understand that the length of the string is not the best indicator, since something can be removed and added at the same time, in which case OP wants true returned--even if length is shorter. Here's a solution that splits the strings into tokens, and then checks whether the last token of the old string occurs before the last token of the new string, because that means something was added after it:
boolean result = false;
String delim = ",";
String oldStringTokens[] = oldString.split(delim);
String newStringTokens[] = newString.split(delim);
for(int i = 0; i < newStringTokens.length; i++) {
if(oldStringTokens[oldStringTokens.length-1].equals(newStringTokens[i])) {
if(i < newStringTokens.length - 1) {
result = true;
}
}
}
return result;

Array result keep getting the last result

I put a partial of my code which I think is the source of problem but I could not figure out hence why I am at StackOverFlow now. Anyways this Class is where i set my data and pass it into an array.
public ArrayList<select.rates> caseGetRates() throws RateTableException, SessionDisconnectedException {
try {
for(int i=0;i < arrayRate.size();i++){
ArrayList<select.rates> arr = new ArrayList<select.rates>();
this.setPair(array[0]);
this.setBid((array[2]));
this.setAsk((array[3]));
arr.add(this);
}
return arr;
} finally{}
}
When I System.out.print the data which I set in this class it gives me:
EUR/USD
1.12372
1.12384
USD/JPY
100.622
100.641
which is correct and what I would like it to be displayed on my webpage.However when I pass the data to my Servlet
try {
ArrayList<select.rates> rates = example.caseGetRates();
for(int i=0;i < rates.size();i++){
System.out.println("");
System.out.println(rates.get(i).getPair());
System.out.println(rates.get(i).getBid());
System.out.println(rates.get(i).getAsk());
}
request.setAttribute("rates", rates);
}
request.getRequestDispatcher("/NewFile.jsp").forward(request, response);
The result I get on my Servlet is:
USD/JPY
100.622
100.641
USD/JPY
100.622
100.641
The result does loop twice however the data seems to be overwritten and I still can't figure out why is this happening. I hope someone can pin point my mistake.
Create ArrayList object outside for loop
and inside for loop create new Object that you are adding to ArrayList
try {
ArrayList<select.rates> rates = example.caseGetRates();
for(int i=0;i < rates.size();i++){
// create new object here and then add to ArrayList
}
request.setAttribute("rates", rates);
}
request.getRequestDispatcher("/NewFile.jsp").forward(request, response);

DeleteSubString in Java

I have written my own deleteSubString method as i'm experimenting creating all the java functions. However i'm having issues with the output it produces. Here is my code:
//deleteSubString
String subString = "ON";
String delString = "PONY";
String emp = "";
int delIndex = 0;
for(int i=0; i<delString.length()-1; i++){
if(delString.contains(subString)){
//do nothing
//read the rest of the string to confirm it contains
for(int j=delIndex; j<delString.length()-1; j++){
if(delString.contains(subString)){
//do nothing
}
else{
emp += delString.charAt(j);
}
}
}
System.out.println("Delete SubString");
System.out.println(emp);
}
What I expect to happen is the string to print out as "PY" but instead it chooses not to print anything at all. Any ideas would be greatly appreciated!
if(delString.contains(subString)){ is always true so emp is never set to a new String.
PONY contains ON and delString.length()-1 won't consider the last character,so your else part would not run.
Instead simply do
if(delString.contains(subString))
{
int delSize=subString.length();
int index1=delString.indexOf(subString);
int index2=index1+delSize;
return delString.substring(0,index1)+""+delString.substring(index2+1);
}
else return delString;
You have:
(delString.contains(subString))
This statement will always be true with the strings you've provided.
for(String s : delString.split(subString)) {
emp += s;
}
is this what you want?
String subString = "ONY";
String delString = "PONY";
String emp = "";
StringBuilder sb1=new StringBuilder(subString);
StringBuilder sb2=new StringBuilder(delString);
for(int i=0;i<sb2.length();i++)
{
for(int j=0;j<sb1.length();j++)
{
if(sb2.charAt(i)==sb1.charAt(j))
{
sb2.deleteCharAt(i);
}
}
}
emp=sb2.toString();
System.out.println(emp);
Sorry!!I have revamped the code but looks like its going to work fine...the problem with the string class is its immutability...The cod which you wrote doesnt give the require output...if it gives it can delete only first character i.e only O in your case Y is not getting deleted so i converted into StringBuffer class and wrote that..Happy Coding!

Nullpointer Acess message in Java

I have created a method to parse a JSON object and to return an array of string.
private String[] getAttributesfromJson(JSONObject attacheddataattributejson) {
String returnjsonArray[] = null;
JSONArray subcatarray = attacheddataattributejson.optJSONArray("subcatAttributes");
if(subcatarray!=null){
for(int i=0;i<subcatarray.length();i++)
{
returnjsonArray[i]=subcatarray.getJSONObject(i).optString("name");
}
}
return returnjsonArray;
}
But my eclipse is showing an warning on returnjsonArray[i] that this can only be null at this pos. But I have a null check for subcatarray also. Please help.
You initialize your returnjsonArray[] to null and try to access it without having ever initialized it.
Java does no magic with null references; what is more, arrays are not dynamically allocated in Java. If you want that, use a List (which you should initialize as well), and return this list's .toArray().
See this line
String returnjsonArray[] = null;
You forgot to initialize it.
You won't get anything from a basket when you did'nt fill it before.
you can use the following code.
private String[] getAttributesfromJson(JSONObject attacheddataattributejson) throws JSONException {
List<String> returnjsonArray = new ArrayList<String>();
JSONArray subcatarray = attacheddataattributejson.optJSONArray("subcatAttributes");
if (subcatarray != null) {
for (int i = 0; i < subcatarray.length(); i++) {
returnjsonArray.add(subcatarray.getJSONObject(i).optString("name"));
}
}
return (String[]) returnjsonArray.toArray();
}

How to Create class declare Object and then assign value

The user enters an expression. Suppose user entered the following as input:
new y java.util.ArrayList int:5
i have successfully tokenized the string and stored it into different locations of my String array. next thing i want to do is that i should check whats on the index and do things according as mentioned in the above input for reflection. Am stuck how to do it. here is my code so far
public static void handling_input()
{
System.out.println("Welcome To Java Command Prompt: ");
aLine = null;
try
{
System.out.println("Enter The Command Line Expression: ") ;
keyboard = new BufferedReader(new InputStreamReader(System.in));
aLine = keyboard.readLine();
st = new StringTokenizer(aLine);
dt = new StringTokenizer(aLine);
}
catch (IOException ex)
{
System.out.println("Error reading input!");
}
}
public static void storing_tokens()
{
int counter =0;
while(st.hasMoreTokens())
{
counter++;
st.nextToken();
}
int i=0;
expression_keeper= new String[counter];
do
{
expression_keeper[i] = dt.nextToken().toString();
i++;
}while(dt.hasMoreTokens());
}
public static void token_classification()
{
for(int i=0; i<expression_keeper.length; i++)
{
if(expression_keeper[0].equalsIgnoreCase("new"))
{
}
else
if(expression_keeper[0].equalsIgnoreCase("call"))
{
}
else
if(expression_keeper[0].equalsIgnoreCase("print"))
{
}
else
{
System.out.println("Invalid Script!");
}
}
}
}
Inside this if condition:
if(expression_keeper[0].equalsIgnoreCase("new"))
{
}
i want to create the specified class,its object and assign values to the modifiers mentioned!
It is unclear to me what your input string tokens really mean. Is "java.util.ArrayList" the type for "y" and should it have an initial size of 5 units? Or should the first element be an integer of 5?
In the past I have found writing my own syntax tokenizer and parser a complicated thing to do. Even in simple cases I have often found that using something like JavaCC was easier in the long run.
By specifying your syntax formally you give much but structure to your code and it's debuggability. And then as said elsewhere use introspection to do the creation. The packages to do this are in java.lang.reflect.

Categories