2009年3月9日 星期一

Homework 3-2-2009

1. Write a program that can reverse the order of an input string. For example, if you input "ab", it will output "ba". If you input "abcdefg", it should return "gfedcba".

概念:
比如我有6個字,所以.length()=6
但是我要從編號5開始倒著排回去(5 4 3 2 1 0)
所以.length()-1並取for迴圈美執行ㄧ次減一個編號這樣(--)

public static void main(String[] args) {
String word = "ab";
System.out.println(word);
for(int i=word.length()-1;i>=0;i--)
{
System.out.print(word.charAt(i));
}

String word2 = "abcdefg";
System.out.println("\n" + word2);
for(int i=word2.length()-1;i>=0;i--)
{
System.out.print(word2.charAt(i));
}

// TODO code application logic here
}


2. Write a program that can print names alternatively. The names are in the format of "First Name + Last Name" or "Last Name, First Name". For example, if you input "Walt Savitch", your program will output "Savitch, Walt". If you input "Savitch, Walt", your program will output "Walt Savitch".


用,來取位置來交換前半段和後半段

public static void main(String[] args) {
String name = "Dispy,Jhung";
System.out.println(name);
int i = name.indexOf(",");
String start = name.substring(i+1);
String end = name.substring(0,i);
name = start+" "+end;
System.out.println(name);

沒有留言:

張貼留言