compare input to an object arraylist - java

I would like to compare the input from a JTextField to all the elements in a string arraylist. If the input is equal to an element in the list I would like the program to acknowledge by saying "This is in my vocabulary.", and if it is not, I would like the program to say "This is NOT in my vocabulary." In my code, I have tried getting this to work buy I always get the message "This is NOT in my vocabulary." even if the input matches an element in my list. How can I get this to work properly?
Here is my code, in it AI is where the list that is being compared is.
package Important;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import AI.*;
public class TextActions implements ActionListener{
private String hero;
private Vocabulary vocab1 = new Vocabulary();
public void actionPerformed(ActionEvent e) {
e.getSource();
hero = e.getActionCommand();
if (vocab1.Adjectives.equals(hero)){
System.out.println("This word is in my vocab");
}else{
System.out.println( hero + " is not in my vocab");
}
//CompareWords(hero);
}
public void CompareWords(String readme){
if (vocab1.Adjectives.contains(readme)){
//System.out.println("This word is in my vocab");
}
}
}
Here is the Vocabulary class as requested.
package AI;
import java.util.*;
public class Vocabulary {
//String[] thoughts;
public List<String> Adjectives = new ArrayList<String>();
public void AddWord(int ArrayListNumber, String WordEntered){
if(ArrayListNumber == 1){
Adjectives.add(WordEntered);
}
}
}

You are creating new object
Vocabulary vocab1 = new Vocabulary();
This would contain an empty Adjectives list.
So, you have to first populate the Adjectives list before you do the checking as follows
vocab1.Adjectives.contains(hero)
and use contains instead of equals.

Related

Comparing an array to a single string output using assertEquals in Java

So I would like to create a simple code that greets people according to the input.
The difficulity I have that I have no idea how to compare a simple string with an array, using arrayEquals (or any equivalent).
This is the way I have created the code - according to a previous project:
Test file:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class test {
#Test
public void ShouldGreet() {
assertEquals("Hello, my friend.", new GreetPeople().greeter(""));
assertEquals("Hello, Bob.", new GreetPeople().greeter("Bob"));
}
}
Actual code:
import java.util.Arrays;
public class GreetPeople {
public String greeter(String[] names) {
if (Arrays.stream(names).count() == 1) {
return("Hello, " + names + ".");
}
return("Hello, my friend.");
}
}
Any kind of help is well appreciated!
The first patameter of greeter is an array:
assertEquals("Hello, my friend.", new GreetPeople().greeter(new String[]{""}));
assertEquals("Hello, Bob.", new GreetPeople().greeter(new String[]{"Bob"}));

adding into an Array list of objects from a text file in java

