java,在for循环中保存输入

时间:2013-09-22 01:21:44

标签: java loops for-loop input save

做作业我想要让用户一次输入他的名字1个字符。我使用for循环继续要求他输入下一个字符。最后,我想显示整个名称,而不仅仅是给出的最后一个字母。我知道,随着循环的转变,它将继续打印掉最后一个字母,因为lastName=lastName.substring(0,1);

如何保存输入的最后一个字母并用它构建一个字符串?多数民众赞成我的问题

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

import javax.swing.JOptionPane;


public class onecharacter {


public static void main(String[] args) {


    for(int x=1; x>-1; x++){
    Scanner userInput = new Scanner( System.in );

    String lastName;
    if (x==1){
    System.out.println ("Please enter your last name, one character at a time.");
    }
    else 
        {System.out.println ("Next letter");}
    lastName= userInput.nextLine();
    //System.out.println (lastName.substring(0,1));
    lastName=lastName.substring(0,1);// only reading first character in string. 
    //In case someone puts more than 1 character in.
    int answer=
            JOptionPane.showConfirmDialog(null, "Are you finished?", "Click Yes or No:", JOptionPane.YES_NO_OPTION);
            if (answer== JOptionPane.YES_OPTION)
                {System.out.println ("You entered " +lastName); 


                System.exit(0);}



                else if (answer== JOptionPane.NO_OPTION);

                else
                    System.out.println ("This is Impossible");


    }


}

1 个答案:

答案 0 :(得分:2)

您需要再引入一个变量来读取该行。当你操纵字符串时,使用StringBuilder也是一个好主意:

 StringBuilder lastName;
 String line;
    if (x==1){
    System.out.println ("Please enter your last name, one character at a time.");
    }
    else 
        {System.out.println ("Next letter");}
    line = userInput.nextLine();
    lastName.append(line.substring(0,1));

如果StringBuilder引入了一些问题,请修改您的其余代码