Printing textdata from toString - Java - java

I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?
This is how my toString looks like:
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
Full code:
import java.util.*;
import java.io.*;
public class Codes {
public static void main(String[] args) {
List<Codes2> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] personData = fileRead.split(":");
String personName = personData[0];
String userNameGenerator = personData[1];
Codes2 personObj = new Codes2(personName, userNameGenerator);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++){
String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
for(int j = 0; j < regionSplit.length; j++){
newStrSet.add(regionSplit[j]);
}
}
for (String p: newStrSet) {
System.out.printf("%s -> ", p);
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.getPersonName());
}
}
System.out.println();
}
}
}
Java Class:
public class Codes2 implements Comparable<Codes2> {
private String personName;
private String userNameGenerator;
public Codes2(String personName, String userNameGenerator) {
this.personName = personName;
this.userNameGenerator = userNameGenerator;
}
public String getPersonName() {
return personName;
}
public String getUserNameGenerator() {
return userNameGenerator;
}
#Override
public int compareTo(Codes2 o) {
return getUserNameGenerator().compareTo(o.getUserNameGenerator());
}
public int compare(Object lOCR1, Object lOCR2) {
return ((Codes2)lOCR1).userNameGenerator
.compareTo(((Codes2)lOCR2).userNameGenerator);
}
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
}

Everything looks right in your code.
I think you should just call the method when you are trying to print it out:
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.toString());
}
}
This follows the fact that the class that prints out the object is not so closely coupled with the class that hold the data.

Try:
#Override
public String toString() {
return String.format("%s -> [%s]",this.userNameGenerator,this.personName);
}

Related

Actual and formal argument lists differ in length error in main

