-3

I am creating a program where a user plays a game in which they have to guess whether a number is high or low, and then wagering points that they will either lose or gain depending on the outcome of the answer. One of the elements should be a simple code where the user inputs their name (Like: "John Smith"), and then it takes the name, scans for the space and takes the first for letters of the last name and combines it with the first letter of the first name (smitJ). However, it isn't working in the way I want it to.

I've tried using the indexOf the space and then seeing if it matched with the name, as well as using valueOf to see if it would match. I was also messing about with the substring numbers so those might be off.

public class HiLoSummativeUI extends javax.swing.JFrame {

    String name;
    public HiLoSummativeUI() {

        initComponents();
    }
    String spaceIS;
private void nameButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        name = nameInput.getText();
        System.out.println(name);
        spaceIS = " ";
        System.out.println(spaceIS);
        for (int i=0;i<name.length();i++){
            String s = String.valueOf(" ");
            if(s.equals(spaceIS)) {
                String lastName = name.substring(i, i+3) + name.substring(0,1);
                nameOutput.setText("Hello: " + lastName);
            }
        }
    }                                          

If I were to enter "John Smith", the UI should return "smitJ", however, it returns something like "ithJ" with this error code:

Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 11

  • 1
    Possible duplicate of [What is IndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/questions/40006317/what-is-indexoutofboundsexception-how-can-i-fix-it) – takendarkk Jan 26 '19 at 22:29

1 Answers1

0

Make the changes as shown below:

for (int i=0;i<name.length();i++){
                String s = String.valueOf(name.charAt(i));
                if(s.equals(spaceIS)) {
                    String lastName = name.substring(i+1, i+5) + name.substring(0,1);
                    nameOutput.setText("Hello: " + lastName);
                }
            }

As we have a space at the ith index, we start from i+1 index(inclusive) till i+5(exclusive).

uneq95
  • 2,158
  • 2
  • 17
  • 28