-3

Well as you can read, when i use the replace function in my code it prints out: Hey, I'm. Hey, (name). When it should only print out Hey, (name). And i dont understand why. Here is the code:

 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fiestaaburrida;

import java.util.Scanner;

/**
 *
 * @author xBaco
 */
public class FiestaAburrida {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner teclado = new Scanner(System.in);
        int times = teclado.nextInt();
        int index = 0;
        while (index < times){
            String greeting = teclado.next();
            String newgreeting = greeting.replace("I'm ","");
            System.out.println("Hey, "+newgreeting+".");
        }


    }

}
Bcct
  • 27
  • 5

3 Answers3

0

It is because teclado.next(); fetches the next value in the console that is separated by a space. You want to use teclado.nextLine();. Although this is not a complete fix. If you were to follow up with this approach and enter "I'm Jake", than the program would print "Hey, ." followed by "Hey, Jake". This is because you are using teclado.nextInt();, which works, but it will not cause Scanner#nextLine() to read "I'm Jake" immediately. Thus you must also replace nextInt(); with nextLine(); and parse it:

public static void main(String[] args) {
        Scanner teclado = new Scanner(System.in);
        int times = Integer.parseInt(teclado.nextLine());
        int index = 0;
        while (index < times){
            String greeting = teclado.nextLine();
            String newgreeting = greeting.replace("I'm ","");
            System.out.println("Hey, " + newgreeting + ".");
        }
}
Cardinal System
  • 2,227
  • 2
  • 18
  • 33
0

Scanner.next() will read your input up to the next delimeter, which by default is a space. Because of this, you are getting two inputs, I'm Joe, rather than the one input I'm Joe.

If you want to take in an entire line at once, you should use Scanner.nextLine(). (Though you should watch out for this quirk which will affect you because of your first nextInt.)

Joe C
  • 13,953
  • 7
  • 35
  • 48
-2

Java's String.replace method find one string and replace the one. So, I recommend you use String.replaceAll

    // ....
    while (index < times){
        String greeting = teclado.next();
        String newgreeting = greeting.replaceAll("I'm ","");
        System.out.println("Hey, "+newgreeting+".");
    }
    // ....
drakejin
  • 184
  • 1
  • 1
  • 12