Can anyone tell me what im doing wrong here ? I just want to detect the last word of the sentence and if not found to show "Not found." here is the code:

String[] items = { "Iphone", "Computer", "Car" };
String field = Field.getText();
        String text = "I want a ";
        Scanner scan = new Scanner(text);
        for (int i = 0; i < text.length(); i++) {
            while (scan.hasNext()) {
                String next = scan.next();
                for (int j = 0; j < items.length; j++) {
                    if (next.equals(items[j])) {
                        infoLabel.setText("You want a: "+items[j]);
                    } else {
                        infoLabel.setText("Item not found.");
                    }
                }
            }
        }

Recommended Answers

All 9 Replies

Use split on the string(with space regex), it will return an array of strings, then you can get the last item in the array will be your last word

String[] bits = yourSentance.split(" ");
String lastOne = bits[bits.length-1];

Another option could be this
String last = yourSentance.substring(yourSentance.lastIndexOf(' ') + 1);

what its doing this line String last = yourSentance.substring(yourSentance.lastIndexOf(' ') + 1); can you explain me and where should i put this too ? Also i want to know is this is a good way of doing this ?

for (int i = 0; i < text.length(); i++) {
            Scanner scan = new Scanner(text);
            while (scan.hasNext()) {
                String next = scan.next();
                for (String item : items) {
                    if (next.contains(item)) {
                        infoLabel.setText("You want a: " + item);
                    } else {
                        infoLabel.setText("Item not found.");
                    }
                }
            }
        }

How about StringTokenizer class here ?

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
(from the API doc)

Okay, here is some more information on the methods I proposed but as James said the first one in there is the recommended one, the one liner still works though

Let's break this a bit ..
String last = yourSentance.substring(yourSentance.lastIndexOf(' ') + 1);

yourSentance is a string variable that you get from the user, let's make an example where:
String yourSentance = "I am a sentance";
what substring does is it cuts the string from a starting position in it until a stop position. For example if we call split with parameters 2 and 4 such as

String yourSentance = "I am a sentance";
System.out.println(yourSentance.substring(2,4));

it will print out "am" as that is on position 2 to 4 in the string yourSentance. Now the way that we have it in the example above is
substring(last occurance of space + 1) - means the first character after the last space that exists in the string sentance. Second parameter is not specified so the return gives you the rest of the string from the last occurance of last 'space' if there are multiple ones of course.

The split method is similiar. It splits the entire sentance based on a specified regex. For example our string "I am a sentance" if we use split on this with a regex that is just space such as " " then the result returned to us will be an array of strings, where the original string is cut on each occurance of space so the array will contain [I,am,a,sentance]. Using the length you can get what is the length of that array and since arrays are 0 based, you need to substract 1 to get the last element of it as I showed on the first post

Hope this helps you understand it

@Slavi i have understanded your post and thanks for sharing it with me it helps me alot but im still trying to figure out, but im failing if you can change it here in the code i will be very happy here is my last try...

String[] items = { "Iphone", "Computer", "Car" };

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String field = Field.getText();
        String text = "I want a";
        Scanner scan = new Scanner(text);
        String[] bits = text.split(" ");
        String last = bits[bits.length-1];

        for (int j = 0; j < items.length; j++) {
            String next = scan.next(last);

            if (next.equals(items[j])) {
                infoLabel.setText("You want a: "+items[j]);
            } else {
                infoLabel.setText("Not found.");
            }
        }        
    }

My guess: you are getting three texts for each word you enter.

move your if-else outside of that for loop. keep a local variable (boolean found = false)
which you set to true if next is found in your array. after your iteration:

if ( found ) setText("A");
else setText("B");

if you are looking for the first word of your array, with your current code, you'll get "not found", because the "found" text is overwritten by the not found, because the later elements don't match.
another solution is to say:

if ( found ){ 
setText("text"); 
break; // to get out of the loop
}
else{ setText("not found");}

Here is my take on your original code without suggesting a better algorithm.

1) You are looping through the size of text string, but your intention is to loop through the scan size. Take out the for-loop scope that wrapping around the content (line 5 & 16). Then it should correctly loop through your string.

2) Your current comparison (using equals()) does a case-sensitive check. If you want it to be case-insensitive, use equalsIgnoreCase() instead.

3) Once you found the text, you must break;, or the same text field will be replaced over and over again.

Your code is not well described in my opinion, do you always want to get the last word from the sentance "You want a" which will always be "a" or do you want to get the last string in the string array that you had previous defined as items? I think your idea is something like ask a user for an item, the item is expected to be the last word in a sentance right? If that item exists in a previously defined list, then print to the user that he is getting that item, if it does not exist, print to the user that there is no such item, correct? If so ...

import java.util.Arrays;
import java.util.Scanner;

public class Test {
    static String[] items = { "Iphone", "Computer", "Car" };
    public static void main(String[] args) {                                         
            System.out.println("What would you like to order?");
            Scanner scan = new Scanner(System.in); //in case of reading input from console
            //I assume that scan will be used to get a sentance from the user
            String sentance = scan.nextLine(); // Example "I want a computer"
            String[] bits = sentance.split(" ");
            String last = bits[bits.length-1];
            if(Arrays.asList(items).contains(last))
                System.out.println("You have ordered " + last + ".");
            else
                System.out.println("Item "+ last + " was not found in our system.");
        }
}

In this case you have to be careful that "computer" will not be recognised just "Computer would". You can make the words in the array to be all lower case letters and the same with the input from the user at the point where you check if it is part of the array

Running the code above produces this:

What would you like to order?
I want a Computer // this is the input from the user
You have ordered Computer.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.