Im working on a project where I have 3 text files with data of doctors, patients and home visits. When Im trying to upload the doctors file, upload all the data to a new object I get an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Id_pacjenta Nazwisko Imie PESEL Data_urodzenia"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at com.company.Main.main(Main.java:40)
Below I'll paste my main as well as the classes & a snapshot of the text file used for imports:
Could anyone advise how to avoid this issue? Thanks!
public class Main {
public static void main(String[] args) {
List<Lekarz> lekarz = new ArrayList<>();
try{
File fileLekarze = new File("src/com/company/lekarze.txt");
Scanner readerLekarze = new Scanner(fileLekarze);
while(readerLekarze.hasNextLine()){
String[] data =readerLekarze.nextLine().split(" ");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
readerLekarze.close();
} catch (FileNotFoundException e) {
System.out.println("Error File Lekarze");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
List<Pacjenci> pacjent = new ArrayList<>();
try{
File pacjenciFile = new File("src/com/company/pacjenci.txt");
Scanner readerPacjenci = new Scanner(pacjenciFile);
while(readerPacjenci.hasNextLine()){
String[] data = readerPacjenci.nextLine().split(" ");
pacjent.add(new Pacjenci(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}
readerPacjenci.close();
}catch (FileNotFoundException e) {
System.out.println("Error File Pacjenci");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
}
}
public class Pacjenci {
private int idPacjenta;
private String nazwisko;
private String imie;
private String pesel;
private Date dataUrodzenia;
public Pacjenci(int idPacjenta, String nazwisko, String imie, String pesel, Date dataUrodzenia) {
this.idPacjenta = idPacjenta;
this.nazwisko = nazwisko;
this.imie = imie;
this.pesel = pesel;
this.dataUrodzenia = dataUrodzenia;
}
public int getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(int idPacjenta) {
this.idPacjenta = idPacjenta;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public Date getDataUrodzenia() {
return dataUrodzenia;
}
public void setDataUrodzenia(Date dataUrodzenia) {
this.dataUrodzenia = dataUrodzenia;
}
#Override
public String toString() {
return "Pacjenci{" +
"idPacjenta=" + idPacjenta +
", nazwisko='" + nazwisko + '\'' +
", imie='" + imie + '\'' +
", pesel='" + pesel + '\'' +
", dataUrodzenia=" + dataUrodzenia +
", wizyty=" +
", lekarze=" +
'}';
}
}
public class Wizyty {
private Lekarz idLekarza;
private Pacjenci idPacjenta;
private Date dataWizyty;
public Wizyty(Lekarz idLekarza, Pacjenci idPacjenta, Date dataWizyty) {
this.idLekarza = idLekarza;
this.idPacjenta = idPacjenta;
this.dataWizyty = dataWizyty;
}
public Lekarz getIdLekarza() {
return idLekarza;
}
public void setIdLekarza(Lekarz idLekarza) {
this.idLekarza = idLekarza;
}
public Pacjenci getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(Pacjenci idPacjenta) {
this.idPacjenta = idPacjenta;
}
public Date getDataWizyty() {
return dataWizyty;
}
public void setDataWizyty(Date dataWizyty) {
this.dataWizyty = dataWizyty;
}
#Override
public String toString() {
return "Wizyty{" +
"idLekarza=" + idLekarza +
", idPacjenta=" + idPacjenta +
", dataWizyty=" + dataWizyty +
'}';
}
}
Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
100 Kowal Waldemar 01211309876 2001-1-13
Because of the data spacing in the file, try this:
while(readerLekarze.hasNextLine()){
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim()
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
You could also just do:
String[] data = readerLekarze.nextLine().trim().split("\\s+");
As a complement to the #DevilsHnd, you only need to add a code to avoid the first line, because the first line is the "header information" of your file.
boolean headerRead = false;
while(readerLekarze.hasNextLine()) {
if (!headerRead) {
// extract the first line -> Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
readerLekarze.nextLine();
headerRead = true;
continue;
}
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim();
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(
Integer.parseInt(data[0]),
data[1],
data[2],
data[3],
new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}

How can I delete/not display the nulls?

So my question is how can i Delete/not display the nulls,the excess not founds,and 0's when I run the program, also the last two attributes of the Student201 when 'runned', it displays in reverse order meaning the the nulls or the excess not founds or zeroes are displayed first.
also how can I add students 'predefined'
This is my preferred output or display as much as possible w/o the not found
This is not what I want, the not founds are printed first before the desired output
Main.java
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Student a1=new Student();
//a1.choosy();
Student201 a2 =new Student201();
a2.studinfo();
a2.findstud("2000000001);
}
}
Student201.java
public class Student201 {
Student [] studarray = new Student[13];
int x;
public void studinfo()
{
for (x=0;x<studarray.length;x++) {
studarray[x]= new Student();
}
Student estudyante1 = new Student();
Student estudyante2 = new Student ();
Student estudyante3 = new Student ();
Student estudyante4 = new Student ();
Student estudyante5 = new Student ();
estudyante1.getStudName("Yves Francisco");
estudyante1.getStudNum(2000000001);
estudyante1.getYrLvl(5);
estudyante1.getKors("CpE");
estudyante1.getGender("Male");
estudyante2.getStudName("Lance Eco");
estudyante2.getStudNum(2000000002);
estudyante2.getYrLvl(5);
estudyante2.getKors("CpE");
estudyante2.getGender("Male");
estudyante3.getStudName("Karlos Castillo");
estudyante3.getStudNum(2000000003);
estudyante3.getYrLvl(5);
estudyante3.getKors("CpE");
estudyante3.getGender("Male");
estudyante4.getStudName("Glenn Bordonada");
estudyante4.getStudNum(2000000004);
estudyante4.getYrLvl(4);
estudyante4.getKors("ECE");
estudyante4.getGender("Male");
estudyante5.getStudName("Tim Tolentino");
estudyante5.getStudNum(2000000005);
estudyante5.getYrLvl(4);
estudyante5.getKors("ECE");
estudyante5.getGender("Male");
studarray[0]=estudyante1;
studarray[1]=estudyante2;
studarray[2]=estudyante3;
studarray[3]=estudyante4;
studarray[4]=estudyante5;
}
public void findstud (String query) //String query for searching
{
int ercatch=0;
try{
ercatch=Integer.parseInt(query);
}
catch (NumberFormatException m)
{
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setStudName())) //query.equalsIgnorecase for case sensitive inputs
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender()+"\n");
System.out.println("\n");
}
}
for (x=0;x<studarray.length;x++)
{
if (ercatch == studarray[x].setStudNum()) //Integer.parseInt for int data types
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
else if (ercatch != studarray[x].setStudNum())
{
System.out.println("Not Found!");
}
}
for (x=0;x<studarray.length;x++)
{
if (ercatch == studarray[x].setYrLvl())
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
else if (ercatch != studarray[x].setYrLvl())
{
System.out.println("Not Found!");
}
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setKors()))
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setGender()))
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
}
}
public void addstud (String query)
{
}
}
Student.Java
public class Student {
private String StudName;
private int StudNum;
private int YrLvl;
private String Kors;
private String Gender;
//this just for naming convention for the get and set
public void getStudName (String name) {
this.StudName=name;
}
public String setStudName() {
return StudName;
}
public void getStudNum (int numero) {
this.StudNum=numero;
}
public int setStudNum() {
return StudNum;
}
public void getYrLvl (int yrlvl) {
this.YrLvl=yrlvl;
}
public int setYrLvl()
{
return YrLvl;
}
public void getKors (String korse) {
this.Kors=korse;
}
public String setKors() {
return Kors;
}
public void getGender (String sex)
{
this.Gender=sex;
}
public String setGender() {
return Gender;
}
public void choosy() {
System.out.println("Here is the list and the information of the Students \n");
}
/*public static void main(String[] args) {
// TODO Auto-generated method stub
}*/
}
First things first, you have totally mixed up getters and setters, getters should return the value without any parameter, and setters set the field to a vala ue with parameter, like this
public void setStudName (String name) {
this.StudName=name;
}
public String getStudName() {
return StudName;
}
public void setStudNum (int numero) {
this.StudNum=numero;
}
public int getStudNum() {
return StudNum;
}
Since you don't want to display the Not found result, so I remove it and this is your Student201 class.
public class Student201 {
Student[] studarray = new Student[13];
int x;
public void studinfo() {
for (x = 0; x < studarray.length; x++) {
studarray[x] = new Student();
}
Student estudyante1 = new Student();
Student estudyante2 = new Student();
Student estudyante3 = new Student();
Student estudyante4 = new Student();
Student estudyante5 = new Student();
estudyante1.setStudName("Yves Francisco");
estudyante1.setStudNum(2000000001);
estudyante1.setYrLvl(5);
estudyante1.setKors("CpE");
estudyante1.setGender("Male");
estudyante2.setStudName("Lance Eco");
estudyante2.setStudNum(2000000002);
estudyante2.setYrLvl(5);
estudyante2.setKors("CpE");
estudyante2.setGender("Male");
estudyante3.setStudName("Karlos Castillo");
estudyante3.setStudNum(2000000003);
estudyante3.setYrLvl(5);
estudyante3.setKors("CpE");
estudyante3.setGender("Male");
estudyante4.setStudName("Glenn Bordonada");
estudyante4.setStudNum(2000000004);
estudyante4.setYrLvl(4);
estudyante4.setKors("ECE");
estudyante4.setGender("Male");
estudyante5.setStudName("Tim Tolentino");
estudyante5.setStudNum(2000000005);
estudyante5.setYrLvl(4);
estudyante5.setKors("ECE");
estudyante5.setGender("Male");
studarray[0] = estudyante1;
studarray[1] = estudyante2;
studarray[2] = estudyante3;
studarray[3] = estudyante4;
studarray[4] = estudyante5;
}
public void findstud(String query) //String query for searching
{
int ercatch = 0;
try {
ercatch = Integer.parseInt(query);
} catch (NumberFormatException m) {
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getStudName())) //query.equalsIgnorecase for case sensitive inputs
{
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender() + "\n");
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (ercatch == studarray[x].getStudNum()) //Integer.parseInt for int data types
{
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (ercatch == studarray[x].getYrLvl()) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getKors())) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getGender())) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
}
public void addstud(String query) {
}
}
how can i Delete/not display the nulls,the excess not founds,and 0's
First, remove this
for (x=0;x<studarray.length;x++) {
studarray[x]= new Student();
}
Then, all the students are null except for those you defined, which you can explicitly ignore them.
for (int x = 0; x < studarray.length; x++) {
Student s = studarray[x];
if (s == null) {
continue; // here
}
// Check all your fields in a single loop
if (query.equalsIgnoreCase(s.getStudName())) {
} else if (Integer.parseInt(query) == s.getStudNum()) {
} else {
System.out.println("Student not found using query " + query);
}
}

