ETA at 9:42 p.m. March 21: Dumb mistake. I made sure the original creation of the object made the name .toUpperCase(). The partial search didn't find the search term because they weren't capitalized. Edited code below. Thank you all for the help.
I'm trying to figure out how to use regular expressions to find out if any pattern of characters matches what's in the object.
For instance, if the name associated with the object was "StackOverflow," I'd like for someone to search "ck" and make the if statement true. So, why is my if statement here not returning true?
ETA: i.getName() returns a string. The program is looping through an ArrayList of objects to find which object has a name that matches the input.
System.out.println("What name or partial name would you like to filter?");
String name = input.nextLine();
int count = 0;
for (MyObject i: testObject) {
if (i.getName().matches(".*" + name.toUpperCase() + ".*")) {
count++;
}
}
You need to use toString(). You can not apply matches over an object.
Try that:
System.out.println("What name or partial name would you like to filter?");
String name = input.nextLine();
int count = 0;
for (Object i: testObject) {
if (i.getName().toString().matches(".*" + name + ".*")) {
count++;
}
}
I'm not sure why your code doesn't work, but see this working example, perhaps you have a small mistake somewhere.
Here's a MyObject class that has a name field:
class MyObject {
private final String name;
public MyObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
and here's the program that find matches:
List<MyObject> myObjects = new ArrayList<MyObject>();
myObjects.add(new MyObject("Stack Overflow"));
myObjects.add(new MyObject("Stack Exchange"));
Scanner input = new Scanner(System.in);
System.out.print("What name or partial name would you like to filter? ");
String pattern = input.nextLine();
int count = 0;
for (MyObject i: myObjects) {
if (i.getName().matches(".*" + pattern + ".*")) {
count++;
}
}
System.out.println("Matches: " + count);
Input:
ck
Output:
Matches: 2
Related
I am writing a short Java script to where I have a name in String as a variable. I want to write get method to get initials and return them for later use. That method works well when printing out the initials, but not when wanting to return that value.
//method for getting initials of the name
public String getInitials() {
String words[] = competitorName.split(" ");
for(String word : words) {
return word.charAt(0) + " ";
}
}
It shows me that the method must return a result of type String but that should already be it. And does not work even when I am adding toString methods (then it writes that it is already String)
You almost got it! Just use StringBuilder and return result
public String getInitials() {
String words[] = competitorName.split(" ");
StringBuilder builder = new StringBuilder();
for(String word : words) {
builder.append(word.charAt(0));
}
return builder.toString();
}
I'm finding it hard to use my methods even if I correctly instantiated my objects. Any ideas on where I went wrong?
example: I tried compiling the java file but the error I get is
"incompatible types: String cannot be converted to Books"
I think the problem is my instantiated object is being forced into a string but the problem is I used the correct syntax to call on a string. However, it still doesn't read it as a string and says that the instantiated object cannot be converted to the "Books" class.
I've already searched about it but all they say is the object hasn't been created. However, I checked my code and I already instantiated my object even before putting it into the method parameter.
I even tried to print the object on its own with the specific characteristics and it turned out fine. So I guess it goes right up until it gets put into a method.
One thing I don't understand is that I need that object to be referenced into a method.
Here is my code:
class Books{
String type;
int pages;
Books[] booklist;
int bookcounter = 0;
//Constructor to initialize the object "book"
Books(int input){
if(input == 1){
this.type = "Math";
this.pages = 5;
}
if(input == 2){
this.type = "Physics";
this.pages = 9;
}
if(input == 3){
this.type = "Economics";
this.pages = 20;
}
}
//This method needs to add the instantiated object to the array list
void addbooktype(Books kind){
System.out.println("You chose: " + kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = kind;
}
void printbooks(){
for(int i = 0; i <= bookcounter; i++){
int y = i+1;
System.out.println("Book #"+ y + "is: " +this.booklist[i].type);
System.out.println("With pages of: " + this.booklist[i].pages);
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int bookchoice;
int choice;
String booktype;
int booknum = 0;
do{
System.out.println("===========Menu===========");
System.out.println("[1] - Pick a book \n[2] - Print book list\n[0] - Exit");
System.out.println("==========================");
System.out.print("Choice: ");
choice = sc.nextInt();
switch(choice){
//Selects and adds a book to the list
case 1:
System.out.println("Choose your book: ");
bookchoice = sc.nextInt();
Books book = new Books(bookchoice);
System.out.println(book.type);
booktype = book.type;
book.addbooktype(booktype);
booknum++;
break;
//Prints the book list
case 2:
System.out.println("List of Books: ");
book.printbooks();
break;
case 0:
System.out.println("Exit");
return;
default: System.out.println("Input not found.");
}
}while(choice!=0);
}
}
The errors I get is on the "book.addbooktype(booktype);"
This is where it bugs me, I printed the objected and even put it into a String container but it still rejects it. I don't know where I went wrong. And when it goes into the method it doesn't read the parameter. Any thoughts?
Your method addbooktype requires a parameter of Books type whereas you wanted a String parameter there
void addbooktype(Books kind){
Your code would work if you would make this slight change:
void addbooktype(String kind){
Edit: As per the comments, it seems I misunderstood the code. That being said, here's what you can do:
Replace
book.addbooktype(booktype);
with
book.addbooktype();
and replace
void addbooktype(Books kind){
System.out.println("You chose: " + kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = kind;
}
with
void addbooktype(){
System.out.println("You chose: " + this.kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = this;
}
This would add the currently calling object to your array and allow you to use it later.
The issue is that your method accepts Object of Class Book only. However when you are calling that function
book.addbooktype(booktype);
You are giving it type String (In your book class type is String variable). To fix that you either need to pass book object or change the method itself
Passing the book object:
Books book = new Books(bookchoice);
book.addbooktype(book);
and in function you can do something like this
void addbooktype(Books book) {
System.out.println("You chose: " + book.type);
System.out.println("Adding to the list...");
booklist[bookcounter++] = book;
}
(Added Later) Using This:
This approach also utilizes the object however it is better than the approach described above. Instead of passing the object as a parameter which is redundant you can use java word this.
According to java docs Using the this Keyword
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
So when you call function
book.addbooktype(book);
^ and ^ are same
| |
Inside the method addbooktype
void addbooktype(Books book) {
this and book would also be same.
}
so instead you could do this
book.addbooktype();
and addbooktype would be
void addbooktype() {
System.out.println("You chose: " + this.type);
System.out.println("Adding to the list...");
booklist[bookcounter++] = this;
}
An example where passing object and this would be useful is when you have to compare objects. Lets say you have two objects book1 and book2. You would do something like this
int compareResult = book1.compareTo(book2);
Your method would be
public int compareTo(Book book) {
Now here this would be book1
and book would be book2
Also keep in mind this.type would be same as type. type and this.type are both
referring to same object i.e who we called function on (book1).
}
Changing the function:
or you can just change you function like this though I suggest you pass the object itself. If you just pass the String you won't be able to store it in Books[] booklist
void addbooktype(String type) {
System.out.println("You chose: " + type);
System.out.println("Adding to the list...");
// The line below will give error unless you change Books[] booklist;
// to String[] booklist;
booklist[bookcounter++] = kind;
}
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication10Arraylistandobjects {
static Scanner user_input = new Scanner(System.in);
public static void main(String[] args) {
test();
}
public static void test(){
ArrayList<mainclass> me = new ArrayList <> ();
mainclass ob;
for (int i=0;i<2;i++){
ob = new mainclass();
System.out.println("name");
ob.name = user_input.nextLine();
System.out.println("sname");
ob.sname = user_input.nextLine();
me.add(ob);
}
System.out.println("Show List: " + me);
System.out.println("Confirm if is true or false: " + me.get(1).toString().contains("max"));
System.out.println("what is index of: " + me.get(1).toString().indexOf("max"));
}
}
public class mainclass {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
#Override
public String toString() {
return "mainclass{" + "name=" + name + ", sname=" + sname + '}';
}
String name;
String sname;
}
My questions is how can I find correctly indexOf string.
For example when I am checking if string "max" exist - it shows me "true"
and when I am trying to find index of string "max" it shows me index 15 which is not correct.
P.S. I found an article with the same problem where it says that I have to override equals and hashcode - I've done it but anyway I got the same problem.
Please point me to the right direction.
What I am doing wrong here, can someone explain me pls.
These are my inputs and output.
run:
name Jony
sname Bravo
name max
sname hitman
Show List:[mainclass{name=Jony, sname=Bravo}, mainclass{name=max, sname=hitman}]
Confirm if is true or false: true
what is index of: 15
BUILD SUCCESSFUL (total time: 11 seconds)
The line:
System.out.println("what is index of: " + me.get(1).toString().indexOf("max"));
has a problem, in that you're getting the object in the me list at index 1, getting its toString(), and looking for "max" in there. What you actually want to do, as I understand it, is look through the me list and find the place in the list with "max" in it.
P.S. I found an article with the same problem where it says that I have to override equals and hashcode - I've done it but anyway I got the same problem.
If you did that, it would allow you to do something like this:
x = new mainclass();
x.setName("Max");
System.out.println("what is index of: " + me.indexOf(x));
However, there's still a potential problem. Unless you set your equals() and hashCode() to only look at the name and not also sname, then it's not going to find anything unless the sname also matches.
Recently i started learning java. And after some knowledge i starts with some program. so i create a Jumble Word game. it works but i have a problem. Here is my code....
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
class JumbleWords
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
ArrayList <String>alist = new ArrayList<String>();
ArrayList <Character>chars = new ArrayList<Character>();
Random rd = new Random();
int listLimit,charLimit,value,ulimit=0,counter=0;
String string,temp;
alist.add("done");
alist.add("nest");
alist.add("rat");
alist.add("cat");
alist.add("hello");
alist.add("cycle");
alist.add("chain");
alist.add("paint");
alist.add("collect");
alist.add("your");
alist.add("gift");
alist.add("card");
alist.add("today");
alist.add("cheer");
alist.add("what");
alist.add("time");
alist.add("share");
alist.add("build");
alist.add("help");
alist.add("success");
alist.add("career");
alist.add("access");
alist.add("learn");
alist.add("course");
alist.add("year");
alist.add("expert");
alist.add("school");
alist.add("floor");
alist.add("season");
alist.add("education");
alist.add("spread");
listLimit = alist.size();
int i=0;
System.out.println();
System.out.println("How many JumbleWords you want to play...");
System.out.println("Max limit is "+listLimit);
ulimit = scan.nextInt();
scan.nextLine();
if(ulimit < listLimit )
{
while(i<ulimit )
{
value = rd.nextInt(listLimit);
string = alist.get(value);
for ( char c : string.toCharArray() )
{
chars.add( c );
}
Collections.shuffle(chars);
Collections.shuffle(chars);
System.out.println(chars);
System.out.println("\nEnter the correct order of the word.");
temp = scan.nextLine();
if(string.equalsIgnoreCase(temp)==true){
System.out.println("You Win......");
System.out.println("(*^*)");
System.out.println();
++counter;
}
else{
System.out.println("You Lose......");
System.out.println("The correct word is :-");
System.out.println(string);
System.out.println("(*_*)");
System.out.println();
}
chars.clear();
alist.remove(value);
i++;
}
System.out.println("Your Score is "+counter+" out of "+ulimit);
System.out.println();
}
else
{
System.out.println("Not enough words we have...");
System.out.println();
}
}
}
now in case of "CHAIN" is suffle and user must input chain for winning but "CHINA" is also a word with same chars. how can i build a logic for that.
You can compare the whole word:
while(i<ulimit )
{
value = rd.nextInt(listLimit);
string = alist.get(value);
if(string.equalsIgnoreCase(value)){
System.out.println("You Win......");
System.out.println("(*^*)");
System.out.println();
++counter;
}
...
First, your code is really not straight readable.
Variable names are very very bad chosen while you implement a specific matter :
a word game.
Besides you declare your variables too early and have also a too broad scope, which is error prone and don't easy the reading too.
How to understand these statements without reading the whole code ?
string = alist.get(value);
Or :
if(string.equalsIgnoreCase(temp)==true){
It should be something like:
String wordToGuess = wordsToGuess.get(value);
and :
if(wordToGuess.equalsIgnoreCase(userInput)){
Instead of using a List of String.
ArrayList <String>alist = new ArrayList<String>();
use a List of WordToGuess where each instance will store a List<String> anagrams where WordToGuess could be declared :
public class WordToGuess{
private List<String> anagrams;
...
public WordToGuess(String... anagrams){
this.anagrams = Arrays.asList(anagrams);
}
public String getAnyWord(){
return anagrams.get(0);
}
public boolean contains(String word){
return anagrams.contains(word.toLowerCase());
}
}
In this way you have just to check if the input of the user is contained in the List.
So
ArrayList <String>alist = new ArrayList<String>();
will become :
List<WordToGuess> wordsToGuess = new ArrayList<WordToGuess>();
Favor the interface in the variable type declaration over concrete class.
And you could populate your List in this way :
wordsToGuess.add(new WordToGuess("done", "node")); // two possibilities
wordsToGuess.add(new WordToGuess("nest")); // one
...
wordsToGuess.add(new WordToGuess("chain", "china")); // two
...
And the comparing input String with the expected String :
if(wordToGuess.equalsIgnoreCase(userInput)){
will become :
if(wordsToGuess.contains(userInput)){
It is better to keep the ignoring-case task in the provider class that in the client class that may forget it.
public class Pig {
private int pigss;
private Pig[] pigs;
public Pig[] pigNumber (int pigss)
{
pigs = new Pig [pigss];
return pigs;
}
Code that includes main method:
public class animals{
public static void main(String[] args){
Pig cool = new Pig();
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int pigss = Integer.parseInt( keyboard.nextLine() );
cool.pigNumber(pigss);
//This is where I have trouble. I want to use the array pigs here in the main method, this is what i tried:
Pig[] pigs = cool.pigNumber(pigss);
I then tried to use a for loop and assign values (String) to the index of arrays (pigs[]). But the error that gives me is: cannot convert from String to Pig. Any tips are appreciated. THank you.
for(int j = 0; j < pigs.length; j++)
{
System.out.println("What is the pig " + (j+1) + "'s name");
pigs[j] = keyboard.nextLine();
}
Your pigs will need an attribute to contain the string values you are trying to pass:
public class Pig {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
Then when you want to assign this string value to your pig:
int indexOfPig = 0; // Or whatever it is supposed to be
pigs[indexOfPig].setName("I am a string");
In java you can only use ints as the indexes of arrays
It is saying 'cannot convert from String to Pig' because you can't do that!
If you want somehow convert a String to a Pig, you are going to need to write some code to do the conversion. For example, you might write a constructor that creates a new Pig from some kind of description. Or you might write a method that looks up a Pig by name or number or something.
It is hard to offer any more concrete advice because you don't tell us what is in the string values ... or how you expect the strings to become pigs. (The only suggestion I have is to try Macrame :-) )
Pig doesn't have a name member or even method that accepts a string. Also you are trying to assign a String(keyboard.nextline() to a Pig(pigs[j].
Add an attribute name to your pig.
class Pig{
public String name:
public void Pig(String name){
this.name = name;
}
}
Then assign a new instance of Pig in the loop.
pigs[j] = new Pig(keyboard.nextLine());
Also get rid of the useless class pigNumber. All you need is an ArrayList of Pigs. The array list can be dynanically sized.
List<Pig> pigs = new ArrayList<Pig>
so your loop could be something like
String name = ""
while(true){
name = keyboard.readline();
if(name== "stop"){
break;
}
pigs.add(new Pig(names);
}
Then getting the number of pigs is a simple
System.out.println(pigs.length());