I created array list of customer class.store data using joptionpane. how i can get data at specific index of arraylist for udpating customer data.
here its my customer class
public class Customer_Data {
public int account_num,starting_balance=0 ;
public String pincode="",name="",type="",account_num1="";
public Object status;
}
its admin class for create delete and update customer.
public class ADMIN extends javax.swing.JFrame {
/**
* Creates new form ADMIN
*/
public ADMIN() {
this.user = new ArrayList<Customer_Data>();
initComponents();
}
List<Customer_Data> user;
public void create_account() {
Customer_Data a = new Customer_Data();
a.account_num = (user.size() - 1)+1;
String[] s0 = {"Current", "Savings"};
String[] s01 = {"Active", "Deactive"};
String s = ""; a.name=JOptionPane.showInputDialog("Enter Name");
String s1 = "";
//a.pincode = JOptionPane.showInputDialog("Enter PinCode", s1);
do {
a.pincode = JOptionPane.showInputDialog("Enter 5 digit PinCode", s1);
} while (!a.pincode.matches("[0-9]{5}")); String s2="";
s2 = JOptionPane.showInputDialog("Enter Starting Balance ");
a.starting_balance = Integer.parseInt(s2);
//String s3 = "";
a.status = (String) JOptionPane.showInputDialog(null, "Select Status...", "Status", JOptionPane.QUESTION_MESSAGE, null, s01, s01[0]);
a.type = (String) JOptionPane.showInputDialog(null, "Select Type...", "Type", JOptionPane.QUESTION_MESSAGE, null, s0, s0[0]);
user.add(a);
for (int i = 0; i < user.size(); i++) {
Customer_Data var = user.get(i);
JOptionPane.showMessageDialog(null, var.account_num + "\n" + var.name + "\n" + var.pincode + "\n" + var.status + "\n" + var.type, "sad", JOptionPane.PLAIN_MESSAGE);
}
}
how i can get data at specific index in search function
public void Search() {
String s1 = "", s2 = "";
s1 = JOptionPane.showInputDialog("Enter Account Number u want to ", s2);
for (int i = 0; i < user.size(); i++) {
if (user.contains(s1)) {
for (int u = 0; u < user.indexOf(i); u++) {
Customer_Data var = user.get(u);
JOptionPane.showMessageDialog(null, var.account_num + "\n" + var.name + "\n" + var.pincode + "\n" + var.status + "\n" + var.type, "sad", JOptionPane.PLAIN_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Not Fount");
}
}
}
Since your question is mainly about search function, I'll try to demonstrate how you can fix it. Check out the Search() function in below program.
I'm looping over the Customer_Data list only once. For each Customer_Data in the list, I get account_num and compare it with user inputted value.
To avoid confusions, I did not change any identifier name you have used. But I strongly recommend you to use Java naming conventions. E.g:
Use Admin instead of ADMIN
Use CustomerData instead of Customer_Data
Use search() instead of Search()
Use accountNum instead of account_num etc.
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.List;
public class ADMIN {
private List<Customer_Data> user;
public static void main(String[] args) {
ADMIN admin = new ADMIN();
admin.user = new ArrayList<>();
Customer_Data customer1 = new Customer_Data();
customer1.account_num = 123;
customer1.name = "Kevin";
admin.user.add(customer1);
Customer_Data customer2 = new Customer_Data();
customer2.account_num = 456;
customer2.name = "Sally";
admin.user.add(customer2);
Customer_Data customer3 = new Customer_Data();
customer3.account_num = 789;
customer3.name = "Peter";
admin.user.add(customer3);
admin.Search();
}
public void Search() {
String s1 = "", s2 = "";
s1 = JOptionPane.showInputDialog("Enter Account Number u want to ", s2);
boolean found = false;
for (int i = 0; i < user.size(); i++) {
Customer_Data var = user.get(i);
if (var.account_num == Integer.parseInt(s1)) {
JOptionPane.showMessageDialog(null, var.account_num + "\n" + var.name, "sad", JOptionPane.PLAIN_MESSAGE);
found = true;
}
}
if (!found) {
JOptionPane.showMessageDialog(null, "Not Fount");
}
}
}
class Customer_Data {
public int account_num,starting_balance=0 ;
public String pincode="",name="",type="",account_num1="";
public Object status;
}
the List<E> method listOject.indexOf(theSearchObject) is what you are looking for .
it return an int as the first matching occurance index or -1 if it's not contained .
Related
That is simple Library project. It has to load the data from the database, by asking the user to search based on keywords or genres.
I have two classes. One of them is the Book class. :
package library;
import java.sql.Date;
public class Book implements Comparable<Book> {
String title;
String author;
Date date;
String ISBN;
String format;
String publisher;
float price;
String[] keywords;
String[] inputArray;
String input;
public Book(String title_param, String author_param, java.util.Date date_param, String ISBN_param,
String format_param, String publisher_param, float price_param, String keywords_param) {
title = title_param;
author = author_param;
date = (Date) date_param;
ISBN = ISBN_param;
format = format_param;
publisher = publisher_param;
price = price_param;
keywords = keywords_param.split(",");
}
public void setUserInput(String userIn) {
input = userIn;
}
private int getRelevance(String userInput) {
inputArray = userInput.split(",");
int num = 0;
for (int i = 0; i != keywords.length; i++) {
String in = inputArray[i];
for (int l = 0; l != keywords.length; l++) {
if (in.equals(keywords[l]))
num++;
}
}
return num;
}
public int compareTo(Book o) {
if (this.getRelevance(input) > o.getRelevance(input)) {
return 1;
} else if (this.getRelevance(input) < o.getRelevance(input)) {
return -1;
}
return 0;
}
}
In the second one I want to CALL in the right way Collection.sort() and CompareTo(), in a way that it shows the books that contain at least one of these keywords. BUT it has to show the books on top that have the most keywords from the input.
The collection and the compare parts
are NOT not working right now.
package library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Scanner;
public class LibrarySearch {
static ArrayList<Book> books = new ArrayList<Book>();
ArrayList<LibrarySearch> genres = new ArrayList<LibrarySearch>();
static ArrayList<LibrarySearch> keywords = new ArrayList<LibrarySearch>();
public static void main(String[] args) {
load_data();
}
private static void load_data() {
Collections.sort(books, new Comparator<Book>() {
#Override
public int compare(Book first, Book second) {
if (first.compareTo(second) == 1) {
return 1;
} else if (first.compareTo(second) == -1) {
return -1;
}
return 0;
}
});
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "123456");
statement = connection.createStatement();
System.out.println("Choose to search by keywords or genres");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.equals("keywords")) {
System.out.println("Enter your keywords: ");
String[] keyWordsInput = scanner.nextLine().split(",");
ResultSet result = null;
for (int i = 0; i != keyWordsInput.length; i++) {
result = statement
.executeQuery(" SELECT * FROM book WHERE keywords LIKE '%" + keyWordsInput[i] + "%'");
}
while (result.next()) {
int id = result.getInt("id");
String title = result.getString("title");
String author = result.getString("author");
Date date = result.getDate("date");
String ISBN = result.getString("ISBN");
String format = result.getString("format");
String publisher = result.getString("publisher");
float price = result.getFloat("price");
String keywords = result.getString("keywords");
System.out.println("ID = " + id);
System.out.println("TITLE = " + title);
System.out.println("AUTHOR = " + author);
System.out.println("DATE = " + date);
System.out.println("ISBN = " + ISBN);
System.out.println("FORMAT = " + format);
System.out.println("PUBLISHER = " + publisher);
System.out.println("PRICE = " + price);
System.out.println("KEYWORDS = " + keywords);
System.out.println("___________________________________________________________________________");
if (title.equals("I,Robot")) {
Book new_book = new Book(title, author, date, ISBN, format, publisher, price, keywords);
books.add(new_book);
}
if (title.equals("Catch-22")) {
Book new_book1 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
books.add(new_book1);
}
if (title.equals("Pride and Prejudice")) {
Book new_book2 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
books.add(new_book2);
}
if (title.equals("Gone with the Wind")) {
Book new_book3 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
books.add(new_book3);
}
}
result.close();
statement.close();
connection.close();
} else if (input.equals("genres")) {
System.out.println("Enter your genres" + ": ");
String genresInput = scanner.nextLine();
ResultSet result = statement.executeQuery(
" SELECT * FROM books_genres JOIN book ON (book.id = books_genres.book_id) JOIN genre ON (genre.id = books_genres.genre_id) WHERE name LIKE '%"
+ genresInput + "%' ");
while (result.next()) {
int id = result.getInt("id");
String name = result.getString("name");
int book_id = result.getInt("book_id");
int genre_id = result.getInt("genre_id");
int id1 = result.getInt("id");
String title = result.getString("title");
String author = result.getString("author");
Date date = result.getDate("date");
String ISBN = result.getString("ISBN");
String format = result.getString("format");
String publisher = result.getString("publisher");
float price = result.getFloat("price");
String keywords = result.getString("keywords");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Book ID = " + id1);
System.out.println("TITLE = " + title);
System.out.println("AUTHOR = " + author);
System.out.println("DATE = " + date);
System.out.println("ISBN = " + ISBN);
System.out.println("FORMAT = " + format);
System.out.println("PUBLISHER = " + publisher);
System.out.println("PRICE = " + price);
System.out.println("KEYWORDS = " + keywords);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Genre ID = " + id);
System.out.println("Genre Name = " + name);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Book ID = " + book_id);
System.out.println("Genre ID = " + genre_id);
}
result.close();
statement.close();
connection.close();
}
else {
System.out.println("Sorry, wrong command");
}
} catch (SQLException ex) {
System.out.println("No successful connection");
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
}
catch (ClassNotFoundException x_not_found) {
System.out.println("Class not found");
}
}
}
First off, since getRelevance() method returns int, I would suggest writing compareTo like this:
public int compareTo(Book o) {
return this.getRelevance(input) - o.getRelevance(input);
}
Similarly, comparator would look like this:
Collections.sort(books, new Comparator<Book>() {
#Override
public int compare(Book first, Book second) {
return first.compareTo(second);
}
});
As for calling, looks like you are sorting the empty list first, and then populate it with search results. I suggest moving the sorting part to the end of the load_data() method.
One problem: You're iterating over inputArray keywords.length times, which is probably not correct. Don't know if that's your problem - it might be if the keywords array is much shorter than the input array.
The larger issue is iterating over keywords for ever element of inputArray. Put your keywords in a HashSet and test for contains instead.
I am trying to find the max score from the array of objects. The code for that is everything below the int maxValue = -1; line of code. I am also trying to write that bands information to an external file:
import java.io.FileWriter;
public class App {
public static void main(String[] args) {
Bands[] bands = new Bands[5];
bands[0] = new Bands("Joe", "Rick", "Nick", "Dalton", "Doylestown, PA", "RockOn", 4000.50 , "Rock");
bands[1] = new Bands("Luke", "Bill", "Ian", "Matt", "State College, PA", "Blink182", 3500.50 , "Alternative");
bands[2] = new Bands("Corey", "Noah", "Jon", "Kaleb", "Philadelphia, PA", "Rise Against", 10000.50 , "Rock");
bands[3] = new Bands("Jake", "Joey", "Mike", "Mac", "New York, NY", "Thousand Foot Krutch", 2000.50 , "Rock");
bands[4] = new Bands("Bob", "Jeff", "Dom", "Mark", "King of Prussia, PA", "Skillet", 5500.50 , "Rock");
bands[0].compete();
bands[1].compete();
bands[2].compete();
bands[3].compete();
bands[4].compete();
for (int i = 0; i < 5; i++) {
String bandInfo = bands[i].getInfo();
System.out.println(bandInfo);
}
System.out.println("");
//DOESNT WORK BEYOND THIS POINT
int maxValue = -1;
for (int i = 0; i < bands.length; i++) {
if (bands[i].compete() > maxValue) {
maxValue = bands[i].compete();
}
}
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
fw.write(bandInfo + "\n");
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And then here is my Bands class code:
import java.util.Random;
public class Bands {
private String singerName;
private String guitarName;
private String bassistName;
private String drummerName;
private String Hometown;
private String bandName;
private double income;
private String genre;
private int score;
private int winningBand;
public Bands(String singerName, String guitarName, String bassistName, String drummerName, String Hometown, String bandName, double income, String genre)
{
this.singerName = singerName;
this.guitarName = guitarName;
this.bassistName = bassistName;
this.drummerName = drummerName;
this.bandName = bandName;
this.Hometown = Hometown;
this.income = income;
this.genre = genre;
this.score = -1;
this.winningBand = -1;
}
public void compete()
{
Random rand = new Random();
this.score = rand.nextInt(20);
}
public int getScore()
{
return this.score;
}
public String getInfo()
{
String bandInfo = "Band: " + this.bandName + ", Singer: " + this.singerName + ", Guitarist: " + this.guitarName + ", Bassist: " + this.bassistName +
", Drummer: " + this.drummerName + ", Hometown: " + this.Hometown + ", Income: " + this.income + ", Genre: " +
this.genre + ", Final Score: " + this.score;
return bandInfo;
}
}
As for your question about only printing band with highest score info:
Create a global variable (In this case I called it winningBand as an Integer)
Then edit your loop:
for (int i = 0; i < bands.length; i++) {
if (bands[i].getScore() > maxValue) {
maxValue = bands[i].getScore();
winningBand = i;
}
}
Then when you write to the file, only write the winningBand:
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
fw.write(band[winningBand].getInfo);
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
You are trying to find the highest score? Well in your code below
for (int i = 0; i < bands.length; i++) {
if (bands[i].compete() > maxValue) {
maxValue = bands[i].compete();
}
}
When you say .compete(), this does nothing. It assigns a random score in the Bands class. Instead it should look like this if you want to compare scores.
for (int i = 0; i < bands.length; i++) {
if (bands[i].getScore() > maxValue) {
maxValue = bands[i].getScore();
}
}
NOTE: You need to write a getScore() method in the band class that returns the score like the one below:
public Integer getScore(){
return score;
}
As for your question about writing to the file, this should work:
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
for(int i = 0; i <= 4; i++){
fw.write(band[i].getInfo + "\n");
}
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
In this code I want to search in an ArrayList but my code returns an incorrect result and I can not resolve this problem.
ReceivedItemStructure structure:
public class ReceivedItemStructure {
public String mLastID;
public String mUserID;
public String mSmsBody;
public String mMobileNumber;
public String mDate;
public String mSenderName;
public String mSmsNumber;
public String mContactName;
public String getmLastID() {
return mLastID;
}
}
My Code:
int countSMS = 0;
String smsReceivedSender = "";
String r = new JsonService(config_username, config_password, 0, 20, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mId = json_obj.getString("id_recived_sms");
for (ReceivedItemStructure rf:items){
if( ! mId.equals(rf.getmLastID()) ) {
countSMS++;
}
}
}
My problem is this line :
if( ! mId.equals(rf.getmLastID()) ) {
if mId = 2000 and rf.getmLastID() = 1000 then count must be ++
Loop through your list and do a contains or startswith.
ArrayList<String> resList = new ArrayList<String>();
String searchString = "man";
for (String curVal : list){
if (curVal.contains(searchString)){
resList.add(curVal);
}
}
You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.
Ok so to clarify please try to debug your code like this:
int countSMS = 0;
String TAG = "Debugger";
String smsReceivedSender = "";
String r = new JsonService(config_username, config_password, 0, 20, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
Log.i(TAG, "items size is " + items.size());
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mId = json_obj.getString("id_recived_sms");
Log.i(TAG, "Trying to compare " + mId);
for (ReceivedItemStructure rf:items){
Log.i(TAG, "iteration step of " + rf.getmLastID);
if( ! mId.equals(rf.getmLastID()) ) {
countSMS++;
Log.i(TAG, "they are equal, count is " + countSMS);
}
}
}
I have a class Called File
Location which stores the size, name, drive and directory of a file.
The class is supposed to separate the extension from the file name ("java" from "test.java") then compare it to another file using an equals method. Though for some reason it is returning false everytime. Any idea what's wrong?
Class file
import java.util.*;
public class FileLocation
{
private String name;
private char drive;
private String directory;
private int size;
public FileLocation()
{
drive = 'X';
directory = "OOProgramming\\Practicals\\";
name = "test";
size = 2;
}
public FileLocation(char driveIn, String dirIn, String nameIn, int sizeIn)
{
drive = driveIn;
directory = dirIn;
name = nameIn;
size = sizeIn;
}
public String getFullPath()
{
return drive + ":\\" + directory + name;
}
public String getFileType()
{
StringTokenizer st1 = new StringTokenizer(name, ".");
return "File type is " + st1.nextToken();
}
public String getSizeAsString()
{
StringBuilder data = new StringBuilder();
if(size > 1048575)
{
data.append("gb");
}
else if(size > 1024)
{
data.append("mb");
}
else
{
data.append("kb");
}
return size + " " + data;
}
public boolean isTextFile()
{
StringTokenizer st2 = new StringTokenizer(name, ".");
if(st2.nextToken() == ".txt" || st2.nextToken() == ".doc")
{
return true;
}
else
{
return false;
}
}
public void appendDrive()
{
StringBuilder st1 = new StringBuilder(drive);
StringBuilder st2 = new StringBuilder(directory);
StringBuilder combineSb = st1.append(st2);
}
public int countDirectories()
{
StringTokenizer stDir =new StringTokenizer(directory, "//");
return stDir.countTokens();
}
public String toString()
{
return "Drive: " + drive + " Directory: " + directory + " Name: " + name + " Size: " + size;
}
public boolean equals(FileLocation f)
{
return drive == f.drive && directory == f.directory && name == f.name && size == f.size;
}
}
Tester program
import java.util.*;
public class FileLocationTest
{
public static void main(String [] args)
{
Scanner keyboardIn = new Scanner(System.in);
FileLocation javaAssign = new FileLocation('X', "Programming\\Assignment\\", "Loan.txt", 1);
int selector = 0;
System.out.print(javaAssign.isTextFile());
}
}
this code will give true only if the file is doc.
StringTokenizer st2 = new StringTokenizer(name, ".");
if(st2.nextToken() == ".txt" || st2.nextToken() == ".doc")
if file name file.txt then what happend
(st2.nextToken() == ".txt") means ("file" == "txt") false
(st2.nextToken() == ".doc") means ("txt" == "txt") false
first token will gave file name second token will gave ext.
right code is
StringTokenizer st2 = new StringTokenizer(name, ".");
String filename = st2.nextToken();
String ext = st2.nextToken();
if(ext.equalsIgnoreCase(".txt") || ext.equalsIgnoreCase(".txt"))
use always equals to compare strings not ==
Take a look at my own question I posted a while back. I ended up using Apache Lucene's tokenizer.
Here is how you use it (copied from here):
TokenStream tokenStream = analyzer.tokenStream(fieldName, reader);
OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class);
CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
while (tokenStream.incrementToken()) {
int startOffset = offsetAttribute.startOffset();
int endOffset = offsetAttribute.endOffset();
String term = charTermAttribute.toString();
}
I want to use WikipediaTokenizer in lucene project - http://lucene.apache.org/java/3_0_2/api/contrib-wikipedia/org/apache/lucene/wikipedia/analysis/WikipediaTokenizer.html But I never used lucene. I just want to convert a wikipedia string into a list of tokens. But, I see that there are only four methods available in this class, end, incrementToken, reset, reset(reader). Can someone point me to an example to use it.
Thank you.
In Lucene 3.0, next() method is removed. Now you should use incrementToken to iterate through the tokens and it returns false when you reach the end of the input stream. To obtain the each token, you should use the methods of the AttributeSource class. Depending on the attributes that you want to obtain (term, type, payload etc), you need to add the class type of the corresponding attribute to your tokenizer using addAttribute method.
Following partial code sample is from the test class of the WikipediaTokenizer which you can find if you download the source code of the Lucene.
...
WikipediaTokenizer tf = new WikipediaTokenizer(new StringReader(test));
int count = 0;
int numItalics = 0;
int numBoldItalics = 0;
int numCategory = 0;
int numCitation = 0;
TermAttribute termAtt = tf.addAttribute(TermAttribute.class);
TypeAttribute typeAtt = tf.addAttribute(TypeAttribute.class);
while (tf.incrementToken()) {
String tokText = termAtt.term();
//System.out.println("Text: " + tokText + " Type: " + token.type());
String expectedType = (String) tcm.get(tokText);
assertTrue("expectedType is null and it shouldn't be for: " + tf.toString(), expectedType != null);
assertTrue(typeAtt.type() + " is not equal to " + expectedType + " for " + tf.toString(), typeAtt.type().equals(expectedType) == true);
count++;
if (typeAtt.type().equals(WikipediaTokenizer.ITALICS) == true){
numItalics++;
} else if (typeAtt.type().equals(WikipediaTokenizer.BOLD_ITALICS) == true){
numBoldItalics++;
} else if (typeAtt.type().equals(WikipediaTokenizer.CATEGORY) == true){
numCategory++;
}
else if (typeAtt.type().equals(WikipediaTokenizer.CITATION) == true){
numCitation++;
}
}
...
WikipediaTokenizer tf = new WikipediaTokenizer(new StringReader(test));
Token token = new Token();
token = tf.next(token);
http://www.javadocexamples.com/java_source/org/apache/lucene/wikipedia/analysis/WikipediaTokenizerTest.java.html
Regards
public class WikipediaTokenizerTest {
static Logger logger = Logger.getLogger(WikipediaTokenizerTest.class);
protected static final String LINK_PHRASES = "click [[link here again]] click [http://lucene.apache.org here again] [[Category:a b c d]]";
public WikipediaTokenizer testSimple() throws Exception {
String text = "This is a [[Category:foo]]";
return new WikipediaTokenizer(new StringReader(text));
}
public static void main(String[] args){
WikipediaTokenizerTest wtt = new WikipediaTokenizerTest();
try {
WikipediaTokenizer x = wtt.testSimple();
logger.info(x.hasAttributes());
Token token = new Token();
int count = 0;
int numItalics = 0;
int numBoldItalics = 0;
int numCategory = 0;
int numCitation = 0;
while (x.incrementToken() == true) {
logger.info("seen something");
}
} catch(Exception e){
logger.error("Exception while tokenizing Wiki Text: " + e.getMessage());
}
}