当前位置: 代码迷 >> Java相关 >> 编程练习(1)
  详细解决方案

编程练习(1)

热度:533   发布时间:2004-06-26 22:24:00.0
编程练习(1)

Write a program that asks for the user's name and then writes that name to the monitor with either "Ms." or "Mr." in front, depending if the name is for a female or male. Assume that the only female names are

  • Amy
  • Buffy
  • Cathy

and that the only male names are

  • Elroy
  • Fred
  • Graham

All other names will be echoed without a title. The program continutes looping until the user hits "enter" without first typing a name.

C:\>java Title
Enter a name:
Amy Johnson
Ms. Amy Johnson

Enter a name:
Fred Smith
Mr. Fred Smith

Enter a name:
Zoltan Jones
Zoltan Jones

Enter a name:
(this exercise comes from http://chortle.ccsu.edu/cs151/cs151java)

搜索更多相关的解决方案: 练习  name  female  

----------------解决方案--------------------------------------------------------

This is my answer for this question:

/* Test.java */

import java.io.*; public class Test { //判断是否为男士 static boolean isMale(String s) { if(s.startsWith("Elroy") || s.startsWith("Fred") || s.startsWith("Graham")) return true; else return false; } //判断是否为女士 static boolean isFemale(String s) { if(s.startsWith("Amy") || s.startsWith("Buffy") || s.startsWith("Cathy")) return true; else return false; } public static void main(String[] args)throws IOException { BufferedReader data = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a name:"); String str = data.readLine();

while(str.length() != 0) { if(isMale(str)) System.out.println("Mr. " + str); else if(isFemale(str)) System.out.println("Ms. " + str); else System.out.println(str);

System.out.println("Enter a name:"); str = data.readLine(); } } }


----------------解决方案--------------------------------------------------------

import java.io.*;

public class Name{ public static void main(String [] args) throws IOException { BufferedReader keyboard = new BufferedReader( new InputStreamReader(System.in));

final String[] MENNAMES = {"Elroy","Fred","Graham"}; final String[] LADYNAMES = {"Amy","Buffy","Cathy"}; System.out.print("Enter a name: "); String inputName = keyboard.readLine();

while(inputName.length()!=0){ boolean notDone = true; for(int i = 0; i<MENNAMES.length&&notDone; i++){ String familyName = inputName.substring(0,inputName.indexOf(" ")); if(familyName.equals(MENNAMES[i])){ System.out.println("Mr. "+inputName); notDone = false; } else if(familyName.equals(LADYNAMES[i])){ System.out.println("Ms. "+inputName); notDone = false; } } if(notDone) System.out.println(inputName); System.out.print("Enter a name: "); inputName = keyboard.readLine(); } } }

//随便写了一下,可能有错误,呵呵,多多指教


----------------解决方案--------------------------------------------------------
  相关解决方案