I am Having an XML file
<?xml version="1.0"?>
<ticket>
<team>A</team>
<imp>I1</imp>
</ticket>
<ticket>
<team>A</team>
<imp>I2</imp>
</ticket>
<ticket>
<team>b</team>
<imp>I2</imp>
</ticket>
<ticket>
<team>A</team>
<imp>I1</imp>
</ticket>
<ticket>
<team>B</team>
<imp>I2</imp>
</ticket>
<ticket>
<team>c</team>
<imp>I1</imp>
</ticket>
out put to like :-
Team I1 I2 I3
A 2 1 0
B 1 1 0
C 1 0 0
Here currently I3 is not there in XML. is it Possible to take I1,I2 and I3 into Hash and check if I1 is there then to get count accorind to team and display like above.
ticket.java
package com.asn.ticket;
public class ticket {
private String team;
private String imp;
public ticket(String team, String imp) {
super();
this.team = team;
this.imp = imp;
}
public String getteam() {
return team;
}
public void setteam(String team) {
this.team = team;
}
public String getimp() {
return imp;
}
public void setimp(String imp) {
this.imp = imp;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((team == null) ? 0 : team.hashCode());
result = prime * result + ((imp == null) ? 0 : imp.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;
ticket other = (ticket) obj;
if (team == null) {
if (other.team != null)
return false;
} else if (!team.equals(other.team))
return false;
if (imp == null) {
if (other.imp != null)
return false;
} else if (!imp.equals(other.imp))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ticket [team=");
builder.append(team);
builder.append(", imp=");
builder.append(imp);
builder.append("]");
return builder.toString();
}
}
ticketcounts.java
package com.asn.team;
import com.asn.team.ticket;
public class ticketsCount {
public static void main(String[] args) {
List<ticket> ticketList = new ArrayList<ticket>();
try {
String Path = "C:\\Users";
File fXmlFile = new File(Path+"\\tickets.xml");
// File fXmlFile = new File(App.class.getClassLoader().getResource("C:\\Users\// \\tickets.xml").getFile());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList ticketNodeList = doc.getElementsByTagName("ticket");
for (int temp = 0; temp < ticketNodeList.getLength(); temp++) {
Node varNode = ticketNodeList.item(temp);
if (varNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) varNode;
NodeList teamList = eElement.getElementsByTagName("team");
NodeList varsionList = eElement.getElementsByTagName("imp");
Node teamNode = teamList.item(0);
Node impNode = varsionList.item(0);
if(teamNode.getNodeType() == Node.ELEMENT_NODE && impNode.getNodeType() == Node.ELEMENT_NODE){
Element teamElement = (Element)teamNode;
Element impElement = (Element)impNode;
ticket ticket = new ticket(teamElement.getTextContent(), impElement.getTextContent());
ticketList.add(ticket);
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
Map<ticket,Integer> count = new HashMap<ticket, Integer>();
for(ticket c: ticketList)
if(!count.containsKey(c))
count.put(c, Collections.frequency(ticketList, c));
List<String> imps = getimps(count);
List<String> teams = getteams(count);
StringBuilder heading = new StringBuilder("ticket \t| ");
for(String s : imps){
heading.append(s);
heading.append("\t| ");
}
System.out.println(heading);
System.out.println("---------------------------------");
for(String m : teams){
System.out.println(m+"\t| "+getNumOfteams(m, imps, count));
}
}
/**
* #param count
* #return
*/
private static List<String> getteams(Map<ticket, Integer> count) {
List<String> teams = new ArrayList<String>();
for(Map.Entry<ticket, Integer> ent : count.entrySet())
if(!teams.contains(ent.getKey().getteam()))
teams.add(ent.getKey().getteam());
return teams;
}
private static String getNumOfteams(String team, List<String> imps, Map<ticket, Integer> count) {
StringBuilder builder = new StringBuilder();
for(String v : imps){
for(Map.Entry<ticket, Integer> ent : count.entrySet())
if(team.equals(ent.getKey().getteam()) && ent.getKey().getimp().equals(v)){
int cnt = ent.getValue();
builder.append((cnt==0)?" ": cnt);
builder.append("\t| ");
}
}
return builder.toString();
}
private static List<String> getimps(Map<ticket, Integer> count) {
List<String> imps = new ArrayList<String>();
for(Map.Entry<ticket, Integer> ent : count.entrySet())
if(!imps.contains(ent.getKey().getimp()))
imps.add(ent.getKey().getimp());
return imps;
}
}
I haven't executed your code, but if I understand correctly, it works fine except you don't have any column for I3, because no ticket in the XML file has I3 as its imp. So you simply need to do as if there was I3 in the file:
private static List<String> getimps(Map<ticket, Integer> count) {
List<String> imps = new ArrayList<String>();
for(Map.Entry<ticket, Integer> ent : count.entrySet())
if (!imps.contains(ent.getKey().getimp())) {
imps.add(ent.getKey().getimp());
}
}
// make sure I3 is listed as imp as well:
if (!imps.contains("I3")) {
imps.add("I3");
}
return imps;
}
And in the getNumOfTeams() method, you shouldn't assume that at least one ticket has the current imp. So I would rewrite it as:
private static String getNumOfteams(String team, List<String> imps, Map<ticket, Integer> count) {
StringBuilder builder = new StringBuilder();
for (String v : imps){
Integer cnt = count.get(new ticket(team, v));
if (cnt == null) {
cnt = 0;
}
builder.append(cnt + "\t");
}
return builder.toString();
}
Side note: you should really learn and apply naming conventions. Don't abuse abbreviations. Name your getters and setters getTeam() and setTeam() rather than getteam() and setteam(), classes start with an uppercase letter.
Related
I have to create and use LinkedList (implement from scratch) to work with the Book Library Management Program. I have 3 files which contain different classes, 3 main classes in 3 files are the BookList - which is a list of Books, ReaderList - which stores the list of readers and LendingList - which is used for storing the List of lending purposes. The BookList and ReaderList are type of Book and Reader respectly, I want to extract the current data from bookCode property of the Book class and readerCode property of the Reader class.
Input data
Allow a user to input lending item.
When running, the screen looks like:
Enter book code:
Enter reader code:
Enter state:
After the user enter bcode and rcode, the program check and acts as follows:
If bcode not found in the books list or rcode not found in the readers list then data is not accepted.
If both bcode and rcode found in the lending list and state=1 then data is not accepted.
If bcode and rcode found but lended = quantity then new lending item with state = 0 is added to the end of the Lending list.
If bcode and rcode found and lended < quantity then lended is increased by 1 and new lending item with state = 1 is added to the end of the Lending list.
The Books file:
package BooksPackage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
/**
*
* #author Do Van Nam
*/
class Book {
String bcode;
String btitle;
int quantity;
int lended;
double price;
Book(String code, String title, int quantity, int lended, double price) {
this.bcode = code;
this.btitle = title;
this.quantity = quantity;
this.lended = lended;
this.price = price;
}
#Override
public String toString() {
return "Book{" + "bcode=" + bcode + ", btitle=" + btitle + ", quantity=" + quantity + ", lended=" + lended + ", price=" + price + '}';
}
}
class List {
private static class Node {
Book element;
Node next;
public Node(Book e, Node next) {
this.element = e;
this.next = next;
}
public Node(Book e) {
this(e, null);
}
public Node getNext() {
return next;
}
public Book getElement() {
return element;
}
public void setNext(Node e) {
this.next = e;
}
}
Node head = null;
Node tail = null;
int size = 0;
public List() {
}
public boolean isEmpty() {
return size == 0;
}
public Book getFirst() {
if (isEmpty()) {
return null;
}
return head.element;
}
public Book getLast() {
if (isEmpty()) {
return null;
}
return tail.element;
}
public void addFirst(Book e) {
head = new Node(e, head);
if (size == 0) {
tail = head;
}
size++;
}
public void addLast(Book e) {
Node last = new Node(e, null);
if (isEmpty()) {
head = last;
} else if (size == 1) {
head.setNext(last);
tail = last;
} else {
tail.setNext(last);
tail = last;
}
size++;
}
public void removeFirst() {
if (isEmpty()) {
return;
}
head = head.getNext();
size--;
}
public void removeLast() {
if (isEmpty()) {
return;
}
Node secondLast = head;
while (secondLast.next.next != null) {
secondLast = secondLast.next;
}
secondLast.next = null;
size--;
}
public boolean isDuplicate(String code) {
Node node = head;
while (node != null) {
if (node.element.bcode.equals(code)) {
return true;
}
node = node.next;
}
return false;
}
public String displayNode() {
Node node = head;
double value;
String a = "";
while (node != null) {
value = node.element.price * node.element.quantity;
a += node.element.bcode + "\t" + node.element.btitle + "\t" + node.element.quantity + "\t" + node.element.lended + "\t" + node.element.price + "\t" + value + "\n";
node = node.getNext();
}
return a;
}
public Node searchByCode(String code) {
Node x = head;
while (x != null) {
if (x.element.bcode.equals(code)) {
return x;
}
x = x.getNext();
}
return null;
}
public void deleteByCode(String code) {
Node x = head;
if (x.element.bcode.equals(code)) {
head = head.next;
size--;
return;
}
while (x.next != null) {
if (x.next.element.bcode.equals(code)) {
x.next = x.next.next;
size--;
return;
}
x = x.next;
}
}
public void sortByBCode() {
Node a, b;
Book obj;
a = head;
while (a != null) {
b = a.next;
while (b != null) {
if (b.element.bcode.compareTo(a.element.bcode) < 0) {
obj = a.element;
a.element = b.element;
b.element = obj;
}
b = b.next;
}
a = a.next;
}
}
public void insertAfter(Node node, Book book) {
if (isEmpty() || node == null) {
return;
}
Node after = node.next;
Node newNode = new Node(book, after);
node.next = newNode;
if (tail == node) {
tail = newNode;
}
size++;
}
public Node nodeAtPos(int pos) {
int i = 0;
Node init = head;
while (init != null) {
if (i == pos) {
return init;
}
i++;
init = init.next;
}
return null;
}
public void deleteAtPostion(int pos) {
if (isEmpty()) {
return;
}
Node temp = head;
if (pos == 0) {
head = head.next;
return;
}
for (int i = 0; temp != null && i < pos - 1; i++) {
temp = temp.next;
}
if (temp == null || temp.next == null) {
return;
}
Node next = temp.next.next;
temp.next = next;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// 1
List bookList = new List();
// 2
// a.addFirst(new Book("SA", "SOMETHING", 12, 23, 122));
// a.addFirst(new Book("SAX", "SOMETHING", 12, 23, 122));
// a.addFirst(new Book("SAC", "SOMETHING", 12, 23, 122));
// a.addFirst(new Book("SAD", "SOMETHING", 12, 23, 122));
System.out.println("1.1. Load data from file\n"
+ "1.2. Input & add to the end\n"
+ "1.3. Display data\n"
+ "1.4. Save book list to file\n"
+ "1.5. Search by bcode\n"
+ "1.6. Delete by bcode\n"
+ "1.7. Sort by bcode\n"
+ "1.8. Input & add to beginning\n"
+ "1.9. Add after position k\n"
+ "1.10. Delete position k");
int option;
do {
System.out.println("Choose an option from 1 to 10, press 0 to stop");
option = sc.nextInt();
if (option == 1) {
System.out.println("Enter the file you want to read");
String file = sc.next();
// the file will be using here is test.txt, which is existed on my local computer, you should try by entering the file you want to read on your computer instead.
BufferedReader read = new BufferedReader(new FileReader(file));
String str;
while ((str = read.readLine()) != null) {
System.out.println(str);
}
}
if (option == 2) {
System.out.println("Enter the book");
String bcode = sc.next();
String btitle = sc.next();
int quantity = sc.nextInt();
int lended = sc.nextInt();
double price = sc.nextDouble();
if (!bookList.isDuplicate(bcode)) {
bookList.addLast(new Book(bcode, btitle, quantity, lended, price));
} else {
System.out.println("This book is already in the list.");
}
}
if (option == 3) {
System.out.println("code" + "\t" + "Title" + "\t" + "Quantity" + "\t" + "Lended" + "\t" + "Price" + "\t" + "Value");
System.out.println("-------------------------------------------------------------------");
System.out.println(bookList.displayNode());
}
if (option == 4) {
System.out.println("Enter the file name");
String fileName = sc.next();
File input = new File(fileName);
if (input.createNewFile()) {
FileWriter fr = null;
BufferedWriter br = null;
String content = bookList.displayNode();
try {
fr = new FileWriter(input);
br = new BufferedWriter(fr);
// String[] lines = content.split("\r\n|\r|\n");
// int linesNums = lines.length;
br.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
fr.close();
}
}
}
if (option == 5) {
System.out.println("Enter the code of the book you are searching");
String code = sc.next();
if (bookList.searchByCode(code) != null) {
System.out.println(bookList.searchByCode(code));
} else {
System.out.println("Not found");
}
}
if (option == 6) {
System.out.println("Enter the code of the book you want to delete");
String code = sc.next();
bookList.deleteByCode(code);
}
if (option == 7) {
bookList.sortByBCode();
}
if (option == 8) {
System.out.println("Enter the book you want to add to the beginning of the list");
System.out.println("How many books you want to add?");
int nums = sc.nextInt();
while (nums != 0) {
System.out.println("Enter bcode, title, quantity, lended and price for this book");
String bcode = sc.next();
String title = sc.next();
int quantity = sc.nextInt();
int lended = sc.nextInt();
double price = sc.nextDouble();
bookList.addFirst(new Book(bcode, title, quantity, lended, price));
nums--;
}
}
if (option == 9) {
System.out.println("Insert a new node after the bcode: ");
String code = sc.next();
System.out.println("Enter the book");
String bcode = sc.next();
String title = sc.next();
int quantity = sc.nextInt();
int lended = sc.nextInt();
double price = sc.nextDouble();
Book newBook = new Book(bcode, title, quantity, lended, price);
bookList.insertAfter(bookList.searchByCode(code), newBook);
}
if (option == 10) {
System.out.println("Enter the position you want to delete");
int pos = sc.nextInt();
bookList.deleteAtPostion(pos);
}
} while (option != 0);
}
}
The Reader file:
package BooksPackage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author VanNam
*/
class Reader {
private String rcode;
private String name;
private int byear;
Reader(String rcode, String name, int byear) {
this.rcode = rcode;
this.name = name;
this.byear = byear;
}
#Override
public String toString() {
return "Reader{" + "rcode=" + rcode + ", name=" + name + ", byear=" + byear + '}';
}
public String getRcode() {
return rcode;
}
public void setRcode(String rcode) {
this.rcode = rcode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getByear() {
return byear;
}
public void setByear(int byear) {
this.byear = byear;
}
}
class XList {
private static class Node {
Reader element;
Node next;
public Node(Reader e, Node next) {
this.element = e;
this.next = next;
}
public Node(Reader e) {
this(e, null);
}
public Node getNext() {
return next;
}
public Reader getElement() {
return element;
}
public void setNext(Node e) {
this.next = e;
}
}
public XList() {
head = tail = null;
}
Node head = null;
Node tail = null;
int size = 0;
public boolean isEmpty() {
return size == 0;
}
public Reader getFirst() {
return head.getElement();
}
public Reader getLast() {
return tail.getElement();
}
public void addFirst(Reader e) {
head = new Node(e, head);
if (size == 0) {
tail = head;
}
size++;
}
public void addLast(Reader e) {
Node last = new Node(e, null);
if (size == 0) {
head = last;
} else if (size == 1) {
head.setNext(last);
tail = last;
} else {
tail.setNext(last);
tail = last;
}
size++;
}
public String displayNode() {
Node node = head;
String a = "";
while (node != null) {
a += node.element.getRcode() + "\t" + node.element.getName() + "\t" + node.element.getByear() + "\n";
node = node.getNext();
}
return a;
}
public Node searchByCode(String code) {
Node x = head;
while (x != null) {
if (x.element.getRcode().equals(code)) {
return x;
}
x = x.getNext();
}
return null;
}
public void deleteByCode(String code) {
Node x = head;
if (x.element.getRcode().equals(code)) {
head = head.next;
size--;
return;
}
while (x.next != null) {
if (x.next.element.getRcode().equals(code)) {
x.next = x.next.next;
size--;
return;
}
x = x.next;
}
System.out.println("Not found this reader on the list");
}
public boolean isDuplicate(String code) {
Node node = head;
while (node != null) {
if (node.element.getRcode().equals(code)) {
return true;
}
node = node.getNext();
}
return false;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
XList readerList = new XList();
int option;
System.out.println("2.1. Load data from file\n"
+ "2.2. Input & add to the end\n"
+ "2.3. Display data\n"
+ "2.4. Save reader list to file\n"
+ "2.5. Search by rcode\n"
+ "2.6. Delete by rcode");
do {
Scanner sc = new Scanner(System.in);
System.out.println("Choose an option");
option = sc.nextInt();
if (option == 1) {
System.out.println("Enter the file you wanna read");
String file = sc.next();
// the file will be using here is testReader.txt, which is existed on my local computer, you should try by entering the file you want to read on your computer instead.
BufferedReader read = new BufferedReader(new FileReader(file));
String str;
while ((str = read.readLine()) != null) {
System.out.println(str);
}
}
if (option == 2) {
System.out.println("Enter the reader");
String code = sc.next();
String name = sc.next();
int year = sc.nextInt();
if (!readerList.isDuplicate(code)) {
readerList.addLast(new Reader(code, name, year));
} else {
System.out.println("This reader is already in the list.");
}
}
if (option == 3) {
System.out.println(readerList.displayNode());
}
if (option == 4) {
System.out.println("Enter the file name");
String fileName = sc.next();
File input = new File(fileName);
if (input.createNewFile()) {
FileWriter fr = null;
BufferedWriter br = null;
String content = readerList.displayNode();
try {
fr = new FileWriter(input);
br = new BufferedWriter(fr);
br.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
fr.close();
}
}
}
if (option == 5) {
System.out.println("Find the reader by entering the code");
String code = sc.next();
if (readerList.searchByCode(code) != null) {
System.out.println("Found at this address: " + readerList.searchByCode(code));
} else {
System.out.println("Not found");
};
}
if (option == 6) {
System.out.println("Enter the reader you want to delete by entering the code");
String code = sc.next();
readerList.deleteByCode(code);
}
} while (option != 0);
}
}
The LendingBook file:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BooksPackage;
import java.util.Scanner;
/**
*
* #author VanNam
*/
public class LendingBook {
private String bcode;
private String rcode;
private int state;
public LendingBook(String bcode, String rcode, int state) {
this.bcode = bcode;
this.rcode = rcode;
this.state = state;
}
#Override
public String toString() {
return "LendingBook{" + "bcode=" + bcode + ", rcode=" + rcode + ", state=" + state + '}';
}
public String getBcode() {
return bcode;
}
public void setBcode(String bcode) {
this.bcode = bcode;
}
public String getRcode() {
return rcode;
}
public void setRcode(String rcode) {
this.rcode = rcode;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
class LendingList {
private static class Node{
private LendingBook element;
private Node next;
public Node(LendingBook e, Node n){
this.element = e;
this.next = n;
}
public Node(LendingBook e){
this(e, null);
}
public Node getNext() {
return next;
}
public LendingBook getElement() {
return element;
}
public void setNext(Node n){
this.next = n;
}
}
Node head = null;
Node tail = null;
int size = 0;
public boolean isEmpty(){
return size == 0;
}
public LendingBook getFirst() {
if(isEmpty()) return null;
return head.getElement();
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
LendingList lendingList = new LendingList();
int option;
do{
System.out.println("Enter the option" + "\n" + "1.Input data 2. Display lending data 3. Sort by bcode + rcode" + "\n" + "Press 0 to exit");
option = sc.nextInt();
if(option == 1){
String bookCode; // -> Here, I want to check it with the existing bookCode from the Book file
String readerCode; // // -> Here, I want to check it with the existing readerCode from the Reader file
int state;
System.out.println("Enter book code");
bookCode = sc.next();
System.out.println("Enter the reader code");
readerCode = sc.next();
}
}while(option != 0);
}
}
I want to get that information and use the data from the two classes above in my LendingList. Many thanks.
You can only pass data using constructors or instance methods.
or do
filename bob = new filename(object or data type);
bob.method(object or data type);
PS : Not sure if this is going to work.
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
I have an arrayList of arrayList,
example:
mainList = [[2,1],[3,1],[5,1],[6,2],[11,2],[7,2],[9,3],[10,3],[11,3],....,[n,m]] ,
where n and m can be any value.
now I want to group elements according to innerList 2nd tuple value and put all groups in different arrayList, that is:
newList1 =[2,3,5], newList2=[6,11,7] , like that other groups , I'm not able to find any solution, i'm new in java, please suggest some ways.
public class CsvParser {
public static void main(String[] args) {
try {
FileReader fr = new FileReader((args.length > 0) ? args[0] : "data.csv");
Map<String, List<String>> values = parseCsv(fr, " ", true);
System.out.println(values);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<String, List<String>> parseCsv(Reader reader, String separator, boolean hasHeader) throws IOException {
Map<String, List<String>> values = new LinkedHashMap<String, List<String>>();
List<String> columnNames = new LinkedList<String>();
BufferedReader br = null;
br = new BufferedReader(reader);
String line;
int numLines = 0;
while ((line = br.readLine()) != null) {
if (StringUtils.isNotBlank(line)) {
if (!line.startsWith("#")) {
String[] tokens = line.split(separator);
if (tokens != null) {
for (int i = 0; i < tokens.length; ++i) {
if (numLines == 0) {
columnNames.add(hasHeader ? tokens[i] : ("row_"+i));
} else {
List<String> column = values.get(columnNames.get(i));
if (column == null) {
column = new LinkedList<String>();
}
column.add(tokens[i]);
values.put(columnNames.get(i), column);
}
}
}
++numLines;
}
}
}
return values;
}
}
Something like this would suffice. I'm sure it can be cleaned up since I wrote it in a hurry.
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
try {
List<List<Integer>> outerList = new ArrayList<List<Integer>>();
outerList.add(new ArrayList<Integer>(asList(11,2)));
outerList.add(new ArrayList<Integer>(asList(2,1)));
outerList.add(new ArrayList<Integer>(asList(11,3)));
outerList.add(new ArrayList<Integer>(asList(6,2)));
outerList.add(new ArrayList<Integer>(asList(7,2)));
outerList.add(new ArrayList<Integer>(asList(9,3)));
outerList.add(new ArrayList<Integer>(asList(3,1)));
outerList.add(new ArrayList<Integer>(asList(5,1)));
outerList.add(new ArrayList<Integer>(asList(10,3)));
if(outerList.size() == 0) return;
Collections.sort(outerList, new CustomComparator());
System.out.println(outerList);
List<List<Integer>> newOuterList = new ArrayList<List<Integer>>();
int i = 0;
int value = outerList.get(0).get(1);
while(i < outerList.size()) {
List<Integer> newInnerList = new ArrayList<Integer>();
while(i < outerList.size()) {
if(outerList.get(i).get(1) == value) {
newInnerList.add(outerList.get(i).get(0));
i++;
} else {
value = outerList.get(i).get(1);
break;
}
}
newOuterList.add(newInnerList);
}
System.out.println(newOuterList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class CustomComparator implements Comparator<List<Integer>> {
#Override
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.get(1).compareTo(o2.get(1));
}
}
I am trying to read the xml file and trying to send the mail.
here is the xml code
<?xml version="1.0" encoding="UTF-8"?><xml>
<u_incident_task>
<description>messafe</description>
<priority>1</priority>
<number>12345</number>
<u_task_incident_service_ci>A</u_task_incident_service_ci>
</u_incident_task>
<u_incident_task>
<description>messafe</description>
<priority>3</priority>
<number>123456</number>
<u_task_incident_service_ci>A</u_task_incident_service_ci>
</u_incident_task>
</xml>
so when ever Priority is 1 i need to send mail. currently my below code is working and able to send.
But when ever Priority is updated from 3 to 1 mail is not able to send. may be the reason i am storing all the number in array since i dont want to send mail repeatedly. so i stored the numbers in array so that i can be sent only once. so while i am storing the numbers if any Priority is updated to 1 mail is not working.
But when record is created with 1 mail i sent but if we updated the existing priority from 3 to 1 it not workin. complete working code is here. can any one help what i missed in logic pls?
complete code here.
Incidentreport2000.java
package com.asn.model;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.asn.model.incident200;
import com.asn.model.incident1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.mail.Message;
import javax.mail.MessagingException;import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
public class incidentreport2000 implements Runnable {
List<String> number1 = new ArrayList<String>();
public incidentreport2000(){
}
public void run(){
for(int i=1;i>0;i++){
try{
Thread.sleep(9600);
List<incident1> incident1List = new ArrayList<incident1>();
List<incident200> incident200List = new ArrayList<incident200>();
FileWriter fw =null;
BufferedWriter bw=null;
String Path = "C:\\Users";
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
InputStream input = null;
String address ="C:\\Users" ;
String localFileName = "\\file.xml";
try {
File fXmlFile = new File(Path + "\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList incident1NodeList = doc.getElementsByTagName("u_incident_task");
for (int temp = 0; temp < incident1NodeList.getLength(); temp++) {
Node varNode = incident1NodeList.item(temp);
if (varNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) varNode;
NodeList u_task_incident_service_ciList = eElement.getElementsByTagName
("u_task_incident_service_ci");
NodeList varsionList = eElement.getElementsByTagName("priority");
NodeList numberList = eElement.getElementsByTagName("number");
NodeList descriptionList = eElement.getElementsByTagName("description");
/* Node u_task_incident_service_ciNode =
u_task_incident_service_ciList.item(0);
Node priorityNode = varsionList.item(0);*/
Node u_task_incident_service_ciNode =
u_task_incident_service_ciList.item(0);
Node priorityNode = varsionList.item(0);
Node numberNode = numberList.item(0);
Node descriptionNode = descriptionList.item(0);
if (u_task_incident_service_ciNode.getNodeType() == Node.ELEMENT_NODE
&& priorityNode.getNodeType() ==
Node.ELEMENT_NODE) {
Element u_task_incident_service_ciElement = (Element)
u_task_incident_service_ciNode;
Element priorityElement = (Element) priorityNode;
Element numberElement = (Element) numberNode;
Element descriptionElement = (Element) descriptionNode;
incident1 incident1 = new incident1(
u_task_incident_service_ciElement.getTextContent(),
priorityElement.getTextContent());
incident1List.add(incident1);
incident200 incident200 = new incident200(
u_task_incident_service_ciElement.getTextContent(),
priorityElement.getTextContent(),numberElement.getTextContent (),descriptionElement.getTextContent());
incident200List.add(incident200);
}
}
// fw = new FileWriter(file.getAbsoluteFile());
// bw = new BufferedWriter(fw);
}
} catch (Exception e) {
e.printStackTrace();
}
Map<incident1, Integer> count = new HashMap<incident1, Integer>();
for (incident1 c : incident1List)
if (!count.containsKey(c))
count.put(c, Collections.frequency(incident1List, c));
List<String> prioritys = getprioritys(count);
List<String> u_task_incident_service_cis = getu_task_incident_service_cis(count);
Map<incident200, Integer> count1 = new HashMap<incident200, Integer>();
for (incident200 c1 : incident200List)
if (!count1.containsKey(c1))
count1.put(c1, Collections.frequency(incident200List, c1));
List<String> number = getnumber(count1);
List<String> description = getdescription(count1);
List<String> prioritys1 = getprioritys1(count1);
List<String> u_task_incident_service_cis1 = getu_task_incident_service_cis1(count1);
for (String v2 : prioritys1 ) {
if (v2 =="P1" ){
for (String n2 : number ) {
System.out.println(number);
if (!number1.contains(n2)) {
for (String d : description){
for (String m3 : u_task_incident_service_cis1){
if (m3 == "A"){
getCountu_task_incident_service_cis1( m3,prioritys1,n2,d, count1);
}
if (m3 == "B"){
getCountu_task_incident_service_cis1( m3,prioritys1,n2,d, count1);
}
}} number1.add(n2);
}}
}}
}catch(Exception e){}
}
}
private static List<String> getu_task_incident_service_cis(Map<incident1, Integer>
count) {
List<String> u_task_incident_service_cis = new ArrayList<String>();
for (Map.Entry<incident1, Integer> ent : count.entrySet())
if (!u_task_incident_service_cis.contains(ent.getKey
().getu_task_incident_service_ci()))
u_task_incident_service_cis.add(ent.getKey().getu_task_incident_service_ci
());
System.out.println(u_task_incident_service_cis);
if(!u_task_incident_service_cis.contains("A"))
u_task_incident_service_cis.add("A");
return u_task_incident_service_cis;
}
private static List<String> getu_task_incident_service_cis1(Map<incident200, Integer>
count) {
List<String> u_task_incident_service_cis1 = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!u_task_incident_service_cis1.contains(ent.getKey
().getu_task_incident_service_ci()))
u_task_incident_service_cis1.add(ent.getKey().getu_task_incident_service_ci
());
System.out.println(u_task_incident_service_cis1+"NewCIS");
if(!u_task_incident_service_cis1.contains("BIRSD"))
u_task_incident_service_cis1.add("BIRSD");
return u_task_incident_service_cis1;
}
private static String getNumOfu_task_incident_service_cis(String
u_task_incident_service_ci, List<String> prioritys,
Map<incident1, Integer>
count) {
StringBuilder builder = new StringBuilder();
for (String v : prioritys) {
Integer cnt = count.get(new incident1(u_task_incident_service_ci, v));
if (cnt == null) {
cnt = 0;
}
}
return builder.toString();
}
private static String getCountu_task_incident_service_cis1(String
u_task_incident_service_ci, List<String> prioritys1, String number,String description,
Map<incident200, Integer>
count1) {
StringBuilder builder1 = new StringBuilder();
List<String> ARRAY = new ArrayList<>();
for (String v : prioritys1) {
if ( v == "P1") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
if (!ARRAY.contains(number)) {
mail1 (u_task_incident_service_ci,v,number,description);
ARRAY.add(number);
}
}}
else
if ( v == "P2") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
if (!ARRAY.contains(number)) {
mail1(u_task_incident_service_ci,v,number,description);
ARRAY.add(number);
}}
}}
return number;
}
private static List<String> getprioritys(Map<incident1, Integer> count) {
List<String> prioritys = new ArrayList<String>();
for (Map.Entry<incident1, Integer> ent : count.entrySet())
if (!prioritys.contains(ent.getKey().getpriority()))
prioritys.add(ent.getKey().getpriority());
Collections.sort(prioritys);
return prioritys;
}
private static List<String> getprioritys1(Map<incident200, Integer> count) {
List<String> prioritys1 = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!prioritys1.contains(ent.getKey().getpriority()))
prioritys1.add(ent.getKey().getpriority());
;
//Collections.sort(prioritys);
System.out.println("check1");
return prioritys1;
}
private static List<String> getnumber(Map<incident200, Integer> count) {
List<String> number = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!number.contains(ent.getKey().getnumber()))
number.add(ent.getKey().getnumber());
return number;
}
private static List<String> getdescription(Map<incident200, Integer> count) {
List<String> description = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!description.contains(ent.getKey().getdescription()))
description.add(ent.getKey().getdescription());
return description;
}
public static void mail1(String Email,String v,String n, String d) {
System.out.println(Email);
System.out.println(v);
final String username = "mailid";
final String password = "password";
//w2011.kpnnl.local
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
//props.put("mail.transport.protocol","smtp");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse
("toaddress"));
message.setSubject("Priority:"+v+": "+n+"Incident has bee raised for the team"+Email);
message.setText("messager,"
);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException {
incidentreport2000 mrt = new incidentreport2000();
Thread t = new Thread(mrt);
t.start();
String Path = "C:\\Users";
List<String> number1 = new ArrayList<String>();
}
}
incident200.java
package com.asn.model;
public class incident200 {
private String u_task_incident_service_ci;
private String priority;
private String number;
private String description;
public incident200(String u_task_incident_service_ci, String priority, String number,String description ) {
super();
if (u_task_incident_service_ci.equals("A"))
{ String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
if (priority.equals("1"))
{ String priority1 = "P1";
this.priority = priority1;}
else
if (priority.equals("3"))
{ String priority3 = "P3";
this.priority = priority3;}
else
if (priority.equals("4"))
{ String priority4 = "P3";
this.priority = priority4;}
else
if (priority.equals("5"))
{ String priority5 = "P3";
this.priority = priority5;}
else
if (priority.equals("2"))
{ String priority2 = "P2";
this.priority = priority2;}
else
this.priority = priority;
this.number = number;
this.description = description;
}
public String getu_task_incident_service_ci() {
return u_task_incident_service_ci;
}
public void setu_task_incident_service_ci(String u_task_incident_service_ci) {
this.u_task_incident_service_ci = u_task_incident_service_ci;
}
public String getpriority() {
return priority;
}
public void setpriority(String priority) {
this.priority = priority;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getdescription() {
return description;
}
public void setdescription(String description) {
this.description = description;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((u_task_incident_service_ci == null) ? 0 : u_task_incident_service_ci.hashCode());
result = prime * result + ((priority == null) ? 0 : priority.hashCode());
result = prime * result + ((number == null) ? 0 : number.hashCode());
result = prime * result + ((description == null) ? 0 : description.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;
incident200 other = (incident200) obj;
if (u_task_incident_service_ci == null) {
if (other.u_task_incident_service_ci != null)
return false;
} else if (!u_task_incident_service_ci.equals(other.u_task_incident_service_ci))
return false;
if (priority == null) {
if (other.priority != null)
return false;
} else if (!priority.equals(other.priority))
return false;
if (number == null) {
if (other.number != null)
return false;
} else if (!number.equals(other.number))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("incident99 [u_task_incident_service_ci=");
builder.append(u_task_incident_service_ci);
builder.append(", priority1=");
builder.append(priority);
builder.append(", number=");
builder.append(number);
builder.append(", description=");
builder.append(description);
builder.append("]");
return builder.toString();
}
}
Incident1.java
package com.asn.model;
public class incident1 {
private String u_task_incident_service_ci;
private String priority;
public incident1(String u_task_incident_service_ci, String priority) {
super();
if (u_task_incident_service_ci.equals("A"))
{ String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
if (priority.equals("1"))
{ String priority1 = "P1";
this.priority = priority1;}
else
if (priority.equals("3"))
{ String priority3 = "P3";
this.priority = priority3;}
else
this.priority = priority;
}
public String getu_task_incident_service_ci() {
return u_task_incident_service_ci;
}
public void setu_task_incident_service_ci(String u_task_incident_service_ci) {
this.u_task_incident_service_ci = u_task_incident_service_ci;
}
public String getpriority() {
return priority;
}
public void setpriority(String priority) {
this.priority = priority;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((u_task_incident_service_ci == null) ? 0 : u_task_incident_service_ci.hashCode());
result = prime * result + ((priority == null) ? 0 : priority.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;
incident1 other = (incident1) obj;
if (u_task_incident_service_ci == null) {
if (other.u_task_incident_service_ci != null)
return false;
} else if (!u_task_incident_service_ci.equals(other.u_task_incident_service_ci))
return false;
if (priority == null) {
if (other.priority != null)
return false;
} else if (!priority.equals(other.priority))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("incident1 [u_task_incident_service_ci=");
builder.append(u_task_incident_service_ci);
builder.append(", priority=");
builder.append(priority);
builder.append("]");
return builder.toString();
}
}
This code is rather ... peculiar. Looking at one method:
private static String
getNumOfu_task_incident_service_cis(String u_task_incident_service_ci,
List<String> prioritys,
Map<incident1, Integer> count) {
StringBuilder builder = new StringBuilder();
for (String v : prioritys) {
Integer cnt = count.get(new incident1(u_task_incident_service_ci, v));
if (cnt == null) {
cnt = 0;
}
}
return builder.toString();
}
Several "count" values are obtained from the Map, but the StringBuilder happily remains unchanged; the method always returns "".
Another method:
private static String
getCountu_task_incident_service_cis1( ..., String number,... ){
//...
if ( v == "P1") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
} else
if (cnt1 != 0){
cnt1 = 1;
//...
return number;
}
Here, cnt1 is set to 0 or 1, but not used later on within the same if statement. And the return value is number, a String parameter. So - what's the point?
public incident200(String u_task_incident_service_ci,
String priority, String number,String description ) {
super();
if (u_task_incident_service_ci.equals("A")){
String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
What's the purpose of this complication? A single statement would be sufficient:
this.u_task_incident_service_ci = u_task_incident_service_ci;
I regret that I can only point out why this code may be difficult to understand. Cleaning up the code might be a good start towards finding the bug.
Later
If method getCountu_task_incident_service_cis1 should send emails, it does so for priorities P1 and P2 only:
for (String v : prioritys1) {
if ( v == "P1") {
// ...
} else
if ( v == "P2") {
//...
}
}
Moreover, method run contains
for (String v2 : prioritys1 )
if (v2 =="P1" ){
// some code...
}
}
Do you expect that any other priority is ever sent?
hey
i have text file shown as below.
11/2/2010 cat 6
11/2/2010 cat 3
11/2/2010 dog 4
11/2/2010 cat 11
11/3/2010 cat 1
11/3/2010 dog 3
11/3/2010 cat 8
i have in every month this kind of text file. Above figure shows the part of the text file. so then i want to read this text using java to Jtable.
i Have used StringTokanizer And Arreaylist to ceate this. Unfotunately i couldn't done it. SO PLS HELP ME........
So i want below result to jTable using java program.
date animal total count
11/2/2010 cat 20 3
11/3/2010 cat 9 2
You don't need a StringTokenizer (in fact, it's not recommended). Just get the input line by line using BufferedReader, and do a String split:
List<Array> data = new ArrayList<Array>();
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;
// Read input and put into ArrayList of Arrays
while ((line = in.readLine) != null) {
data.add(line.split("\\s+"));
}
// Now create JTable with Array of Arrays
JTable table = new JTable(data.toArray(), new String[] {
"date", "animal", "total", "count"});
test with : http://crysol.org/es/node/819
or
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class Reader {
public Reader() {
// TODO Auto-generated constructor stub
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("sample.txt")));
Map<String, Object[]> result = new LinkedHashMap<String, Object[]>();
while (reader.ready()) {
String line = reader.readLine();
String[] values = line.split("\\s+");
String key = values[0] + "\t" + values[1];
String label = values[0];
String date = values[1];
Integer sum = 0;
Integer count = 0;
if (result.containsKey(key)) {
sum = (Integer) ((Object[]) result.get(key))[2];
count = (Integer) ((Object[]) result.get(key))[3];
} else {
}
result.put(key, new Object[]{label, date,
sum + Integer.parseInt(values[2]), count + 1});
}
ArrayList arrayList = new ArrayList(result.values());
/* interate and print new output */
/*
* for (String key : result.keySet()) { Integer sum =
* result.get(key); Integer count = result2.get(key);
* System.out.println(key + " " + sum + "\t" + count); }
*/
JTable table = new JTable(new AnimalTableModel(arrayList));
panel.add(new JScrollPane(table));
reader.close();
frame.setContentPane(panel);
frame.setVisible(true);
frame.pack();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Reader();
}
public class AnimalTableModel implements TableModel {
final Class[] columnClass = new Class[]{String.class, String.class,
Integer.class, Integer.class};
final String[] columnName = new String[]{"Date", "Animal", "Sum",
"Count"};
List values = null;
public AnimalTableModel(List values) {
this.values = values;
// initilize values
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return columnClass[columnIndex];
}
#Override
public int getColumnCount() {
return columnClass.length;
}
#Override
public String getColumnName(int columnIndex) {
return columnName[columnIndex];
}
#Override
public int getRowCount() {
return values.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return ((Object[]) values.get(rowIndex))[columnIndex];
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
#Override
public void removeTableModelListener(TableModelListener l) {
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// TODO FOR EDITABLE DT
}
}
}
You will have to populate the data to a map from the given file.I will give you an example as to how to populate the data.
public class AnimalMapping {
public static void main(String[] args) {
Object[][] data = { { "11/2/2010", "cat", 6 },
{ "11/2/2010", "cat", 3 }, { "11/2/2010", "dog", 4 },
{ "11/2/2010", "cat", 11 }, { "11/3/2010", "cat", 1 },
{ "11/3/2010", "dog", 3 }, { "11/3/2010", "cat", 8 } };
HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();
for (Object[] record : data) {
Map<String, AnimalValCnt> innerMap = null;
if ((innerMap = animalMap.get(record[0])) == null) {
innerMap = new HashMap<String, AnimalValCnt>();
animalMap.put((String) record[0], innerMap);
}
AnimalValCnt obj = null;
if ((obj = innerMap.get(record[1])) == null) {
obj = new AnimalValCnt();
innerMap.put((String) record[1], obj);
}
obj.Sumval += (Integer) record[2];
obj.cnt++;
}
System.out.println(animalMap);
}
}
class AnimalValCnt {
int Sumval;
int cnt;
#Override
public String toString() {
return "(" + Sumval + "," + cnt + ")";
}
}
Once you have got the data in a map then it's easy to populate these data to a table.You can use a tablemodel for this purpose.Have a look at this code to understand how data from a map can be loaded into a table using TableModel.
UPDATE:
public class AnimalMapping {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;
String[] record;
HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();
while(((line = in.readLine()) != null)) {
record=line.split("\\s+");
Map<String, AnimalValCnt> innerMap = null;
if ((innerMap = animalMap.get(record[0])) == null) {
innerMap = new HashMap<String, AnimalValCnt>();
animalMap.put(record[0], innerMap);
}
AnimalValCnt obj = null;
if ((obj = innerMap.get(record[1])) == null) {
obj = new AnimalValCnt();
innerMap.put(record[1], obj);
}
obj.Sumval += Integer.valueOf(record[2]);
obj.cnt++;
}
System.out.println(animalMap);
}
}
class AnimalValCnt {
int Sumval;
int cnt;
#Override
public String toString() {
return "(" + Sumval + "," + cnt + ")";
}
}
#Dilantha Chamal: Reading from file was already given by Box9.I just included it in my code.You should be putting some effort here.Maybe you are a beginner that's why I wrote the code.Now try to implement the TableModel by yourself.Just a friendly advice:unless you do it you are never going to learn.
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class AnimalSummaryBuilder
{
private static final Splitter SPLITTER = Splitter.on(CharMatcher.anyOf(","));
private static final Joiner JOINER = Joiner.on("\t");
#SuppressWarnings("unchecked")
public static void main(final String[] args) throws Exception
{
#SuppressWarnings("rawtypes")
Map<Animal, Summary> result = Files.readLines(new File("c:/1.txt"), Charsets.ISO_8859_1, new LineProcessor() {
private final Map<Animal, Summary> result = Maps.newHashMap();
public Object getResult()
{
return result;
}
public boolean processLine(final String line) throws IOException
{
Iterator<String> columns = SPLITTER.split(line).iterator();
String date = columns.next();
String name = columns.next();
int value = Integer.valueOf(columns.next()).intValue();
Animal currentRow = new Animal(date, name);
if (result.containsKey(currentRow))
{
Summary summary = result.get(currentRow);
summary.increaseCount();
summary.addToTotal(value);
}
else
{
Summary initialSummary = new Summary();
initialSummary.setCount(1);
initialSummary.setTotal(value);
result.put(currentRow, initialSummary);
}
return true;
}
});
for (Map.Entry<Animal, Summary> entry : result.entrySet())
{
Animal animal = entry.getKey();
Summary summary = entry.getValue();
System.out.println(JOINER.join(animal.date, animal.name, summary.total, summary.count));
}
}
final static class Animal
{
String date;
String name;
public Animal(final String date, final String n)
{
this.date = date;
this.name = n;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Animal))
{
return false;
}
Animal other = (Animal) obj;
if (date == null)
{
if (other.date != null)
{
return false;
}
}
else if (!date.equals(other.date))
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
}
final static class Summary
{
private int total;
private int count;
void setTotal(int value)
{
total = value;
}
void setCount(int i)
{
count = i;
}
void increaseCount()
{
count++;
}
void addToTotal(int valueToAdd)
{
total += valueToAdd;
}
}
}