My program prints out a library. Each library is composed of books. Each book is composed of a title and the authors of that book. I have a driver program, a Library class, and a Book class. My issue is that when I use my driver program that uses my toString() methods in the library and book classes to print the library, the authors of each book are appearing as [author, ;, author, ;, author] and I want them to print as author; author; author.
Expected output: http://prntscr.com/810ik2
My output: http://prntscr.com/810ipp
My input: http://prntscr.com/810j6f
getAuthors is the method in my driver program that separates the authors (In the input file that the authors are taken from authors are separated by '*' instead of separated by ';' which is what i need in my output)
Please let me know in the comments if there is too little info, too much info, if what I've given is too confusing, or if I didn't explain anything properly. I'm new to Java and fairly new at posting questions here so please go easy on me. Thank you!
Edit: Just in case here are my three classes (only the important stuff):
Book.java:
import java.util.*;
public class Book implements Comparable<Book>
{
private final String myTitle;
private final ArrayList<String> myAuthors;
public Book(final String theTitle, final ArrayList<String> theAuthors)
{
if (theTitle == "" || theAuthors.isEmpty() ||
theTitle == null || theAuthors.get(0) == null)
{
throw new IllegalArgumentException(
"The book must have a valid title AND author.");
}
else
{
myTitle = theTitle;
myAuthors = new ArrayList<String>();
for (int i = 0; i < theAuthors.size(); i++)
{
myAuthors.add(theAuthors.get(i));
}
}
}
public String toString()
{
String result = "\"" + myTitle + "\" by ";
for (int i = 0; i < myAuthors.size(); i++)
{
result += (String)myAuthors.get(i);
}
return result;
}
}
Library.java:
import java.util.*;
public class Library
{
public Library(final ArrayList<Book> theOther)
{
if (theOther == null)
{
throw new NullPointerException();
}
else
{
myBooks = new ArrayList<Book>();
for (int i = 0; i < theOther.size(); i++)
{
myBooks.add(theOther.get(i));
}
}
}
public ArrayList<Book> findTitles(final String theTitle)
{
ArrayList<Book> titleList = new ArrayList<Book>();
for (int i = 0; i < myBooks.size(); i++)
{
if (myBooks.get(i).getTitle().equals(theTitle))
{
titleList.add(myBooks.get(i));
}
}
return titleList;
}
public String toString()
{
String result = "";
for (int i = 0; i < myBooks.size(); i++)
{
String tempTitle = myBooks.get(i).getTitle();
ArrayList<String> tempAuthors = myBooks.get(i).getAuthors();
Book tempBook = new Book(tempTitle, tempAuthors);
result += (tempBook + "\n");
}
return result;
}
}
LibraryDriver.java:
import java.util.*;
import java.io.*;
public class LibraryDriver
{
public static void main(String[] theArgs)
{
Scanner inputFile = null;
PrintStream outputFile = null;
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
ArrayList<Book> books2 = new ArrayList<Book>();
String[] filesInputs = new String[]{"LibraryIn1.txt", "LibraryIn2.txt"};
try
{
outputFile = new PrintStream(new File("LibraryOut.txt"));
for (String fileInput : filesInputs)
{
inputFile = new Scanner(new File(fileInput));
while (inputFile.hasNext())
{
String title = "";
String input = inputFile.nextLine();
//Read title
title = input;
input = inputFile.nextLine();
authors = getAuthors(input);
//Insert title & authors into a book
Book tempBook = new Book(title, authors);
//Add this book to the ArrayList<Book> of books
books.add(tempBook);
}
Library myLib = new Library(books);
outputFile.println(myLib);
inputFile.close();
myLib.sort();
outputFile.println(myLib);
}
}
catch (Exception e)
{
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
inputFile.close();
outputFile.close();
}
public static ArrayList<String> getAuthors(String theAuthors)
{
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++)
{
if (theAuthors.charAt(i) == '*')
{
if (lastAsteriskIndex > 0)
{
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
}
else
{
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0)
{
authorList.add(theAuthors);
}
return authorList;
}
}
So, I hobbled together a runnable example of your code as best as I could and using
The Hobbit
Tolkien, J.R.R
Acer Dumpling
Doofus, Robert
As input, I get
"The Hobbit" by Tolkien, J.R.R
"Acer Dumpling" by Doofus, Robert
The code:
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class LibraryDriver {
public static void main(String[] theArgs) {
// ArrayList<Book> books = new ArrayList<>(25);
// books.add(
// new Book("Bananas in pajamas",
// new ArrayList<>(Arrays.asList(new String[]{"B1", "B2"}))));
//
// Library lib = new Library(books);
// System.out.println(lib.toString());
Scanner inputFile = null;
PrintStream outputFile = null;
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
ArrayList<Book> books2 = new ArrayList<Book>();
String[] filesInputs = new String[]{"LibraryIn1.txt"}; //, "LibraryIn2.txt"};
try {
outputFile = new PrintStream(new File("LibraryOut.txt"));
for (String fileInput : filesInputs) {
inputFile = new Scanner(new File(fileInput));
while (inputFile.hasNext()) {
String title = "";
String input = inputFile.nextLine();
//Read title
title = input;
input = inputFile.nextLine();
authors = getAuthors(input);
//Insert title & authors into a book
Book tempBook = new Book(title, authors);
//Add this book to the ArrayList<Book> of books
books.add(tempBook);
}
Library myLib = new Library(books);
outputFile.println(myLib);
inputFile.close();
// myLib.sort();
// outputFile.println(myLib);
}
} catch (Exception e) {
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
inputFile.close();
outputFile.close();
}
public static ArrayList<String> getAuthors(String theAuthors) {
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++) {
if (theAuthors.charAt(i) == '*') {
if (lastAsteriskIndex > 0) {
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
} else {
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0) {
authorList.add(theAuthors);
}
return authorList;
}
public static class Library {
private ArrayList<Book> myBooks;
public Library(final ArrayList<Book> theOther) {
if (theOther == null) {
throw new NullPointerException();
} else {
myBooks = new ArrayList<Book>();
for (int i = 0; i < theOther.size(); i++) {
myBooks.add(theOther.get(i));
}
}
}
public ArrayList<Book> findTitles(final String theTitle) {
ArrayList<Book> titleList = new ArrayList<Book>();
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getTitle().equals(theTitle)) {
titleList.add(myBooks.get(i));
}
}
return titleList;
}
public String toString() {
String result = "";
for (int i = 0; i < myBooks.size(); i++) {
String tempTitle = myBooks.get(i).getTitle();
Book b = myBooks.get(i);
ArrayList<String> tempAuthors = b.getAuthors();
Book tempBook = new Book(tempTitle, tempAuthors);
result += (tempBook + "\n");
}
return result;
}
}
public static class Book implements Comparable<Book> {
private final String myTitle;
private final ArrayList<String> myAuthors;
public Book(final String theTitle, final ArrayList<String> theAuthors) {
if (theTitle == "" || theAuthors.isEmpty()
|| theTitle == null || theAuthors.get(0) == null) {
throw new IllegalArgumentException(
"The book must have a valid title AND author.");
} else {
myTitle = theTitle;
myAuthors = new ArrayList<String>();
for (int i = 0; i < theAuthors.size(); i++) {
myAuthors.add(theAuthors.get(i));
}
}
}
public String toString() {
String result = "\"" + myTitle + "\" by ";
for (int i = 0; i < myAuthors.size(); i++) {
result += (String) myAuthors.get(i);
}
return result;
}
#Override
public int compareTo(Book o) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public String getTitle() {
return myTitle;
}
public ArrayList<String> getAuthors(String theAuthors) {
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++) {
if (theAuthors.charAt(i) == '*') {
if (lastAsteriskIndex > 0) {
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
} else {
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0) {
authorList.add(theAuthors);
}
return authorList;
}
public ArrayList<String> getAuthors() {
return myAuthors;
}
}
}
Consider providing a runnable example which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses
Related
I have Person class and its properties are:
public class Person {
String Name;
Gender gender;
Person father;
Person mother;
Person partner;
ArrayList<Person> childs = new ArrayList<Person>();
public enum Gender {
MAN, WOMAN
}
public Person(String name, Gender gender){
this.Name = name;
this.gender = gender;
}
public void marryTo(Person person){
this.partner = person;
person.partner = this;
}
public void setChildFromMarriage(Person child){
childs.add(child);
partner.childs.add(child);
}
}
I am getting the properties of persons from a txt file. Each line represents one person. Properties in a line are separated by a slash.
Txt file: https://i.stack.imgur.com/ha3Wi.png
package classPackage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import classPackage.Person.Gender;
public class MainClass {
public static void main (String[] args)
{
try {
MainClass obj = new MainClass ();
obj.run ();
} catch (Exception e) {
e.printStackTrace ();
}
}
ArrayList<Person> persons = new ArrayList<Person>();
public void run () {
ArrayList<String> lines = null;
try {
lines = readFile("/persons.txt");
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(String line: lines) {
Person p = loadPerson(line);
persons.add(p);
}
}
private Person loadPerson(String line) {
StringBuilder sb = new StringBuilder();
int which_gender = 0;
Gender gender = null;
String name = null;
int which_father = 0;
int which_mother = 0;
int which_partner = 0;
int s = 0;
String strS;
for (int j = 0; j < line.length(); j++) {
char ch = line.charAt(j);
if ((int) ch == 47) {
strS = sb.toString();
s++;
sb.setLength(0);
if (s == 1) {
which_gender = Integer.parseInt(strS);
if(which_gender == 0) {
gender = Gender.MAN;
} else if(which_gender == 0) {
gender = Gender.WOMAN;
}
}
else if(s == 2)
name = strS;
else if(s == 3)
which_father = Integer.parseInt(strS);
else if(s == 4)
which_mother = Integer.parseInt(strS);
else if(s == 5)
which_partner = Integer.parseInt(strS);
} else {
sb.append(ch);
}
}
Person person = new Person(name, gender);
if(which_father != -1) {
person.father = persons.get(which_father);
}
if(which_mother != -1) {
person.mother = persons.get(which_mother);
persons.get(which_mother).setChildFromMarriage(person);
}
if(which_partner != -1) {
person.marryTo(persons.get(which_partner));
}
return person;
}
private ArrayList<String> readFile(String filename) throws IOException, URISyntaxException {
File file = new File(getClass().getResource(filename).toURI());
BufferedReader reader = new BufferedReader(new FileReader(file));
ArrayList<String> lines = new ArrayList<String>();
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;
}
lines.add(line);
}
return lines;
}
}
I tried to summarize my problem with these lines of code.
My problem is:
I don't know if it is related to the primitiveness of the txt file but I have 2 problems.
e.g. I always need to initialize son objects after their father. Otherwise "persons.get(which_father);" It will return IndexOutOfBoundsException error.
For example, there are 10 people registered in my txt file. (0-9 index) Let the father of the person in 9.index be the person in index 3. When I delete the person in index 1 and delete and save the 1.index line from the txt file; now our man's father is in index 2, not index 3. Changing the number of the father from 3 to 2 is complicated.
I feel unnecessarily complicated to operate on the txt file. How can I solve these 2 problems and code complexity?
I have been given the problem to complete, and the algorithms to find the first and follow, but my problem is I cant quite find a data structure to implement to find these sets.
import java.util.Stack;
public class FirstFollowSet {
private final String[] term_tokens = { "begin", "end", ";", "if", "then", "else", "fi", "i", "=", "+", "-", "*",
"/", "(", ")", "const" };
private final static String[] non_term_tokens = { "Start", "Prog", "Block", "Body", "S", "E", "T", "F" };
private static RuleStack rules;
private Stack<String> firstSet;
private Stack<String> followSet;
private boolean is_terminal(String str) {
boolean test = false;
for (int i = 0; i < term_tokens.length; i++) {
if (str.equals(term_tokens[i]))
test = true;
}
return test;
}
private boolean is_non_term(String str){
for(int i = 0; i < non_term_tokens.length; i++)
{
if(str.equals(non_term_tokens[i]))
{
return true;
}
}
return false;
}
private class Rule{
String def, token;
public Rule()
{
def = "";
token = "";
}
public Rule(String d, String t)
{
def = d;
token = t;
}
public String getDef() {
return def;
}
public String getToken() {
return token;
}
public String toString()
{
String str = "";
str+= token + " " + def + '\n';
return str;
}
}
public class RuleStack{
Stack<Rule> rules;
public RuleStack(String grammar)
{
if(grammar.equals("G1"));
{
rules = new Stack();
Rule rule = new Rule("Prog", "Start");
rules.push(rule);
rule = new Rule("Block #", "Prog");
rules.push(rule);
rule = new Rule("begin Body end", "Block");
rules.push(rule);
rule = new Rule("begin S end", "Body");
rules.push(rule);
rule = new Rule("Body ; S", "Body");
rules.push(rule);
rule = new Rule("S", "Body");
rules.push(rule);
rule = new Rule("if E then S else S fi", "S");
rules.push(rule);
rule = new Rule("if E else S fi", "S");
rules.push(rule);
rule = new Rule("i = E", "S");
rules.push(rule);
rule = new Rule("Block", "S");
rules.push(rule);
rule = new Rule("E + T", "E");
rules.push(rule);
rule = new Rule("E * T", "E");
rules.push(rule);
rule = new Rule("T", "E");
rules.push(rule);
rule = new Rule("T * F", "T");
rules.push(rule);
rule = new Rule("T / F", "T");
rules.push(rule);
rule = new Rule("F", "T");
rules.push(rule);
rule = new Rule("const", "F");
rules.push(rule);
rule = new Rule("( E )", "F");
rules.push(rule);
}
}
}
public FirstFollowSet()
{
rules = new RuleStack("G1");
firstSet = new Stack();
followSet = new Stack();
}
public String FindFirstSet(String str, Stack<String> used)
{
if(used.contains(str))
{
return null;
}
String firstToken = "";
String win = "";
if(str.indexOf(" ") != -1)
firstToken = str.substring(0, str.indexOf(" "));
else
firstToken = str;
if(is_terminal(firstToken))
{
if(!(firstSet.contains(firstToken)))
win = firstToken;
if(win.equals("") != true)
firstSet.push(win);
}
else if(is_non_term(firstToken) && !(used.contains(firstToken)))
{
used.push(firstToken);
if(firstToken.equals("lambda"))
{
if(!(firstSet.contains(firstToken)))
win = firstToken;
}
else
{
RuleStack rules = new RuleStack("G1");
while(rules.rules.isEmpty() != true)
{
Rule winner = rules.rules.pop();
if(winner.token.equals(firstToken))
{
String test = FindFirstSet(winner.def, used);
if(!(test.equals("lambda")))
{
if(!(firstSet.contains(test)))
win = test;
}
}
}
}
}
return win;
}
public String findFollowSet(String str)
{
if(str.equals("S"))
{
followSet.push("$");
}
for(int i = 0; i < non_term_tokens.length; i++)
{
if(str.contains(non_term_tokens[i]))
{
int index = str.indexOf(non_term_tokens[i]);
Stack<String> used = new Stack();
FirstFollowSet test = new FirstFollowSet();
if(index > 0 && index < str.length()-1)
{
test.FindFirstSet(str, used);
while(test.firstSet.isEmpty() != true)
{
String token = firstSet.pop();
if(!(token.equals("lambda")))
test.followSet.push(token);
}
}
else if(index > 0 && index == str.length()-1)
{
}
}
}
}
public static void main(String[] args) {
FirstFollowSet test = new FirstFollowSet();
Stack<String> used = new Stack();
test.FindFirstSet("S", used);
while(test.firstSet.isEmpty() != true)
{
String str = test.firstSet.pop();
System.out.println(str);
}
}
}
This is the code I have so far, and the find first set works just fine, but the findfollowset method I'm not quite sure how to implement. The only idea I can seem to come up with is making a stack for each non-terminal symbol, apply the algorithm, and add each terminal symbol returned to the set it belongs to. This method just feel like its more work then necessary.
If anyone has ever solved this problem, or has seen a way to solve this problem I would just like to know what sort of data structure was used and how it the algorithm was implemented for said structure.
Thank you for taking the time to read this, and i appreciate any feedback given.
package modelo;
import java.util.ArrayList;
/**
*
* #author celeste
*/
public class Axioma {
public char getSimbolo() {
return simbolo;
}
public void setSimbolo(char simbolo) {
this.simbolo = simbolo;
}
public ArrayList<Character> getPrimeros() {
return primeros;
}
public void setPrimeros(ArrayList<Character> primeros) {
this.primeros = primeros;
}
public ArrayList<Character> getSiguientes() {
return siguientes;
}
public void setSiguientes(ArrayList<Character> siguientes) {
this.siguientes = siguientes;
}
public ArrayList<Character> getPredictivos() {
return predictivos;
}
public void setPredictivos(ArrayList<Character> predictivos) {
this.predictivos = predictivos;
}
public ArrayList<Character> getRegla() {
return regla;
}
public void setRegla(ArrayList<Character> regla) {
this.regla = regla;
}
private ArrayList<Character> primeros = new ArrayList<>();
private ArrayList<Character> siguientes = new ArrayList<>();
private ArrayList<Character> predictivos = new ArrayList<>();
private ArrayList<Character> regla = new ArrayList<>();
private char simbolo;
}
Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");
;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}
JSONArray issue = new JSONArray();
System.out.println("Enter Epic Name");
String epicName = input.next();
System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
root.put("issue", issue);
finaljson.put(root);
}
System.out.println("JSON DATA" + finaljson.toString());
Hey Making a JSON,as from the code if user will enter versionname is multiple time that it should not add in root jsonobject. so how to restrict it.
[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "ekey1"
}
],
"versionName": "v1"
},
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]
but want
[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "eky1"
},
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]
can you help me how to make this type of dynamic json data
If I understand correctly, you want the output to be like the second JSON array in your question. Changing where you loop should do the trick:
Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}
JSONArray issue = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Epic Name");
String epicName = input.next();
System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
}
root.put("issue", issue);
finaljson.put(root);
System.out.println("JSON DATA" + finaljson.toString());
I tested with the input you have. Here is the formatted JSON output:
[
{
"issue": [
{
"epickKey": "eky1",
"epickName": "e1"
},
{
"epickKey": "eky2",
"epickName": "e2"
}
],
"versionName": "vkey1",
"versionKey": "v1"
}
]
Read in your json using Gson:
Define Pojos for your Json Objects:
public class Epic {
String versionKey, versionName;
Issue issue;
}
public class Issue{
String epicName, epicKey;
}
Load Pojos from json using Gson
// Create gson object
Gson gson = new GsonBuilder().create();
// Load your json objects:
BufferedReader br = new BufferedReader(new FileReader("file.json"));
List<Epic> epics = gson.fromJson(br, new TypeToken<ArrayList<Epic>>() {}.getType());
Create the class structure you want for your "multi-issue-epics":
// This will be used to store in the format you want
public class MultiIssueEpic{
public String versionKey, versionName;
public Set<Issue> issueSet;
public MultiIssueEpic(Epic epic){
this.versionName = epic.versionName;
this.versionKey = epic.versionKey;
this.issueSet = new HashSet<>();
this.issueSet.add(epic.issue);
}
}
Build the MultiIssueEpic up from your List<Epic>:
Map<String, MultiIssueEpic> epicMap = new HashMap<>();
for(Epic epic : epics){
if(epicMap.contains(epic.versionName)){
// Add issue to existing MultiIssueEpic
epicMap.get(epic.versionName).issueSet.add(epic.issue);
} else{
// Add new MultiIssueEpic
epicMap.put(epic.versionName, new MultiIssueEpic(epic));
}
}
// Here is your list of MultiIssueEpics:
List<MultiIssueEpic> multiIssueEpics = new ArrayList<>(epicMap.values());
I change your code and I add two other class. One named Data for (versionKey, nameKey), the second one Epic for (epickName,epickKey)
and to generate Json, I use Gson lib.
This code :
Epic Class:
public class Epic {
private String epicName;
private String epicKey;
public Epic() {
}
public Epic(String epicName, String epicKey) {
this.epicName = epicName;
this.epicKey = epicKey;
}
public String getEpicName() {
return epicName;
}
public void setEpicName(String epicName) {
this.epicName = epicName;
}
public String getEpicKey() {
return epicKey;
}
public void setEpicKey(String epicKey) {
this.epicKey = epicKey;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Epic [epicName=");
builder.append(epicName);
builder.append(", epicKey=");
builder.append(epicKey);
builder.append("]");
return builder.toString();
}
}
Data Class :
import java.util.List;
public class Data {
private String versionName;
private String versionKey;
private List<Epic> epics;
public Data() {
}
public Data(String versionName, String versionKey, List<Epic> epics) {
this.versionName = versionName;
this.versionKey = versionKey;
this.epics = epics;
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public String getVersionKey() {
return versionKey;
}
public void setVersionKey(String versionKey) {
this.versionKey = versionKey;
}
public List<Epic> getEpics() {
return epics;
}
public void setEpics(List<Epic> epics) {
this.epics = epics;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((versionKey == null) ? 0 : versionKey.hashCode());
result = prime * result
+ ((versionName == null) ? 0 : versionName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Data other = (Data) obj;
if (versionKey == null) {
if (other.versionKey != null)
return false;
} else if (!versionKey.equals(other.versionKey))
return false;
if (versionName == null) {
if (other.versionName != null)
return false;
} else if (!versionName.equals(other.versionName))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Data [versionName=");
builder.append(versionName);
builder.append(", versionKey=");
builder.append(versionKey);
builder.append(", epics=");
builder.append(epics);
builder.append("]");
return builder.toString();
}
}
Main Class:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Data> datas = new ArrayList<Data>();
boolean add = false;
for (int j = 0; j < 2; j++) {
add = false;
Data data = new Data();
System.out.println("Enter Version Name");
data.setVersionName(input.next());
System.out.println("Enter Version Key");
data.setVersionKey(input.next());
Epic epic = new Epic();
System.out.println("Enter Epic Name");
epic.setEpicName(input.next());
System.out.println("Enter Epic Key");
epic.setEpicKey(input.next());
List<Epic> epics = new ArrayList<Epic>();
if(datas.isEmpty()){
epics.add(epic);
data.setEpics(epics);
datas.add(data);
}else{
for(Data d:datas){
if(d.equals(data)){
d.getEpics().add(epic);
add=true;
}
}
if(!add){
epics.add(epic);
data.setEpics(epics);
datas.add(data);
}
}
}
//Gson gson = new GsonBuilder().setPrettyPrinting().create();
//System.out.println(gson.toJson(datas));
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(datas);
System.out.println(jsonArray.toString());
}
}
PS: Url to download Gson API
Edit
I made a change in the Main Class to use json-lib-2.4-jdk15.jar
Take a look at this URL:
json-lib
I've dug up the following code for serializing an ItemStack in bukkit (Minecraft). I've been able to serialize an item in hand with the following:
itemString = ItemStackUtils.deserialize(player.getInventory().getItemInHand());
I can't figure out how to utilize the deserial call however. What I am trying to do is to pull an item from the players hand, serialize it, stick it into a config file, then when the player runs another command... deserialize it and slap it into their inventory. I am fairly certain this class will meet my needs if I just can get the last part working.
public final class ItemStackUtils {
public static String getEnchants(ItemStack i){
List<String> e = new ArrayList<String>();
Map<Enchantment, Integer> en = i.getEnchantments();
for(Enchantment t : en.keySet()) {
e.add(t.getName() + ":" + en.get(t));
}
return StringUtils.join(e, ",");
}
public static String deserialize(ItemStack i){
String[] parts = new String[6];
parts[0] = i.getType().name();
parts[1] = Integer.toString(i.getAmount());
parts[2] = String.valueOf(i.getDurability());
parts[3] = i.getItemMeta().getDisplayName();
parts[4] = String.valueOf(i.getData().getData());
parts[5] = getEnchants(i);
return StringUtils.join(parts, ";");
}
public ItemStack deserial(String p){
String[] a = p.split(";");
ItemStack i = new ItemStack(Material.getMaterial(a[0]), Integer.parseInt(a[1]));
i.setDurability((short) Integer.parseInt(a[2]));
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(a[3]);
i.setItemMeta(meta);
MaterialData data = i.getData();
data.setData((byte) Integer.parseInt(a[4]));
i.setData(data);
if (a.length > 5) {
String[] parts = a[5].split(",");
for (String s : parts) {
String label = s.split(":")[0];
String amplifier = s.split(":")[1];
Enchantment type = Enchantment.getByName(label);
if (type == null)
continue;
int f;
try {
f = Integer.parseInt(amplifier);
} catch(Exception ex) {
continue;
}
i.addEnchantment(type, f);
}
}
return i;
}
}
here it saves & loads the whole NBT
package XXXXXXXXX
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
import net.minecraft.server.v1_8_R3.MojangsonParseException;
import net.minecraft.server.v1_8_R3.MojangsonParser;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
public class ItemSerialize {
public ItemSerialize() {
}
public static String serialize(ItemStack i) {
String[] parts = new String[7];
parts[0] = i.getType().name();
parts[1] = Integer.toString(i.getAmount());
parts[2] = String.valueOf(i.getDurability());
parts[3] = i.getItemMeta().getDisplayName();
parts[4] = String.valueOf(i.getData().getData());
parts[5] = getEnchants(i);
parts[6] = getNBT(i);
return StringUtils.join(parts, ";");
}
public static String getEnchants(ItemStack i) {
List<String> e = new ArrayList<String>();
Map<Enchantment, Integer> en = i.getEnchantments();
for (Enchantment t : en.keySet()) {
e.add(t.getName() + ":" + en.get(t));
}
return StringUtils.join(e, ",");
}
public static String getLore(ItemStack i) {
List<String> e = i.getItemMeta().getLore();
return StringUtils.join(e, ",");
}
public static String getNBT(ItemStack i) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
NBTTagCompound compound = nmsStack.hasTag() ? nmsStack.getTag() : new NBTTagCompound();
return compound.toString();
}
public static ItemStack setNBT(ItemStack i, String NBT) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
try {
NBTTagCompound compound = MojangsonParser.parse(NBT);
nmsStack.setTag(compound);
} catch (MojangsonParseException e1) {
e1.printStackTrace();
}
return CraftItemStack.asBukkitCopy(nmsStack);
}
#SuppressWarnings("deprecation")
public static ItemStack deserial(String p) {
String[] a = p.split(";");
ItemStack i = new ItemStack(Material.getMaterial(a[0]), Integer.parseInt(a[1]));
i.setDurability((short) Integer.parseInt(a[2]));
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(a[3]);
i.setItemMeta(meta);
MaterialData data = i.getData();
data.setData((byte) Integer.parseInt(a[4]));
i.setData(data);
if (!a[6].isEmpty()) {
i = setNBT(i, a[6]);
}
if (!a[5].isEmpty()) {
String[] parts = a[5].split(",");
for (String s : parts) {
String label = s.split(":")[0];
String amplifier = s.split(":")[1];
Enchantment type = Enchantment.getByName(label);
if (type == null)
continue;
int f;
try {
f = Integer.parseInt(amplifier);
} catch (Exception ex) {
continue;
}
i.addUnsafeEnchantment(type, f);
}
}
return i;
}
}
ItemStack rItem = ItemStackUtils.deserial(itemString);
In this program iam able to read a file into an array and split the array. Then i have got an array method to sort the file by surname using bubble sort. However, i get an error. Can someone assist me please.
Error:
error: method BubbleCountry in class StudentSort cannot be applied to given types;
StudentSort.txt
Bren Ramal
Casi Ron
Alba Jordi
SortData file
import java.io.*;
import java.util.*;
class ShowSort implements Comparable {
private String name;
private String surname;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSurname() {
return surname;
}
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowSort))
throw new ClassCastException("Error");
String surn = ((ShowSort) Student).getSurname();
return this.surname.compareTo(surn);
}
}
StudentSort file
import java.io.*;
import java.util.*;
public class StudentSort {
StudentSort() {
int j = 0;
ShowSort data[] = new ShowSort[3];
try {
FileInputStream fstream = new FileInputStream("StudentSort.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
ArrayList list = new ArrayList();
while ((line = br.readLine()) != null) {
list.add(line);
}
Iterator itr;
for (itr = list.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split("\t");
String name = "", surname = "";
for (int i = 0; i < splitSt.length; i++) {
name = splitSt[0];
surname = splitSt[1];
}
BubbleCountry(surname);//This is the issue.
data[j] = new ShowSort();
data[j].setName(name);
data[j].setSurname(surname);
j++;
}
for (int i = 0; i < 3; i++) {
ShowSort show = data[i];
String name = show.getName();
String surname = show.getSurname();
System.out.println(name + "\t" + surname);
}
} catch (Exception e) {
}
}
private static void BubbleCountry(String[] myarray) {
String ctry;
for(int i=0; i<myarray.length; i++) {
for(int j=0; j<myarray.length-1-i; j++) {
if(myarray[j].compareTo(myarray[j+1])>0) {
ctry= myarray[j];
myarray[j] = myarray[j+1];
myarray[j+1] = ctry;
}
}
}
}
public static void main(String[] args) {
StudentSort data = new StudentSort();
}
}
You are calling BubbleCountry(surname); but its prototype shows
private static void BubbleCountry(String[] myarray)
So the difference is here. The function requires an array of string as argument but while calling you are passing a string rather than string array.
import java.io.*;
import java.util.*;
public class StudentSort
{
StudentSort()
{
int j = 0;
ShowSort data[] = new ShowSort[3];
try
{
FileInputStream fstream = new FileInputStream("StudentSort.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
list.add(line);
}
Iterator<String> itr = list.iterator();
int k = 0;
for (itr = list.iterator(); itr.hasNext();itr.next())
{
String str = itr.toString();
String[] splitSt = str.split("\t");
data[k].setName(splitSt[0]);
data[k].setName(splitSt[1]);
k++;
}
BubbleCountry(data);//This is the issue.
for (int i = 0; i < 3; i++)
{
ShowSort show = data[i];
String name1 = show.getName();
String surname1 = show.getSurname();
System.out.println(name1 + "\t" + surname1);
}
}
catch (Exception e)
{
}
}
private static void BubbleCountry(ShowSort[] myarray)
{
ShowSort ctry;
for(int i=0; i<myarray.length; i++)
{
for(int j=0; j<myarray.length-1-i; j++)
{
if(myarray[j].compareTo(myarray[j+1])>0)
{
ctry= myarray[j];
myarray[j] = myarray[j+1];
myarray[j+1] = ctry;
}
}
}
}
public static void main(String[] args)
{
StudentSort data = new StudentSort();
}
}