Java JSON Array Text Files - java
I've seen to hit a bump with this. I can't seem to get the array of the map from text file. I mean, I can get everything else BUT the map's array tiles.
This is the text file:
{
'name': 'map_one.txt',
'title': 'xxx One',
'currentMap': 4,
'rightMap': 3,
'lefttMap': 5,
'downMap': 1,
'upMap': 2,
'items': [
{ name: 'Pickaxe', x: 5, y: 1 },
{ name: 'Battleaxe', x: 2, y: 3 }
],
'map': [ [ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],
[ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],
[ 1,7,1,1,1,24,1,1,24,1,1,1,1 ],
[ 1,7,1,1,7,1,1,1,24,1,1,1,1 ],
[ 1,7,7,7,1,24,24,24,24,1,1,1,1 ],
[ 1,1,7,1,1,24,1,24,1,1,1,1,1 ],
[ 1,1,1,1,1,24,1,1,1,1,1,1,1 ],
[ 1,1,3,1,1,24,1,1,1,1,1,1,1 ],
[ 1,3,3,1,1,24,1,1,1,1,1,1,1 ]]
};
and when I run it, I get this:
==========================
JSON MAP LOAD...
==========================
Name of map: xxx One
File of map: map_one.txt
ID of map: 4
==========================
ITEMS IN MAP
==========================
# OF ITEMS: 2
>> Name: Pickaxe (5, 1)
>> Name: Battleaxe (2, 3)
==========================
TILES OF MAP
==========================
null
Press any key to continue . . .
See the null? It's *suppose to be numbers of arrays.
I'm doing it wrong, probably, I know. Here's what I have so far:
import java.util.*;
import java.io.*;
import com.google.gson.*;
public class readGoogle {
public static String MapTitle;
public static Data data;
public static Item item;
public static String dan;
public static FileReader fr;
public static int number;
public static int currentMap;
public static int tile;
public static String[] wepN;
public static void main(String[] args) {
try {
fr = new FileReader("map1.txt");
}catch(FileNotFoundException fne) {
fne.printStackTrace();
}
StringBuffer sb = new StringBuffer();
char[] b = new char[1000];
int n = 0;
try {
while ((n = fr.read(b)) > 0) {
sb.append(b, 0, n);
}
}catch(IOException rex) {
rex.printStackTrace();
}
String fileString = sb.toString();
try {
data = new Gson().fromJson(fileString, Data.class);
}catch (Exception er) {
er.printStackTrace();
}
System.out.println("==========================\n JSON MAP LOAD...\n==========================\n");
System.out.println("Name of map: " + data.getTitle());
System.out.println("File of map: " + data.getName());
System.out.println("ID of map: " + data.getCurrentMap());
String[] wepN = new String[100];
String[] wepX = new String[100];
String[] wepY = new String[100];
int[] tile = new int[256];
int wepQty = 0;
try {
for (int i=0; i < wepN.length; i++) {
if (data.getItems().get(i).getName() == null || "".equals(data.getItems().get(i).getName())) {
System.out.println(data.getItems().get(i).getName() + " -NO MOARE");
break;
}
wepN[i] = data.getItems().get(i).getName();
wepX[i] = Integer.toString(data.getItems().get(i).getX());
wepY[i] = Integer.toString(data.getItems().get(i).getY());
wepQty++;
}
}catch(Exception xe) { }
System.out.println("\n==========================\n ITEMS IN MAP\n==========================\n");
System.out.println("# OF ITEMS: " + wepQty + "\n");
for (int i=0; i < wepQty; i++) {
System.out.println(">> Name: " + wepN[i] + " (" + wepX[i] + ", " + wepY[i] + ")");
}
System.out.println("\n==========================\n TILES OF MAP\n==========================\n");
System.out.println(data.getMap());
}
public static class Item {
public String name;
public int x;
public int y;
public int tile;
public String getName() { return name; }
public int getX() { return x; }
public int getY() { return y; }
public void setName(String name) { this.name = name; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
}
public static class Data {
private String name;
private String title;
private int currentMap;
private List<Item> items;
private int[][] tile;
public String getName() { return name; }
public int getCurrentMap() { return currentMap; }
public String getTitle() { return title; }
public List<Item> getItems() { return items; }
public int[][] getMap() { return tile; }
public void setName(String name) { this.name = name; }
public void setTitle(String title) { this.title = title; }
public void setItems(List<Item> items) { this.items = items; }
public void setMap(int[][] tile) { this.tile = tile; }
}
}
My thought is that the Data class has a tiles field for holding the map but in the JSON it is named map.
try:
public static class Data {
private String name;
private String title;
private int currentMap;
private List<Item> items;
private int[][] map;
public String getName() { return name; }
public int getCurrentMap() { return currentMap; }
public String getTitle() { return title; }
public List<Item> getItems() { return items; }
public int[][] getMap() { return map; }
public void setName(String name) { this.name = name; }
public void setTitle(String title) { this.title = title; }
public void setItems(List<Item> items) { this.items = items; }
public void setMap(int[][] map) { this.map= map; }
}
Related
I can't fetch dogs/cats/fish name , age, colour, friendly from my JSON file
It show the full JSON file I want to partly like dogs, cats, fish separately MyGdxGame.java public class MyGdxGame extends ApplicationAdapter { private Stage stage; public static AssetManager manager; private com.badlogic.gdx.scenes.scene2d.ui.Image image; #Override public void create() { stage = new Stage(); Gdx.input.setInputProcessor(stage); manager = new AssetManager(); manager.load("badlogic.jpg", Texture.class); manager.load("song.mp3", Music.class); manager.finishLoading(); image = new Image(manager.get("badlogic.jpg", Texture.class)); image.setBounds(20, 30, 200, 200); Music music = manager.get("song.mp3", Music.class); music.play(); image.addAction(Actions.sequence(Actions.moveBy(300, 200), Actions.rotateBy(300, 200))); stage.addActor(image); JsonReader temp = new JsonReader(); JsonValue base = temp.parse(Gdx.files.internal("pets.json")); JsonValue pets = base.get("pets"); for (JsonValue component : base.get("pets")) { Pets dog = new Pets(); Pets cat = new Pets(); Pets fish = new Pets(); Json json = new Json(); System.out.println("\n\n name : " + component.getString("name")); System.out.println("age : " + component.getString("age")); System.out.println("colour : " + component.getString("colour")); if (component.has("friendly")) { System.out.println("friendly : " + component.getString("friendly")); } } } #Override public void render () { Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); super.render(); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); } } Pets.java this is pets class where object is define package com.mygdx.game; import java.util.ArrayList; public class Pets { public int age; public String name; public String colour; public boolean friendly; public Pets(String name,int age, String colour, boolean friendly) { this.age = age; this.name = name; this.colour = colour; this.friendly = friendly; } public Pets() { } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public boolean isFriendly() { return friendly; } public void setFriendly(boolean friendly) { this.friendly = friendly; } } pets.json this is my json file where i want to fetch data { pets: [ { age:12, name:"tommy", colour:"balck", friendly:"true" }, { age:5, name:"bob", colour:"white", friendly:"true" }, { age:22, name:"fishy", colour:"white" } ] } Output I want to output dogs name=tommy dogs age=12 dogs color=black dogs friendly=true
How to get number of different words in Java?
I am working with Musical Jukebox program. I have two main classes: Song.java and Playlist.java. The Song.java is as follows: public class Song { String name; String title; double length; public Song(String name,String title,double length) { this.name=name; this.title=title; this.length=length; } public void setArtist(String songname) { name=songname; } public String getArtist() { return name; } public void setTitle(String songtitle) { title=songtitle; } public String getTitle() { return title; } public void setLength(double songlength) { length=songlength; } public double getLength() { return length; } public String toString() { return "Title: " + getTitle() + ", Artist: " + getArtist() + ", Track Length: " + getLength(); } And Playlist.java is as follows: import java.util.ArrayList; import java.util.HashSet; import java.util.Set; #SuppressWarnings("serial") public class Playlist<E extends Song> extends java.util.Vector<E> { java.util.Iterator<E> itr = this.iterator(); String name; ArrayList<Song> songList; public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayList<Song> getSongList() { return songList; } public void setSongList(ArrayList<Song> songList) { this.songList = songList; } public void PlayList() { name = "Untitled"; songList = new ArrayList<Song>(); } public Playlist(String name) { this.name = name; songList = new ArrayList<Song>(); } public Object getTitle() { return "Playlist Title"; } public boolean addtoPlist(Song song1) { songList.add(song1); return true; } public Song getSong(int index) { songList.trimToSize(); if(songList.size() >= index){ return songList.get(index); } else return null; } public boolean hasTitle(String string) { if( string.equals("Playlist Title")) return true; return false; } public boolean hasArtist(String string) { if(string.equalsIgnoreCase("artist1")) return true; return false; } public Object numberOfSongs() { // TODO Auto-generated method stub return songList.size(); } public Object numberOfArtists() { return 0; } public Object numberOfTitles() { return null; } public double playTime() { return 0; } public Object findSong(Song song1) { if(song1.equals("song1")&&song1.equals("song2")&& song1.equals("song3")&&song1.equals("song4")) itr.next(); return true; } public void sortByArtist() { } public boolean removeFromPlist(Song str) { songList.remove(str); return true; } } And this is playlisttest.java for unit testing: import junit.framework.TestCase; import java.util.Vector; public class PlaylistTest extends TestCase { private Playlist<Song> aPlaylist; private Song song1, song2, song3, song4, duplicate_song, nullSong; public void setUp() { aPlaylist= new Playlist<Song>("Playlist Title"); song1 = new Song("Artist1", "AA", 6.00); song2 = new Song("Artist1", "BB", 3.50); song3 = new Song("Artist2", "BB", 3.00); song4 = new Song("Artist2", "CC", 5.50); duplicate_song = new Song("ARTIST1", "TITLE1", 5.00); // Same song with song 1 nullSong = null; } protected void tearDown() throws Exception { super.tearDown(); } protected void fillPlaylist() { aPlaylist.addtoPlist(song1); aPlaylist.addtoPlist(song2); aPlaylist.addtoPlist(song3); aPlaylist.addtoPlist(song4); } public void test_Constructor() { assertNotNull(aPlaylist); assertTrue(aPlaylist instanceof Vector); assertTrue(aPlaylist.isEmpty()); } public void test_getTitle() { assertTrue(aPlaylist.getTitle().equals("Playlist Title")); } public void test_addtoPList() { assertTrue(aPlaylist.isEmpty()); assertTrue(aPlaylist.addtoPlist(song1)); assertEquals(1, aPlaylist.size()); assertTrue(aPlaylist.addtoPlist(song2)); assertTrue(aPlaylist.addtoPlist(song3)); assertEquals(3, aPlaylist.size()); assertFalse(aPlaylist.addtoPlist(nullSong)); assertEquals(3, aPlaylist.size()); assertFalse(aPlaylist.addtoPlist(duplicate_song)); assertEquals(3, aPlaylist.size()); } public void test_removeSong() { fillPlaylist(); int size = aPlaylist.size(); assertFalse(aPlaylist.removeFromPlist(nullSong)); assertEquals(size, aPlaylist.size()); assertFalse(aPlaylist.removeFromPlist(new Song("Artist1", "Title1", 1.00))); assertEquals(size, aPlaylist.size()); assertTrue(aPlaylist.contains(duplicate_song)); assertTrue(aPlaylist.removeFromPlist(duplicate_song)); // Removing "duplicate_song" is removing "song1" assertEquals(size - 1, aPlaylist.size()); } public void test_getSong() { fillPlaylist(); assertTrue(aPlaylist.getSong(0) instanceof Song); assertEquals(song1, aPlaylist.getSong(0)); assertEquals(duplicate_song, aPlaylist.getSong(0)); assertEquals(song2, aPlaylist.getSong(1)); assertEquals(song3, aPlaylist.getSong(2)); assertEquals(song4, aPlaylist.getSong(3)); } public void test_hasTitle() { fillPlaylist(); assertTrue(aPlaylist.hasTitle("Playlist Title")); assertFalse(aPlaylist.hasTitle("wrong title")); } public void test_hasArtist() { fillPlaylist(); assertTrue(aPlaylist.hasArtist("artist1")); assertFalse(aPlaylist.hasArtist("wrong artist")); } public void test_numberOfSongs() { fillPlaylist(); assertEquals(4, aPlaylist.numberOfSongs()); } public void test_numberOfArtists() { fillPlaylist(); assertEquals(2, aPlaylist.numberOfArtists()); } public void test_numberOfTitles() { fillPlaylist(); assertEquals(3, aPlaylist.numberOfTitles()); } public void test_playTime() { fillPlaylist(); assertTrue(aPlaylist.playTime() == 19.00); } public void test_findElement() { fillPlaylist(); assertEquals(0, aPlaylist.findSong(song1)); assertEquals(1, aPlaylist.findSong(song2)); assertEquals(2, aPlaylist.findSong(song3)); assertEquals(3, aPlaylist.findSong(song4)); //assertEquals(-1, aPlaylist.findSong(new Song("Not", "There", 0))); } public void test_sortByArtist() { // TODO: Assignment 6 -- create new test case here: sort by artist } public void test_sortByTitle() { } } I would like to implement numberOfTitles method that retrieves number of different titles but I really do not know how to take different titles and return the count (which is 3 in our case as it could be seen).If possible could you help me to solve this please? Your help is greatly appreciated!
You can store the unique titles in a Set and get the size of this once you're done: Set<String> uniqueSongs = new Set<>(); for (Song song : songList) { uniqueSongs.add(song.getTitle()); } Then you can use uniqueSongs.size() to get the number of unique songs. You can also use streams if you're in Java 8 (thanks to Boris the Spider for pointing it out): Set<String> uniqueSongs = songList.stream().map(Song::getTitle).collect(Collectors.toSet())
Can't set propertys of objects in an ObservableList
In my main class I initialise a static object (lkw), which contains the public ObservableList (ladung). Now I want to manipulate the data in the list whith the methode ergebniss, which is located in the class Methoden. I call the methode ergebniss in my JavaFx Gui. It doesn't work. I don't get an error, but the X property is empty. Also removing an element (Main.lkw.ladung.remove(j)) doesn't work. What I do wrong? EDIT Code Class Main public class Main extends Application{ public static Lkw lkw=new Lkw(); public static void main(String[] args) { javafx.application.Application.launch(Gui.class); } #Override public void start(Stage primaryStage) throws Exception { // TODO Auto-generated method stub } Class Lkw public class Lkw { private String name=""; private int länge=0; private int breite=0; private int höhe=0; public ObservableList<Ladung> ladung=FXCollections.observableArrayList(); public Lkw(String name, int länge, int breite, int höhe){ this.name=name; this.länge=länge; this.breite=breite; this.höhe=höhe; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public int getLänge() { return länge; } public void setLänge(int länge) { this.länge = länge; } public int getBreite() { return breite; } public void setBreite(int breite) { this.breite = breite; } public int getHöhe() { return höhe; } public void setHöhe(int höhe) { this.höhe = höhe; } public ObservableList<Ladung> getLadung() { return ladung; } public void setLadung(ObservableList<Ladung> ladung) { this.ladung = ladung; } Class Ladung public class Ladung { private int nr; private int länge = 0; private int breite = 0; private int höhe = 0; private int x = 0; private int y = 0; private int z = 0; private int raum = 0; private Rectangle farbe = new Rectangle(100, 50); public Ladung(int nr, int länge, int breite, int höhe) { this.nr = nr; this.länge = länge; this.breite = breite; this.höhe = höhe; this.farbe.setFill(new Color(Math.random(), Math.random(), Math.random(), 1)); } public Ladung(int nr, int länge, int breite, int höhe, int raum, int x, int y, int z, Rectangle farbe) { this.nr = nr; this.länge = länge; this.breite = breite; this.höhe = höhe; this.raum = raum; this.x = x; this.y = y; this.z = z; this.farbe=farbe; } public int getLänge() { return länge; } public void setLänge(int länge) { this.länge = länge; } public int getBreite() { return breite; } public void setBreite(int breite) { this.breite = breite; } public int getHöhe() { return höhe; } public void setHöhe(int höhe) { this.höhe = höhe; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getZ() { return z; } public void setZ(int z) { this.z = z; } public int getNr() { return nr; } public void setNr(int nr) { this.nr = nr; } public int getRaum() { return raum; } public void setRaum(int raum) { this.raum = raum; } public Rectangle getFarbe() { return farbe; } public void setFarbe(Rectangle farbe) { this.farbe = farbe; } This is the class with some static methods public class Methoden { public static int einlesen(String pfad) { int ret=0; String zeile = ""; String[] daten = null; FileReader fr = null; try { fr = new FileReader(pfad); BufferedReader br = new BufferedReader(fr); zeile = br.readLine(); daten = zeile.split(" "); Main.lkw.setLänge(Integer.valueOf(daten[1])); Main.lkw.setBreite(Integer.valueOf(daten[2])); Main.lkw.setHöhe(Integer.valueOf(daten[3])); zeile = br.readLine(); int j=0; while (zeile != null) { daten = null; daten = zeile.split(" "); Main.lkw.ladung.get(j).setX(Integer.valueOf(daten[5])); Main.lkw.ladung.get(j).setY(Integer.valueOf(daten[6])); Main.lkw.ladung.get(j).setZ(Integer.valueOf(daten[7])); Main.lkw.ladung.get(j).setRaum(Integer.valueOf(daten[4])); zeile = br.readLine(); } br.close(); fr.close(); if(Main.lkw.getLadung().size()==0){ ret=-1; } for(int i=0;i<Main.lkw.getLadung().size();i++){ System.out.println(Main.lkw.getLadung().get(i)); System.out.println(Main.lkw.getLadung().get(i).getRaum()); if(Main.lkw.getLadung().get(i).getRaum()!=1){ ret=-1; System.out.println("achtung!!!!"); } } } catch (IOException e) { System.err.println(e.getMessage() + " " + e.getClass()); } return ret; } I call the methode ergebniss from a JavaFx Gui class.
how to sort linkedhashmap based on key . Here I used an object as a key
I am using the linked hashmap to populate values in expandable list .I successfully populate them. Here key is the menuitems and values are corresponding modifiers I places two buttons foe increasing and decreasing quantity of menu items .As it is the key I remove them and update them and again I put them in the list. This time they are inserting on the lastrow . How to placethem in same position as they were before deletion? The function where i update my key. public void putminusquantity(int pos) { try { SaleDetailsMenuItems aa = (SaleDetailsMenuItems)listDataChild.keySet().toArray()[pos]; List<ModifList> modlist =listDataChild.get(aa); //modlist.add(mli); listDataChild.remove(aa); int qty = Integer.parseInt(aa.getQuantity()); float priced = Float.parseFloat(aa.getPrice()); //Double finaltotal1 = Math.round( priced * 100.0 ) / 100.0; //Toast.makeText(getApplicationContext(), finaltotal1.toString(), Toast.LENGTH_SHORT).show(); System.out.println(qty); float priced1 = priced / qty; if(qty>1) { qty--; priced = priced1 * qty; String quantity1 = Integer.toString(qty); String price1 = Float.toString(priced); aa.setQuantity(quantity1); aa.setPrice(price1); listDataChild.put(aa, modlist); listviewAdapter = new ExpandableListAdapter(getApplicationContext(), listDataChild); list.setAdapter(listviewAdapter); listviewAdapter.notifyDataSetChanged(); resetquantity(); settotal(); } else { Toast.makeText(getApplicationContext(), "Invalid Quantity", Toast.LENGTH_SHORT).show(); } } catch(Exception e) { System.out.println(e); } } Here is the model class: class SaleDetailsMenuItems extends Sale { int i; private int id; private String name; private String price; private String quantity; private int statuss; private String itemnote; private long saledetailId; private long saleid; private int menutype; private long menu_id; private int istaxinclusive; private int coursing_id; private String seatname; private int seatId; private String reason; // private int discountdtls; private int istaxexmpt; private float taxpercent; //private float inctaxpercent; private float taxamt; private float incltaxamt; private int ordertype; private boolean istaxincl; private int storeid; private int crtdby; private int modby; private int status; public SaleDetailsMenuItems(int i1,String item, String quantity, String price, int id, int statuss,String itemnote) { // TODO Auto-generated constructor stub this.i=i1; this.id=id; this.name = item; this.quantity = quantity; this.price = price; this.statuss = statuss; this.itemnote = itemnote; //this.flag = flag; } public int getStatuss() { return statuss; } public void setStatuss(int statuss) { this.statuss = statuss; } public long getSaledetailId() { return saledetailId; } public void setSaledetailId(long saledetailId) { this.saledetailId = saledetailId; } public long getSaleid() { return saleid; } public void setSaleid(long saleid) { this.saleid = saleid; } public int getMenutype() { return menutype; } public void setMenutype(int menutype) { this.menutype = menutype; } public long getMenu_id() { return menu_id; } public void setMenu_id(long menu_id) { this.menu_id = menu_id; } public int getIstaxinclusive() { return istaxinclusive; } public void setIstaxinclusive(int istaxinclusive) { this.istaxinclusive = istaxinclusive; } public int getCoursing_id() { return coursing_id; } public void setCoursing_id(int coursing_id) { this.coursing_id = coursing_id; } public String getSeatname() { return seatname; } public void setSeatname(String seatname) { this.seatname = seatname; } public int getSeatId() { return seatId; } public void setSeatId(int seatId) { this.seatId = seatId; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public int getIstaxexmpt() { return istaxexmpt; } public void setIstaxexmpt(int istaxexmpt) { this.istaxexmpt = istaxexmpt; } public float getTaxpercent() { return taxpercent; } public void setTaxpercent(float taxpercent) { this.taxpercent = taxpercent; } public float getTaxamt() { return taxamt; } public void setTaxamt(float taxamt) { this.taxamt = taxamt; } public float getIncltaxamt() { return incltaxamt; } public void setIncltaxamt(float incltaxamt) { this.incltaxamt = incltaxamt; } public int getOrdertype() { return ordertype; } public void setOrdertype(int ordertype) { this.ordertype = ordertype; } public boolean isIstaxincl() { return istaxincl; } public void setIstaxincl(boolean istaxincl) { this.istaxincl = istaxincl; } public int getStoreid() { return storeid; } public void setStoreid(int storeid) { this.storeid = storeid; } public int getCrtdby() { return crtdby; } public void setCrtdby(int crtdby) { this.crtdby = crtdby; } public int getModby() { return modby; } public void setModby(int modby) { this.modby = modby; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getQuantity() { return quantity; } public void setQuantity(String quantity) { this.quantity = quantity; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getStatus() { return statuss; } public void setStatus(int statuss) { this.statuss = statuss; } public String getItemnote() { return itemnote; } public void setItemnote(String itemnote) { this.itemnote = itemnote; } } I am using this class's object as key in my Map.
TreeMap Is the way to sort the map by key. May be this will help you
I need something like a multi dimensional array but using a for loop [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 9 years ago. Improve this question String[] item ={"[1]hotdog", "[2]eggpie","[3]menudo","[4]pizza","[5]lumpia"}; int[] cost = {5, 10, 15, 20, 25}; int[] selling = {10,15,20,25,30,}; int[] qty = {2,4,6,8,10}; for(int b = 0; b<5;b++) { for(int c = 0; c<=1;c++) { for(int d = 0; d<=1;d++) { for(int e = 0; e<=1;e++) { System.out.println(" " + item[b] + "\t" + cost[c] + "\t\t" + selling[d] + "\t\t" + qty[e]); } } } } It doesn't run how I want it to run; I want it to run like a table but using a for loop only not using an array[][].
Just use a regular for loop to iterate over all arrays at once: String[] item ={"[1]hotdog", "[2]eggpie","[3]menudo","[4]pizza","[5]lumpia"}; int[] cost = {5, 10, 15, 20, 25}; int[] selling = {10,15,20,25,30,}; int[] qty = {2,4,6,8,10}; for (int i = 0; i < item.length; i++) { System.out.println(" " +item[i]+"\t"+cost[i]+"\t\t"+selling[i]+"\t\t"+qty[i]); } I would recommend putting all of these fields in an object, and then you can iterate over an array of that object.
Take a look at the Guava libraries Table collection.
public class Item { private int position; private String name; private int selling; private int quantity; private int cost; public Item() { position = 0; name=""; selling = 0; quantity =0; cost = 0; } public String GetState() { return String.format("{0} {0} {0} {0} {0} {0}", position,name,selling,cost,quantity); } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSelling() { return selling; } public void setSelling(int selling) { this.selling = selling; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getCost() { return cost; } public void setCost(int cost) { this.cost = cost; } } package test; import java.util.ArrayList; import java.util.List; public class ItemTest { public static void main(String[] args) { Item i = new Item(); List<Item> items = new ArrayList<Item>(); items.add(i); items.add(i); for (Item item : items) { System.out.println(item.GetState()); } } } console out : [0] 0 0 0 [0] 0 0 0