Writing and Reading to/from a file Objects stored in ArrayList

This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.
Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?
I tried with something like:
`while(ois !=null) {
Person result = (Person) ois.readObject();
persons.add(result);
}
but it's not working.
Here is full test code:
public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();
public static void savePersons() throws IOException{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object for examle */
for(int i = 0; i<5; i++){
Person personTest = new Person("name", "surname", "email", "1234567890");
persons.add(personTest);
}
try{
fout = new FileOutputStream("C:\\data.dat", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" +persons.size()+ "' Object to Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR");
} finally {
if(oos != null){
oos.close();
}
}
}
public static void loadPersons() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
/** Clean 'persons' array for TEST of load data*/
persons.removeAll(persons);
try {
fis = new FileInputStream("C:\\data.dat");
ois = new ObjectInputStream(fis);
Person result = (Person) ois.readObject();
persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" +persons.size()+ "' Object from Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR");
} finally {
if(ois != null){
ois .close();
}
}
}
}
Person class:
public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;
public Person(String n, String s, String m, String t){
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
Main class:
public class Test {
public static void main(String[] args) {
Data.savePersons();
Data.loadPersons();
}}
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}
#Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}

Java - Collection

I'm working on my first java project and I have a question. The question should be quiet simple (though the the code is not that short, but there's no reason to be intimidated :) ). I create a basic roleplaying-game and I have an abstract class "Character" that defines each character. Among its subclasses you can find Mage, who has a Spellbook (Map). Spellbook class offers methods like addToSpellbook, that works fine. In addition I have an Inventory class that has addToInventory method, which is quit identical to addToSpellbook.
My question is as follows - why can I use In the main method addToSpellbook and can't use AddToInventory?
I guess the reason is that Map doesn't have AddToInventory, so I should override put, but still, how can I use addToSpellbook ?
public class Game {
public static void main(String[] args) throws IOException {
CharacterCreator heroCreator = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc = new Scanner(System.in);
int scan = sc.nextInt();
String chosenClass = CharacterCreator.getCharacterClass(scan);
Character hero = CharacterCreator.createCharacter(chosenClass);
try {
hero.displayCharacter();
}catch (Exception e){
System.out.println("Problem displaying character data");
}
hero.getInventory().addToInventory("Long sword");
CharacterCreator heroCreator2 = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc2 = new Scanner(System.in);
int scan2 = sc.nextInt();
String chosenClass2 = CharacterCreator.getCharacterClass(scan2);
Character hero2 = CharacterCreator.createCharacter(chosenClass2);
try {
hero2.displayCharacter();
}catch (Exception e){
System.out.println("Wrong input");
}
if(hero instanceof Mage) {
((Mage)hero).getSpellBook().addToSpellBook("Magic Missiles");
((Mage)hero).getSpellBook().addToSpellBook("Fireball");
((Mage)hero).getSpellBook().addToSpellBook("Mage Armor");
((Mage)hero).getSpellBook().showSpellBook();
((Mage)hero).getSpellBook().getSpellFromSpellbook("Fireball").castSpell(hero, hero2);
((Mage)hero).getSpellBook().getSpellFromSpellbook("Magic Missiles").castSpell(hero, hero2);
((Mage)hero).getSpellBook().getSpellFromSpellbook("Mage Armor").castSpell(hero, hero);
}
}
}
abstract public class Character {
private Equipment equipment;
private Map<String, Integer> inventory;
protected Character(String name){
equipment = new Equipment();
inventory = new HashMap<String, Integer>();
}
protected Character(String name, int lvl){
equipment = new Equipment();
inventory = new HashMap<String, Integer>();
}
}
public Equipment getEquipment() { return equipment; }
public Map getInventory() { return inventory; }
}
public class Inventory {
private Map<String,Integer> inventory;
Inventory() {
inventory = new HashMap<String, Integer>();
}
public void addToInventory(String item) {
boolean found = false;
try {
for (Iterator<Map.Entry<String, Integer>> iter = inventory.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, Integer> newItem = iter.next();
if (newItem.getKey() == item) {
inventory.put(item, inventory.get(newItem) + 1);
break;
}
}
}catch (Exception e) {
System.out.println(item + " : adding failed");
}
if (!found) {
inventory.put(item,1);
}
}
public void showInventory() {
System.out.println("Show Inventory: ");
for (Map.Entry<String,Integer> entry: inventory.entrySet()) {
System.out.println( entry.getKey() + ", quantity: " + entry.getValue() );
}
System.out.println("");
}
}
public class Mage extends Character {
private SpellBook spellBook;
public Mage(String name) {
super(name);
SpellBook spellbook = new SpellBook();
}
protected Mage(String name, int lvl){
super(name, lvl);
spellBook = new SpellBook();
}
public SpellBook getSpellBook() { return spellBook; }
}
}
public class SpellBook {
private Map<String, Spell> spellBook;
SpellBook() {
spellBook = new HashMap<String, Spell>();
}
public Map getSpellBook() { return spellBook; }
public void addToSpellBook(String spellName) {
Spell newSpell = null;
try {
if (DamageSpell.getSpell(spellName) != null) {
newSpell = DamageSpell.getSpell(spellName);
} else if (ChangeStatSpell.getSpell(spellName) != null) {
newSpell = ChangeStatSpell.getSpell(spellName);
}
System.out.println(newSpell.getSpellName() + " has been added to the spellbook");
spellBook.put(newSpell.getSpellName(), newSpell);
} catch (Exception e){
System.out.println("Adding " + spellName +"to spellbook has failed");
}
}
public void showSpellBook() {
System.out.println("Show spellbook: ");
for (Iterator<String> iter = spellBook.keySet().iterator(); iter.hasNext(); ) {
String spell = iter.next();
System.out.println(spell);
}
System.out.println("");
}
public Spell getSpellFromSpellbook(String spellName) {
Spell spl = null;
//Spell splGet = spellBook.get(spellName); /* straight forward implementation*/
// System.out.println("The spell " + splGet.getSpellName() + " has been retrived from the spellbook by using get method");
try {
for (Iterator<Map.Entry<String, Spell>> iter = spellBook.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, Spell> spell = iter.next();
if (spell.getKey() == spellName) {
spl = spell.getValue();
}
}
}catch (Exception e) {
System.out.println(spellName + " : no such spell in spellbook");
}
return spl;
}
}
getInventory() returns a Map and Map doesn't have the addToInventory() method.
getInventory() should add an Inventory instance.

Google search API return false

I have tool code use Google search API.
My code:
import com.google.gson.Gson;
class GoogleResults {
private ResponseData responseData;
public ResponseData getResponseData() {
return responseData;
}
public void setResponseData(ResponseData responseData) {
this.responseData = responseData;
}
public String toString() {
return "ResponseData[" + responseData + "]";
}
static class ResponseData {
private List<Result> results;
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
public String toString() {
return "Results[" + results + "]";
}
}
static class Result {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String toString() {
return "Result[url:" + url + " ]";
}
}
}
public class CrawData {
public static void main(String[] args) throws IOException, InterruptedException {
String query;
int n;
int k=0;
String site;
String resultset;
Scanner st = new Scanner(System.in);
System.out.print(" Input key search: ");
query = st.nextLine();
System.out.print("Input site: ");
site = st.nextLine();
System.out.print("Input number of result: ");
n = st.nextInt();
resultset = query + " site:" + site;
for (int j = 0; j < n; j = j + 1) {
Thread.sleep(4000);
String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start="+j+"&q=";
String charset = "UTF-8";
URL url = new URL(address + URLEncoder.encode(resultset, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader,
GoogleResults.class);
int total = results.getResponseData().getResults().size();
// Show title and URL of each results
for (int i = 0; i <= total - 1; i++) {
String Url = results.getResponseData().getResults().get(i)
.getUrl();
k = k+1;
System.out.println("URL: " +Url+ " " + k);
}
}
}
}
when i run it, i have trouble about result return of code.
My system return list url of website.. but it not stable.
Some picture:
my error
Have error: Exception in thread "main" java.lang.NullPointerException
at CrawData.main(CrawData.java:107)
help me...
Sorry my english is too bad.. :(
My guess is that on this line:
String Url = results.getResponseData().getResults().get(i)
.getUrl();
Either get(i) is returning null or getUrl() is returning null. You should add some error handling logic:
if (results.getResponseData().getResults().get(i) != null &&
results.getResponseData().getResults().get(i).getUrl() !=null) {
String Url = results.getResponseData().getResults().get(i)
.getUrl();
k = k+1;
System.out.println("URL: " +Url+ " " + k);
} else {
// Print some type of error here. Try to figure out why the result or the
// url is null
}

Categories

Resources