I'm trying to randomize JSON array this way:
private static JSONArray getJSONArray(Context context) {
JSONArray myJSONarr=new JSONArray();
JSONArray myRandomizedJSONarr=new JSONArray();
try
{
InputStream is = context.getAssets().open("chineesecardsdata.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String resultJson = new String(buffer, "UTF-8");
try {
JSONObject myJSONObject=new JSONObject(resultJson);
myJSONarr=myJSONObject.getJSONArray("data");
Log.d("mainActLog","Array before random: "+myJSONarr.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
}
catch(
IOException e) {
}
try {
ArrayList<Integer> intArr1 = new ArrayList<>(myJSONarr.length());
for (int i = 0; i < myJSONarr.length(); i++) {
intArr1.add(i);
}
Collections.shuffle(intArr1);
for (int i = 0; i < intArr1.size(); i++) {
myRandomizedJSONarr.put(i, myJSONarr.getJSONObject(intArr1.get(i)));
if (i == (myJSONarr.length() - 1))
break;
}
Log.d("mainActLog","Array after random: "+myRandomizedJSONarr.toString());
}
catch (JSONException e){}
return myRandomizedJSONarr;
}
As a result of this not only JSON objects are randomizing, but also keys and values.
I mean, I had an array like this:
[
{"id":"0","hieroglyph":"水","pinyin":"Shuǐ","pinyin_num":"Shui3","russian":["вода"],"hsk":"1"},
{"id":"1","hieroglyph":"人","pinyin":"Rén","pinyin_num":"Re2n","russian":["человек"],"hsk":"1"},
{"id":"2","hieroglyph":"日","pinyin":"Rì","pinyin_num":"Ri4","russian":["день"],"hsk":"1"},
{"id":"3","hieroglyph":"不","pinyin":"Bù","pinyin_num":"Bu4","russian":["нет"],"hsk":"1"},
{"id":"4","hieroglyph":"少","pinyin":"Shǎo","pinyin_num":"Sha3o","russian":["мало"],"hsk":"1"}]
And after randomize it looks like this
[{"id":"2","hieroglyph":"日","pinyin":"Rì","pinyin_num":"Ri4","russian":["день"],"hsk":"1"},
{"id":"2","hieroglyph":"日","pinyin":"Rì","pinyin_num":"Ri4","russian":["день"],"hsk":"1"},
{"id":"4","hieroglyph":"少","pinyin":"Shǎo","pinyin_num":"Sha3o","russian":["мало"],"hsk":"1"},
{"id":"3","hieroglyph":"不","pinyin":"Bù","pinyin_num":"Bu4","russian":["нет"],"hsk":"1"},
{"id":"2","hieroglyph":"日","pinyin":"Rì","pinyin_num":"Ri4","russian":["день"],"hsk":"1"}]
Why not just shuffle the array directly?
List<JSONObject> myList = new ArrayList<JSONObject>();
for(int i = 0; i < myJSONarr; i++){
myList.add(myJSONarr.getJSONObject(i));
}
Collections.shuffle(myList);
Related
The overarching theme of this project is to sort stuff. My full code works (sort of) but the issue is that it always sorts my data as a String and I am pretty sure its caused by that fact that I am reading the dataFile's line as a String and inputting that into the array as a string.
Object[] list = new Object[n];
if (n > 0) {
try {
BufferedReader file = new BufferedReader(new FileReader("dataFile.txt"));
for (int i = 0; i < list.length; i++) {
String t = file.readLine();
if (t != null)
list[i] = t;
}
file.close();
}
catch (FileNotFoundException e) {
System.out.println("Error accessing file.");
} catch (IOException io) {
System.out.println("There was an error reading from the file.");
}
}
If someone could point me in the correct direction on how to read a line and input it into an array as an Object, I would be grateful.
A Java String is an Object. (String extends Object)
So you can get an Object reference via assignment!
Perhaps, you can try adding content from your file to an Object array like below:-
Object[] list = new Object[n];
if (n > 0) {
try {
BufferedReader file = new BufferedReader(new FileReader("dataFile.txt"));
for (int i = 0; i < list.length; i++) {
String t = file.readLine();
Object obj = t;
if (obj != null)
list[i] = obj;
}
file.close();
}
catch (FileNotFoundException e) {
System.out.println("Error accessing file.");
} catch (IOException io) {
System.out.println("There was an error reading from the file.");
}
}
Why don't you use Java8 internal tools to ready text files:
public static Object[] readAllLinesFromFile(Path path) throws IOException {
return Files.lines(path).toArray(String[]::new);
}
Figured out the issue. This code fixes, thanks to the people who helped.
void dataType() {
for (int i = 0; i < list.length; i++) {
try {
checkINT = Integer.parseInt((String) list[i]);
list[i] = checkINT;
} catch (Exception eInt) {
try {
checkDBL = Double.parseDouble((String) list[i]);
list[i] = checkDBL;
} catch (Exception eDbl) {
// Then its a string.
}
}
}
}
I am working on a Java project and I am having a problem. I want to have the subtract of two lists or arrays a and b in list/array c but I don't know how to do that. I want "a[i] -b[i]" should be in next list c where the value should be c[i] similarly for 5-2=3 any suggestion and help would be appreciated.
Code:
public static void länge() {
{
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("C:\\Users/Voodoothechild/Desktop/Pidata/Anfang.txt")));
String line = null;
while ((line = br.readLine()) != null) {
{
BufferedReader bro = null;
try {
bro = new BufferedReader(new FileReader(new File("C:\\Users/Voodoothechild/Desktop/Pidata/Ende.txt")));
String lines = null;
while ((lines = br.readLine()) != null) {
String[] anfang = line.split("\n");
String[] ende = lines.split("\n");
List<Integer> an = new ArrayList<Integer>();
List<Integer> en = new ArrayList<Integer>();
for (int index = 0 ; index<ende.length ; index++) {
an.add(Integer.parseInt(anfang[index]));
en.add(Integer.parseInt(ende[index]));
Integer[] anf = new Integer[an.size()];
int[] result = new int[anf.length];
for (int i = 0; i < result.length; i++) {
result[i] = anf[i] - end[i];
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bro != null) {
try {
bro.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
It can be done easily using Stream API:
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
IntStream.range(0, list1.length)
.mapToObj(i -> list1[i] - list2[i])
.collect(Collectors.toList());
or even easier using Javaslang:
Stream.range(0, list1.length)
map(i -> list1[i] - list2[i]);
or by zipping two lists together:
List.ofAll(list1)
.zip(List.ofAll(list2))
.map(t -> t._1 - t._2);
Its pretty straight forward. Before tackling a programming problem. Always do it in steps. Take your problem for example. You need to subtract values from 2 arrays with values.
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
Now you have 2 list. Ok next step, write a loop to go through the list. But first make sure that both list have the same length or else you will get an index out of bounce.
for(int i =0; i< list1.length; i++)
{
list3[i] = list1[i] - list2[i];
}
Anyway here is the full answer. Be sure to understand it
public class subtract
{
public static void main(String[] args)
{
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
int[] list3 = new int[list1.length];
//Looping the list
for(int i =0; i< list1.length; i++)
{
list3[i] = list1[i] - list2[i];
}
//Print Statement
for(int j =0; j< list3.length; j++)
{
System.out.println(list3[j]);
}
}
}
Here's a very simple answer you can apply to your program.
public static void main(String[] args) {
int[] a = new int[4];
int[] b = new int[4];
int[] c = new int[4];
a[0] = 5;
a[1] = 12;
a[2] = 20;
a[3] = 50;
b[0] = 1;
b[1] = 2;
b[2] = 3;
b[3] = 4;
for(int i=0; i<a.length; i++){
c[i] = a[i] - b[i];
System.out.println(c[i]);
}
}
The answer is the method removeAll of class Collection
ArrayList<Integer> s1 = new ArrayList<Integer>(Arrays.asList(a1));
ArrayList<Integer> s2 = new ArrayList<Integer>(Arrays.asList(a2));
s1.removeAll(s2);
Integer[] result = s1.toArray(new Integer[s1.size()]);
As a beginner, I am trying to print a set of info to a file called "Sign_in.txt" but this code only creates the file and doesn't print anything. What am I doing wrong?
String nu="CUSTOMER DETAILS START";
String enu="CUSTOMER DETAILS END";
n=namefield.getText();
a=agefield.getText();
ad=adfield.getText();
s=salfield.getText();
p=phfield.getText();
d=dobfield.getText();
e=emfield.getText();
ArrayList<String> list = new ArrayList<String>();
list.add(nu);
list.add(n);
list.add(a);
list.add(ad);
list.add(s);
list.add(p);
list.add(d);
list.add(e);
list.add(u);
list.add(q);
list.add(enu);
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Sign_in.txt",true)))) {
Writer output = new BufferedWriter(out);
int l = list.size();
for(int i = 0; i<l; i++){
output.write(list.get(i).toString()+"\n");
}
output.close();
}
catch (Exception e)
{
e.printStackTrace();
}
JOptionPane.showMessageDialog(this,"Thank you for registering");
System.exit(0);
new accpage().setVisible(true);
}
I would have something like this:
try (PrintWriter output =
new PrintWriter(new BufferedWriter(new FileWriter("Sign_in.txt"))))
{
for (String line: list) {
output.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Working code
try (PrintWriter output = new PrintWriter(
new BufferedOutputStream(
new FileOutputStream("Sign_in.txt")), true))
{
int l = list.size();
for (int i = 0; i < l; i++) {
output.println(list.get(i).toString());
}
} catch (Exception e) {
e.printStackTrace();
}
I'm working on JSON. I wrote code which can to parse JSON and show listview(images and text).
Now I want to save my JSON in file (json.txt).
This is a my code. I try to save JSON but when I debug it on my json.txt file saved only first data, but I have 20 data in JSON
if anyone know solution please help .......
jsonparser = new JSONParser();
JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
yourFile = new File("/sdcard/json.txt");
try {
writer = new OutputStreamWriter(
new FileOutputStream(yourFile), "UTF-8");
writer.write(jsonobject.toString());
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
open your file in append mode.
new OutputStreamWriter(new FileOutputStream(yourFile,true), "UTF-8");
Use a separate variable for the JSONObject retrieved from the URL, and the one used to loop the data array:
jsonparser = new JSONParser();
JSONObject jsonfromurl = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonfromurl.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
yourFile = new File("/sdcard/json.txt");
try {
writer = new OutputStreamWriter(
new FileOutputStream(yourFile), "UTF-8");
writer.write(jsonfromurl.toString());
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should follow the same style as here. From what I can see, they actually write bytes to the FileOutputStream, whereas you try to write a string. FileOutputStream only accepts bytes, as per the documentation.
Try writer.write(jsonobject.toString().getBytes()); instead.
package automate;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Point;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
public class AlphabetGestures extends UiAutomatorTestCase {
private static Map<Character,Vector<Point>> map = new HashMap<Character,Vector<Point>>() ;
private static JSONObject jsonObj;
static{
String text;
try {
File file = new File("/data/misc/alphaNums.json");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int)file.length()];
fis.read(data);
fis.close();
text = new String(data, "UTF-8");
jsonObj = new JSONObject(text);
} catch(JSONException e){
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*I am not able to implement the following algorithm:-
I want to create a map for all the characters <- already there in the static bloc
open the alphaNum.json file <- already there in the static bloc,but not error handling.
parse it as a json object <- already there in the static bloc,
for every letter in the json object {
create a vector<Point>
for every Point in the letter {
add the Point to the vector
}
add the vector to the map
}
*/
Vector<Point> liA = setupA();
Vector<Point> liB = setupB();
Vector<Point> liC = setupC();
map.put('A',liA) ;
map.put('B',liB) ;
map.put('C',liC) ;
}
private static Vector<Point> setupA(){
try {
JSONArray jsonArr = jsonObj.getJSONArray("A");
System.out.println("IS here");
//get array A
if(jsonArr!=null){
Vector<Point> apoints = new Vector<Point>();
System.out.println("IS here");
for(int k = 0; k < jsonArr.length(); k++ ){
JSONArray arr = jsonArr.getJSONArray(k);
apoints.add(new Point(arr.getInt(0), arr.getInt(1)));
System.out.println(apoints);
}return apoints ;
}else{
System.out.println("A is null");
}
} catch (JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static Vector<Point> setupB(){
try {
JSONArray jsonArr = jsonObj.getJSONArray("B");
System.out.println("IS here");
//get array B
if(jsonArr!=null){
Vector<Point> apoints = new Vector<Point>();
System.out.println("LUMIA IS here");
for(int k = 0; k < jsonArr.length(); k++ ){
JSONArray arr = jsonArr.getJSONArray(k);
apoints.add(new Point(arr.getInt(0), arr.getInt(1)));
System.out.println(apoints);
}return apoints ;
}else{
System.out.println("B is null");
}
} catch (JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static Vector<Point> setupC(){
try {
JSONArray jsonArr = jsonObj.getJSONArray("C");
System.out.println("IS here");
//get array C
if(jsonArr!=null){
Vector<Point> apoints = new Vector<Point>();
System.out.println(" IS here");
for(int k = 0; k < jsonArr.length(); k++ ){
JSONArray arr = jsonArr.getJSONArray(k);
apoints.add(new Point(arr.getInt(0), arr.getInt(1)));
System.out.println(apoints);
}return apoints ;
}else{
System.out.println("C is null");
}
} catch (JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void scribble(char letter, UiDevice uiDevice){
System.out.println("here");
Vector<Point> points = map.get(letter) ;
System.out.println("------------------");
System.out.println(points);
if(points!=null){
uiDevice.swipe(points.toArray(new Point[points.size()]), 5);
}
}
}
What about
private static Vector<Point> setupLetter(String letter){
try {
JSONArray jsonArr = jsonObj.getJSONArray(letter);
System.out.println("IS here");
//get array corresponding to letter
if(jsonArr!=null){
Vector<Point> letterPoints = new Vector<Point>();
System.out.println("IS here");
for(int k = 0; k < jsonArr.length(); k++ ){
JSONArray arr = jsonArr.getJSONArray(k);
letterPoints.add(new Point(arr.getInt(0), arr.getInt(1)));
System.out.println(letterPoints);
}return letterPoints ;
}else{
System.out.println("%s is null".format(letter));
}
} catch (JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}