i thinkj i have a type argument problem which im really confused about, Ive started with an Arraylist which, extends to the another class with my main methods. and i have a Events class, which i want to categorize from the txt file, the main problem i have is adding from my txt file which iread into an ArrayList, java pops up with this error message
incompatible types: java.lang.String cannot be converted to CSC8012.Events
But in my events it has String? Im really confused
This is my generic arraylist i think?
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable> extends
ArrayList<E> {
public void insert(E e) {
this.add(e);
int lastIndex = 0;
for( lastIndex = this.size() -1 ; lastIndex > 0 && this.get(lastIndex-1).compareTo(e) > 0 ; lastIndex--){
this.set(lastIndex, this.get(lastIndex-1));
}
this.set(lastIndex,e);
}
}
Heres my events class objects
public class Events implements Comparable<Events>{
//fields setting up the variables
String ticketsbought;
String eventname;
public Events(String ticketsbought, String eventname ){
this.ticketsbought = ticketsbought;
this.eventname = eventname;
}
#Override
public int compareTo (Events E){
return
ticketsbought.compareTo(E.getTicketsbought()) + eventname.compareTo(E.getEventname());
}
public String getTicketsbought() {
return ticketsbought;
}
public String getEventname() {
return eventname;
}
//setting it up for the main method from the constructor fields above
public void setTicketsbought(String ticketsbought) {
this.ticketsbought = ticketsbought;
}
public void setEventname(String eventname) {
this.eventname = eventname;
}
#Override
public String toString()
{
return "Tickets bought " + this.ticketsbought + "Event name " + this.eventname;
}
}
My main menu class
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Objects;
import java.util.ArrayList;
import java.util.Collections;
java.util.Scanner;
public class MainProgram extends SortedArrayList{
public static void main(String[] args) throws FileNotFoundException{
boolean bye = false;
String line;
String option;
Scanner sc = new Scanner(System.in); //tos take in our input
do{
System.out.println("Choose an option.."); // heres our options
System.out.println("e Information on all events");
System.out.println("c All information on clients");
System.out.println("f to quit");
System.out.println("b to update when tickets are bought by a registered Client");
System.out.println("r to update the stored data when a Client cancels a ticket");
option = sc.nextLine();
switch (option) { // these are splitting our inputs to these cases with different outcomes
case "e":
//System.out.println("information on events");
Scanner inFile = new Scanner(new FileReader("input.txt"));
// Other declarations// Reading and processing the input data// Printing out the results outFile.close();
ArrayList<Events> events = new ArrayList<>();
while(inFile.hasNextLine()) {
String data = inFile.next();
events.add(data);//error based on these? Event is based off of arraylist<E> and inherits from those whilst i have them as string?
You are seeing the exception because of Generics in Java.
Your ArrayList is declared to take Events objects.
ArrayList<Events> events = new ArrayList<>();
However, you are trying to add a String object to it.
String data = inFile.next();
events.add(data); //Cannot add a String object, only Events object allowed.
One way to fix this is to create an Events object using the String, and then add to the Arraylist. I am assuming each line has Event name and String in it, separated by a comma.
//Get your event name and tickets from the String data.
String tokens[] = data.split(",");
String eventName = tokens[0];
String ticketsBought = tokens[1];
//create an events object
Events eventObj = new Events(eventName, ticketsBought);
//Now add to your arraylist.
events.add(eventObj);
As an aside, you do not need to extend SortedArrayList in MainProgram. The main class is usually top level class in your project, and it will only contain objects (this is a common practice). If you want to use the new logic you have added in SortedArrayList, then instead of creating ArrayList<Events> events = new ArrayList<>();, you can create SortedArrayList<Events> events = new SortedArrayList<>();

How to get Long value from text field and send form into ArrayList

How would I get a long data type in Java?
For example, I would get a string like this:
String thisString = thisString.getText();
But I try the same with a long data type and it doesn't work.
I need it to send it to an ArrayList, and this is the whole code:
package dao;
import entities.*;
import java.util.*;
import javax.swing.JTextField;
import java.text.*;
import javaapplication1.*;
public class ProductModel{
public List<Product> findAll(){
try {
List<Product> forms = new ArrayList<Product>();
JTextField textDate;
JTextField textFecha;
JTextField textTotal;
return forms;
} catch (Exception e){
return null;
}
}
}
That's my array, and then I have this other file here:
public class Product{
public String date;
public String fac;
public Long total;
}
And then finally, the button that sends the data that to the ArrayList:
#Override
public void actionPerformed(ActionEvent e) {
Product form = new Product();
form.date = textDate.getText();
form.fac = textFac.getText();
form.total = textTotal.getText();
forms.add(form);
}
});
But it doesn't seem to work.
A String is not a Long. That is the reason compiler is shouting on you. You need to parse it.
form.total = Long.parseLong(textTotal.getText());
Make sure you have a null check and assign it to 0 if the string is null.
And once you fix the issue, please give a read to Encapsulation.

Package that calls different classes when given input to?

I have taken all of my classes from my intro to java college in highschool class, and put them into a package called gameChoices. I then made a class that would call these classes when the user asks for them, this is called whichGame. I've imported the classes I want called using import gameChoices."whatever game it is";. How do I call these classes in whichGame? I also have them all as public static main(string [] args), which ones shouldn't have that(I think it's just whichGame that should..)? And what would I put instead? Thanks for helping a newbie out :)
The simplest way to do it is probably to set up a big if/then statement.
if(input.equals("t"))
thisOne.start();
else if(input.equals("a"))
anotherOne.start();
else if(input.equals("y"))
yetAnotherOne.start();
And so on. Might be a pain if you have a lot of classes, or if they start with the same letter.
Not sure exactly what you want to achieve, but if you need to access a class by its name you can try Class.forName() and check for exceptions thrown (particularly, ClassNotFoundException).
Using case-insensitive String equality for the name check, if would allow you to access any existing class of your ClassLoader through reflection.
Edit
Here's your main class:
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Main {
// initializes your map of letter->game class
private static final Map<String, Class<?>> GAMES = new HashMap<String, Class<?>>();
// constant name of main method for your games
private static final String MAIN_METHOD_NAME = "main";
// add your games
static {
GAMES.put("c", Chess.class);
GAMES.put("d", Doom.class);
// TODO moar gamez
}
public static void main(String[] args) {
try {
// prompts the user
System.out.println("Enter the game's name or starting letter: ");
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
// gets the response
String input = br.readLine();
br.close();
// iterates over your games' first letters
for (String gameName : GAMES.keySet()) {
// the input starts with one game's first letter...
if (gameName.startsWith(input.toLowerCase())) {
// gets the class
GAMES.get(gameName)
// gets its main method (typical signature is String[] args)
.getMethod(MAIN_METHOD_NAME, String[].class)
// invokes its main method with no arguments
.invoke((Object) null, (Object) null);
}
}
// handles any disaster
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Now here are two "game" classes:
package test;
public class Chess {
public static void main(String[] args) {
System.out.println("You've chosen Chess!");
}
}
... and...
package test;
public class Doom {
public static void main(String[] args) {
System.out.println("You've chosen Doom!");
}
}
Now set your "Main" class as your... main class.
When you launch the application, it will query you for an initial letter.
If you choose "c" or "d", it will print out: "You've chosen [Chess/Doom]!"
I hope this helps you getting started.

Java, make sure that a user doesn't enter numbers in a string

I'm trying to create a text based game in Java that I will ask for a user's name and insert it into the game. I'm trying to evaluate with the string that they entered has any number. i.e 09452 or asdf1234.
Here is the code that is relative to the problem.
String name, choiceSelection;
int choice;
name = JOptionPane.showInputDialog(null, "Enter your name!");
//CHECKS IF USER ENTERED LETTERS ONLY
if (Pattern.matches("[0-9]+", name))
{
throw new NumberFormatException();
}
else if (Pattern.matches("[a-zA-Z]+", name))
{
if (Pattern.matches("[0-9]+", name))
{
throw new NumberFormatException();
}
}
I'm trying to figure out if any number is in the string and if so, throw a NumberFormatException so that they know they didn't follow the correct prompt.
What is the best way to make sure the user doesn't enter numbers in the name String?
You can use a simpler check:
if (!name.replaceAll("[0-9]", "").equals(name)) {
// name contains digits
}
The replaceAll call removes all digits from the name. The equals check would succeed only when there are no digits to remove.
Note that throwing NumberFormatException in this case would be misleading, because the exception has a very different meaning.
Consider using a JFormattedTextField or input verifier to prevent the user from entering numbers in the first place. It may not be worth losing the JOptionPane simplicity for a throwaway project, but it simplifies things for the end user.
Or, You simply don't let the User to put any numeric value in textField .For that you are needed to create Customized PlainDocument say NonNumericDocument and setting the Document of JTextField object as that customized NonNumericDocument
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
class NonNumericDocument extends PlainDocument
{
#Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{
if (str == null)
{
return;
}
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++)
{
if (Character.isDigit(arr[i]) || !Character.isLetter(arr[i]))//Checking for Numeric value or any special characters
{
return;
}
}
super.insertString(offs, new String(str), a);
}
}
//How to use NonNumericDocument
class TextFrame extends JFrame
{
JTextField tf ;
public void prepareAndShowGUI()
{
tf = new JTextField(30);
tf.setDocument(new NonNumericDocument());//Set Document here.
getContentPane().add(tf,BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater ( new Runnable()
{
#Override
public void run()
{
TextFrame tFrame = new TextFrame();
tFrame.prepareAndShowGUI();
}
});
}
}
You can use this NonNumericDocument with any JTextField in your code without worrying about handling of non-numeric characters explicitly.
If you want to allow the user to only enter letters you can do this:
if (name.matches("\\p{Alpha}+")) {
// name contains only letters
}
Another way to check it is using parseInt( String s ) method:
private boolean isNumber( String s ) {
try {
Integer.parseInt( s );
} catch ( Exception e ) {
return false; // if it is not a number it throws an exception
}
return true;
}

Categories