2017-10-29 8 views
-3

私のコードでreplace関数を使用すると読むことができます。 ねえ、私です。 ねえ、(名前)。 ヘイ、(名前)のみを印刷する必要があるとき。 そして、私は理由を理解していません。コードは次のとおりです。javaを2つの文字列に置き換えてください

/* 
* 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+"."); 
     } 


    } 

} 
+1

'times'の値は何ですか?' greeting'には何を入力しましたか? –

+0

あなたの入力は何ですか? – user3437460

+0

コードを取得しようとしている入力を入力してください。 – Yashovardhan

答えて

0

Scanner.next()は、デフォルトではスペースで次の区切り文字、までご入力を読み込みます。このため、1つの入力I'm Joeではなく、2つの入力I'mJoeが取得されています。

一度に全行を取りたい場合は、Scanner.nextLine()を使用してください。 (最初にnextIntのためにあなたに影響するthis quirkを気にする必要があります)

-2

JavaのString.replaceメソッドは、1つの文字列を見つけて置き換えます。 だから、私はあなたがteclado.next();は、スペースで区切られ、コンソールに次の値をフェッチするので、それがあるString.replaceAll

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

を使用することを推奨します。 teclado.nextLine();を使用します。これは完全な修正ではありませんが。あなたがこのアプローチをフォローアップして、 "I'm Jake"と入力すると、プログラムは "Hey、。"続いて「ヘイ、ジェイク」。これはあなたがteclado.nextInt();を使用しているためですが、Scanner#nextLine()にはすぐに「I'm Jake」と表示されません。したがって、あなたはまた、nextLine();nextInt();を交換し、それを解析する必要があります。

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 + "."); 
     } 
} 
関連する問題