JAVA - 按混合顺序输出?

时间:2015-01-05 00:52:01

标签: java string printing output

我正在写一个非常基本的程序,我把它放在一个字符串中,然后打印出单词,以及字符串的第一个和最后一个字母。输出应如下所示:

word :: Hello

首字母:: H

最后一封信:: o

但事实并非如此。字母出现在单词之前,好吧,基本上顺序和间距是疯了!希望有人可以帮助我。这是代码:

FirstAndLast Class:



import static java.lang.System.*;

public class FirstAndLast
{
	private String word;

	public FirstAndLast(String s)
	{
	    word = s;
	}

	public void setString(String s)
	{
	    word = s;
	}
	
	public String getWord ()
	{
	     out.print(word);
	     return "";
	}
	
	public String getFirst()
	{
		out.print(word.charAt(0));
	    return "";
	}
	
	public String getLast()
	{
	    out.print(word.charAt((word.length())-1));
	    return "";
	}

 	public String toString()
 	{
 	    String output="";
 		return output;
	}
}




亚军类:



import static java.lang.System.*;

public class FirstRunner
{
	public static void main ( String[] args )
	{
		FirstAndLast demo = new FirstAndLast("Hello");
		System.out.println( "Word :: " + demo.getWord() );
		System.out.println( "First letter :: " + demo.getFirst() );
		System.out.println( "Last letter :: " + demo.getLast() );
		
		FirstAndLast bri = new FirstAndLast("Brianna");
		System.out.println( "Word :: " + bri.getWord() );
		System.out.println( "First letter :: " + bri.getFirst() );
		System.out.println( "Last letter :: " + bri.getLast() );
		
	}
}




谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个:

public class FirstAndLast
{
    private String word;

    public FirstAndLast(String s)
    {
        word = s;
    }

    public String getWord ()
    {
         return word;
    }

    public char getFirst()
    {
        return word.charAt(0);
    }

    public char getLast()
    {
        return word.charAt((word.length())-1);
    }
}

问题在于您为""getWord()getLast()方法返回getFirst()或什么都没有。相反,你可以返回你想要打印的内容。