How to put inner JSONArray data into vector? The program only crash when i want to put data into the vector when I just print the data everythink works fine. Why? How to fix this?
When I run the program with vector:
0
Budapest
Szolnok
time: 0 2018.10.21. 11:20 2018.10.21. 13:25
Exception in thread "main" java.lang.NullPointerException
at Routes.addTime(Routes.java:20)
at JSONReader.main(JSONReader.java:30)
And when I run whitout vecor (just print to the console the good output):
0
Budapest
Szolnok
time: 0 2018.10.21. 11:20 2018.10.21. 13:25
time: 1 2018.10.21. 13:20 2018.10.21. 15:25
1
Veszprem
Budapest
time: 0 2018.10.30. 09:35 2018.10.30. 11:02
2
Veszprem
Gyor
time: 0 2018.11.10. 15:46 2018.11.10. 16:50
1
Gyor
Szombathely
time: 0 2018.11.05. 13:10 2018.11.05. 14:50
JSONReader.java
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONReader {
static String JSON_STRING = "{\"routes\": [{\"id\": 0,\"from\": \"Budapest\",\"to\": \"Szolnok\",\"times\": [{ \"id\": 0, \"start\": \"2018.10.21. 11:20\", \"arrive\": \"2018.10.21. 13:25\" },{ \"id\": 1, \"start\": \"2018.10.21. 13:20\", \"arrive\": \"2018.10.21. 15:25\" }]}, {\"id\": 1,\"from\": \"Veszprem\",\"to\": \"Budapest\",\"times\": [{ \"id\": 0, \"start\": \"2018.10.30. 09:35\", \"arrive\": \"2018.10.30. 11:02\" }]}, {\"id\": 2,\"from\": \"Veszprem\",\"to\": \"Gyor\",\"times\": [{ \"id\": 0, \"start\": \"2018.11.10. 15:46\", \"arrive\": \"2018.11.10. 16:50\" }],}, {\"id\": 1,\"from\": \"Gyor\",\"to\": \"Szombathely\",\"times\": [{ \"id\": 0, \"start\": \"2018.11.05. 13:10\", \"arrive\": \"2018.11.05. 14:50\" }],}]}";
public static void main(String[] args) {
//RoutSystem routsystem = new RoutSystem();
JSONObject object = new JSONObject(JSON_STRING);
JSONArray routes = object.getJSONArray("routes");
for (int y = 0; y < routes.length(); y++) {
JSONObject route = routes.getJSONObject(y);
int id = route.getInt("id");
String from = route.getString("from");
String to = route.getString("to");
JSONArray time = route.getJSONArray("times");
System.out.println(id);
System.out.println(from);
System.out.println(to);
Routes rout = new Routes(id, from, to);
for (int z = 0; z < time.length(); z++) {
JSONObject valami = time.getJSONObject(z);
int id1 = valami.getInt("id");
String start = valami.getString("start");
String arrive = valami.getString("arrive");
System.out.println("time: " + id1 + " " + start + " " + arrive);
rout.addTime(id1, start, arrive);
}
//rout.printRout();
//routsystem.addRoute(rout);
}
}
}
Routes.java
import java.util.Vector;
public class Routes {
int id;
String from, to;
Vector<Times> times;
public Routes(int _id, String _from, String _to) {
id = _id;
from = _from;
to= _to;
}
public void addTime(int id, String start, String arrive) {
Times time = new Times();
time.setid(id);
time.setstart(start);
time.setarrive(arrive);
times.add(time);
}
public void printRout() {
System.out.println(id);
System.out.println(from);
System.out.println(to);
for (Times t : times) {
System.out.println(t.getid() + " " + t.getstart() + " " + t.getarrive());
}
}
}
Times.java
public class Times {
int id;
String start, arrive;
public Times() {
id = 0;
start = "";
arrive = "";
}
public int getid() {
return id;
}
public String getstart() {
return start;
}
public String getarrive() {
return arrive;
}
public void setid(int i) {
id = i;
}
public void setstart(String s) {
start = s;
}
public void setarrive(String a) {
arrive = a;
}
}
The problem is you're not initializing your vector before adding objects into it.
That's why you get a nullpointer exception. You should look at what a nullpointer is.
what is a nullpointer exception and how do i fix it.
Related
I have a lot of JSON files in the following format. I want to map one attribute named Timings to integer.
test.json
"Rating": {
"ratingValue": "4.636365",
"bestRating": "5",
"worstRating": "1",
"ratingCount": "66"
},
"Timings": {
"cookTime": "PT1H",
"prepTime": "PT10M",
"totalTime": "PT1H10M"
}
I want to store the output in another JSON file after mapping. Let say, totalTime in Timings is 1H10M then we assign this as "totalTime:7". If its, "30M" we can assign this as "totalTime:3". I want to do this using java.
Required output
"Rating":
{
"ratingValue": "4.636365",
},
"Timings":
{
"totalTime": "7"
}
I tried this :
class Timings {
private String cookTime;
private String prepTime;
private String totalTime;
public String getCookTime() {
return cookTime;
}
public void setCookTime(String cookTime) {
this.cookTime = cookTime;
}
public String getPrepTime() {
return prepTime;
}
public void setPrepTime(String prepTime) {
this.prepTime = prepTime;
}
public String getTotalTime() {
return totalTime;
}
public void setTotalTime(String totalTime) {
this.totalTime = totalTime;
}
#Override
public String toString() {
return "Timings [cookTime=" + cookTime + ", prepTime=" + prepTime + ", totalTime=" + totalTime + "]";
}
}
public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Timings obj = mapper.readValue(new File("C:\\Users\\Anish\\Desktop\\abc.json"), Timings.class);
String totalTime = obj.getTotalTime().split("PT")[1];
int total = 0;
if (totalTime != null && !totalTime.isEmpty()) {
total = returnTotalTime(totalTime);
}
ObjectNode mainNode = mapper.createObjectNode();
ObjectNode timingNode = mapper.createObjectNode();
childNode.put("totalTime", (total > 9) ? (total / 10) : total);
mainNode.set("Timings", timingNode);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mainNode);
System.out.println(json);
}
private static int returnTotalTime(String totalTime) {
if (totalTime != null && !totalTime.isEmpty()) {
String[] timeValues = totalTime.split("H");
if (timeValues.length == 0) {
return 0;
} else if (timeValues.length < 2) {
if (timeValues[0].contains("M")) {
return (timeValues[0].split("M").length <= 0) ? 0
: timeValues[0].split("M")[0].isEmpty() ? 0 : Integer.parseInt(timeValues[0].split("M")[0]);
}
return timeValues[0].isEmpty() ? 0 : Integer.parseInt(timeValues[0]) * 60;
}
int hour = timeValues[0].isEmpty() ? 0 : Integer.parseInt(timeValues[0]) * 60;
int mins = (timeValues[1].split("M").length <= 0) ? 0
: timeValues[1].split("M")[0].isEmpty() ? 0 : Integer.parseInt(timeValues[1].split("M")[0]);
return (hour + mins);
}
return 0;
}
abc.json
{
"cookTime": "PT1H",
"prepTime": "PT10M",
"totalTime": "PT1H10M"
}
Output :
{
"Timings" : {
"totalTime" : "7"
}
}
When "totalTime": "PT30M", then :
Output :
{
"Timings" : {
"totalTime" : "3"
}
}
When "totalTime": "PT23M", then :
Output :
{
"Timings" : {
"totalTime" : "2"
}
}
You can use any library to parse Json data depending of your goals.
for example org.json is a good choice and here is an example:
JSONObject object = new JSONObject(stringData);
String time = object.getJSONObject("Timings").getString("cookTime");
this way you can parse every Json data and do your business after that.
Also you can use mapping your data to a class with gson or other tools.
I am confused on the output of the code. I want to know for each call on variables i and s, which class is used to call the variables. The question involves variable shadowing. Also I want to know how s keeps on changing throughout the lines in the main method.
public class A {
public int i = 0;
public static String s = "";
public A(int i) {
System.out.println(i);
s += "x";
}
public A debug() {
if (this instanceof B) {
System.out.println("Spam");
s += "s";
}
return this;
}
}
public class B extends A {
public int i = 100;
public static String s = "s";
public B(int i, String s) {
super(i);
this.i += 5;
this.s = s;
}
public static void main(String[] argv) {
String s = "";
B b = new B(0, s);
System.out.println(b.i + " " + b.s);
s += "foo";
A a = new B(42, s);
System.out.println(a.i + " " + a.s);
System.out.println(b.debug().s + " " + b.i + " " + b.s);
System.out.println(a.debug().s + " " + a.i + " " + a.s);
}
}
Here is the output of that code:
0
105
42
0 xx
Spam
xxs 105 foo
Spam
xxss 0 xxss
public class A {
public int i = 0; //not changed, because it is not overrided
public static String s = "";
public A(int i) {
System.out.println(i); //1. 0, 3. 42
s += "x"; //After second run s="xx", because it is static
}
public A debug() {
if (this instanceof B) {
System.out.println("Spam"); //5, 7. Spam
s += "s"; //s = "xxs", than "xxss" because it is static
}
return this;
}
}
public class B extends A {
public int i = 100;
public static String s = "s";
public B(int i, String s) {
super(i);
this.i += 5; //First run: i=105, Second run: i=47
this.s = s; //First run: public static String s="", Second run: public static String a.s="foo"
}
public static void main(String[] argv) {
String s = "";
B b = new B(0, s);
System.out.println(b.i + " " + b.s); //2. 105
s += "foo"; //B.s is now foo
A a = new B(42, s);
System.out.println(a.i + " " + a.s); //3. 0 xx
System.out.println(b.debug().s + " " + b.i + " " + b.s); //1. because of (A)b.s = xxs, 2. b.i = 105, 3. b.s = foo
System.out.println(a.debug().s + " " + a.i + " " + a.s); //(A)a.s = "xxss", (A)a.i = 0, (A)a.s = "xxss"
}
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I am currently trying to write a program that will allow me to use insertion sorting to find the title and to find the year in which the movie was released. Currently whenever I compile and run the program, I end up with a random String that looks like this "[LMovie2;#15f45c9" however, it is different every single time. If someone could help me get an idea of where I am going wrong,(possibly in my array) that would be awesome. I would also like feedback on how to ask questions since this is my first post. Thank you for your time and consideration.
public class Movie2
{
private String title;
private int year;
private String studio;
public Movie2(String t, int y, String s)
{
title = t;
studio = s;
year = y;
}
public String toString()
{
String movies;
movies = title + " \t" + year + "\t" + studio;
return movies;
}
public String getTitle()
{
return title;
}
public void setTitle(String t)
{
title = t;
}
public String getStudio()
{
return studio;
}
public void setStudio(String s)
{
studio = s;
}
public int getYear()
{
return year;
}
public void setYear(int y)
{
year = y;
}
}
public class testMovies2
{
public static void main(String[] args)
{
Movie2[] movies = new Movie2[10];
movies[0] = new Movie2("The Muppets Take Manhattan", 2001, "Columbia Tristar");
movies[1] = new Movie2("Mulan Special Edition", 2004, "Disney");
movies[2] = new Movie2("Shrek 2", 2004, "Dreamworks");
movies[3] = new Movie2("The Incredibles", 2004, "Pixar");
movies[4] = new Movie2("Nanny McPhee", 2006, "Universal");
movies[5] = new Movie2("The Curse of the Were-Rabbit", 2006, "Aardman");
movies[6] = new Movie2("Ice Age", 2002, "20th Century Fox");
movies[7] = new Movie2("Lilo & Stitch", 2002, "Disney");
movies[8] = new Movie2("Robots", 2005, "20th Century Fox");
movies[9] = new Movie2("Monsters Inc.", 2001, "Pixar");
System.out.println(movies);
}
public static void insertionSort(Movie2[] a)
{
int[] source = { 12, 14, 15, 11, 13 };
int[] dest = new int[ source.length ];
for ( int i = 0 ; i < source.length ; i++ )
{
int next = source[ i ];
int insertindex = 0;
int k = i;
while ( k > 0 && insertindex == 0 )
{
if ( next > dest[ k - 1 ] )
{
insertindex = k;
}
else
{
dest[ k ] = dest[ k - 1 ];
}
k--;
}
dest[ insertindex ] = next;
}
}
}
You need to iterate over your movies
Change this
System.out.println(movies);
to
for(Movie2 m : movies)
System.out.println(m.toString());
I am trying to understand stacks with Objects, so I typed this out, but the problem is that I am getting this really weird message that I can't make sense of. It says "Exception in thread "main" java.lang.NoSuchMethodError: Stack.push(Ljava/lang/Object;)V
at TestObjectStack.main(TestObjectStack.java:12)". I googled it, but I still can't figure out what I'm doing wrong. I redid the main method header, but that didn't fix it. Does anyone have any suggestions or insight that I am missing? Thanks a lot!:
public class TestObjectStack
{
public static void main(String[] args)
{
Object o;
Stack test = new Stack();
test.push("Fred");
test.push(20);
test.push(new ThingB("Barney", 42));
Stack copy = new Stack(test);
System.out.println("Stack test: " + test);
System.out.println(test.pop());
System.out.println("Stack test: " + test);
System.out.println("Stack copy: " + copy);
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a String");
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a string");
if(test.isEmpty()) System.out.println("empty");
}
}
class ThingB
{
private String _name;
private int _ID;
public ThingB(String name, int ID)
{
_name = name;
_ID = ID;
}
public String toString()
{
return "Thing B - name - " + _name + " ID = " + _ID;
}
}
class Stack
{
private Object[] _store;
private int _top;
private static final int MAXSIZE = 50;
public Stack()
{
_store = new Object[MAXSIZE];
_top = 0;
}
public Stack(Stack other)
{
_store = new Object[other._store.length];
_top = other._top;
for(int i = 0; i < _top; ++i)
{
_store[i] = other._store[i];
}
}
public boolean isEmpty()
{
return (_top == 0);
}
public void push(Object item)
{
if(_top >= _store.length)
{
Object[] temp = new Object[_store.length+ MAXSIZE];
for(int i = 0; i < _top; ++i)
{
temp[i] = _store[i];
}
_store = temp;
}
_store[_top] = item;
++_top;
}
public Object pop()
{
if(_top == 0) return 0;
--_top;
return _store[_top];
}
public String toString()
{
String s = "";
s = s + "--Top--";
for(int i = _top-1; i >= 0; --i)
{
s = s + " " + _store[i];
}
s = s + "--Bottom--";
return s;
}
}
I executed your code in the IDE: IntelliJ IDEA. And I have the following result:
Stack test: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
Thing B - name - Barney ID = 42
Stack test: --Top-- 20 Fred--Bottom--
Stack copy: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
20
Not a String
Fred
String length = 4
empty
Your source code is working fine, maybe you need to adjust your IDE parameters. Try with a simple "Hello World" program.
Best regards,
Alvaro
I have created a class Hotel defined as follows:
import java.util.Random;
public class Hotel {
private Osoba[] tab = new Osoba[100];
public void zamelduj(Osoba os, int num) {
if (tab[num - 1] == null) {
System.out.println("Pokoj o numerze " + num + "jest zajety");
return;
}
tab[num - 1] = os;
}
public void wymelduj(int num) {
tab[num - 1] = null;
}
public void zamienOsoby(int num1, int num2) {
Osoba o = tab[num1 - 1];
tab[num1 - 1] = tab[num2 - 1];
tab[num2 - 1] = o;
}
public void znajdzWolnePokoje() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println(i + 1);
}
}
public void przydzielPokoje50() {
for (int i = 0; i < 50; i++) {
Random r = new Random();
Osoba o = new Osoba();
int num = r.nextInt(100);
tab[num] = o;
}
}
public void wypisz() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println("Pokoj nr. " + (i + 1) + " jest wolny");
else System.out.println("Pokoj nr. " + i + " jest zajety przez " + tab[i].imie + " " + tab[i].nazwisko);
}
}
public static void main(String[] args) {
Hotel h = new Hotel();
//h.przydzielPokoje50();
//h.wypisz();
h.zamelduj(null, 30);
}
}
I also have a class Osoba:
public class Osoba {
public String imie;
public String nazwisko;
Osoba() {
imie = null;
nazwisko = null;
}
Osoba(String imie, String nazwisko) {
this.imie = imie;
this.nazwisko = nazwisko;
}
}
I want to execute the method Zamelduj, which will assign a person (Osoba) to a cell in a table. However, every time I insert something other than null in the following it says that the first argument is not a capable parameter of the method.
h.zamelduj(null, 30);
What am I doing wrong?
I think your problem is that on the line " h.zamelduj(null, 30);" you need to create a new Osoba:
h.zamelduj(new Osoba("o.o", "._.!"), 30);
what happens is that the function is expecting a Osoba, if you give it another thing, it refuses. i hope it helps
You need to create an object of the class hotel (in your class from where you want to call the method type):
Hotel myObjectHotel = new Hotel();
And then you can call the method trough:
myHotelObject. zamelduj(give parameters here);
:)
Update:
Missed the real question. Just focused on the topic. I'm sorry. ;)