String 문제
문제1
String email ="test_co.kr";
이메일에 @이 존재 여부 체크 indexOf를 이용
String email2 = "test@test.cm";
이메일에 co.kr 또는 .com 있어야 정상 이메일 index를 이용
내가 푼 정답----------------------
package basic_class;
public class String_test01 {
public static void main(String[] args) {
String email ="test_co.kr";
String email2 = "test@test.cm";
if (email.indexOf("@") > -1) {
if (email.indexOf("co.kr") > -1 || email.indexOf(".com") > - 1)
System.out.println("정상이메일입니다.");
else System.out.println("email은 비정상");
}
else System.out.println("email은 비정상");
if (email2.indexOf("@") > -1) {
if (email2.indexOf("co.kr") > -1 || email2.indexOf(".com") > - 1)
System.out.println("email2는 정상이메일입니다.");
else System.out.println("email2는 비정상");
}
else System.out.println("email2는 비정상");
}
}
내가 푼 응용----------------------
이메일을 입력받아 @이 있고 .co.kr 이나 .com이 있어야만 정상, 그 외엔 비정상 판정
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("이메일을 입력하십시오.");
String email = in.nextLine();
if (email.indexOf("@") > -1) {
if (email.indexOf("co.kr") > -1 || email.indexOf(".com") > - 1)
System.out.println("정상이메일입니다.");
else System.out.println("비정상이메일입니다.");
}
else System.out.println("비정상이메일입니다.");
강사님의 정답----------------------
package basic_class;
import java.util.Scanner;
public class String03 {
public static void main(String[] args) {
String email1 ="test_co.kr";
if (email1.indexOf("@") == -1) {
System.out.println("@ 없음");
}else {
System.out.println("정상");
}
String email2 = "test@test.cm";
if (email2.indexOf("co.kr") == -1 && email2.indexOf(".com") == - 1)
System.out.println(".co.kr 이나 .com 없음");
else System.out.println("정상");
}
}
문제2
- String str = "Hello";
위의 문자열을 chatAt()을 이용해서 한 char씩 출력하면서 대문자인지 소문자인지도 출력하시오.( 'A' > ch )
내가 푼 정답----------------------
package basic_class;
public class String_test02 {
public static void main(String[] args) {
String str = "Hello";
int len = str.length();
for (int cnt=0;cnt<len;cnt++){
char ch = str.charAt(cnt);
if (ch >=65 && ch <= 90)
//대문자는 아스키 값으로 65부터 90이고
// 소문자는 아스키 값으로 97부터 122까지며 그 범위 들어가 있으면 영문자이다.
// if (ch >= 'A' && ch <= 'Z') 대문자 순서를 이용하여 이런식으로도 할 수 있음
System.out.println(ch+"는 대문자");
else System.out.println(ch+"는 소문자");
}
}
}
수업 내용의 정답----------------------
public class StringExam01 {
public static void main(String[] args) {
String str = "Hello";
for(int i=0; i<str.length(); i++){
char ch = str.charAt(i);
if(ch >= 'A' && ch <= 'Z'){
System.out.println(ch + ":대문자");
}else {
System.out.println(ch + ":소문자");
}
}
}
}
문제3
- 키보드로 yyyymmdd 를 입력받고 년월일을 출력하고 12~2월이면 겨울 3~5월이면 봄 6~8월이면 여름 9~11월이면 가을이라고 출력하시오. ( int a = Integer.parseInt("100"); )
내가 푼 정답----------------------
package basic_class;
import java.util.Scanner;
public class String_test03 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("8글자로 년월일을 입력하시오");
System.out.println("ex) yyyymmdd");
String ymd = in.nextLine();
System.out.println(ymd.substring(0,4)+"년 "+ymd.substring(4,6)+"월 "+ymd.substring(6,8)+"일");
int mm = Integer.parseInt(ymd.substring(5,6)); // 문자를 숫자로 변환
if (mm >= 3 && mm<=5) System.out.println("봄");
else if (mm >= 6 && mm<=8) System.out.println("여름");
else if (mm >= 9 && mm<=11) System.out.println("가을");
else System.out.println("겨울");
}
}
내가 푼 응용 정답----------------------
package basic_class;
import java.util.Scanner;
import java.util.Calendar;
public class String_test03 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Calendar oCalendar = Calendar.getInstance( ); // 현재 날짜/시간 등의 각종 정보 얻기
System.out.println("8글자로 년월일을 입력하시오");
System.out.println("ex) yyyymmdd");
String ymd = in.nextLine();
int yy = Integer.parseInt(ymd.substring(0,4)); // 문자를 숫자로 변환
int mm = Integer.parseInt(ymd.substring(4,6)); // 문자를 숫자로 변환
int dd = Integer.parseInt(ymd.substring(6,8)); // 문자를 숫자로 변환
if (yy < 1865 || yy > oCalendar.get(Calendar.YEAR)) { //올해년도보다 크거나 150살 이상은 에러
System.out.println("올바른 년도를 입력하시오");
}
else if (mm == 0 || mm > 12) { //0월 및 13월부터는 불가
System.out.println("올바른 월을 입력하시오");
}
else if (dd == 0 || dd > 31) { //0일 및 31일부터는 불가
System.out.println("올바른 날짜를 입력하시오");
}
else { System.out.println(yy+"년 "+mm+"월 "+dd+"일");
if (mm >= 3 && mm<=5) System.out.println("봄");
else if (mm >= 6 && mm<=8) System.out.println("여름");
else if (mm >= 7 && mm<=11) System.out.println("가을");
else System.out.println("겨울");
}
}
}
수업 내용의 정답----------------------
public class StringExam02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("yyyymmdd:");
String ymd = in.next();
String y = ymd.substring(0, 4);
String m = ymd.substring(4,6);
String d = ymd.substring(6);
int iMonth = Integer.parseInt(m);
String season = "";
if(iMonth==12 || iMonth<=2){
season = "겨울";
}else if(iMonth>=3 && iMonth <=5){
season = "봄";
}else if(iMonth>=6 && iMonth <=8){
season = "여름";
}else if(iMonth>=9 && iMonth <=11){
season = "가을";
}
System.out.println(y+"년"+m+"월"+d+"일 "+season);
}
}
문제4
- String data = "이순신;100;강감찬;98";
위의 data는 이름;점수 순으로 데이터가 구성되어 있다. 데이터를 substring으로 잘라내서 아래와 같이 출력하시오.
이순신 : 100점
강감찬 : 98점
합계 : 198
내가 푼 정답----------------------
package basic_class;
public class String_test04 {
public static void main(String[] args) {
String data = "이순신;100;강감찬;98";
int score1 = Integer.parseInt(data.substring(4,7));
int score2 = Integer.parseInt(data.substring(12,14));
int total = score1 + score2;
System.out.println (data.substring(0,3)+ " : "+data.substring(4,7)+"점");
System.out.println (data.substring(8,11)+ " : "+data.substring(12,14)+"점");
System.out.println ("합계 : "+total);
}
}
수업 내용의 정답----------------------
public class StringExam03 {
public static void main(String[] args) {
String data = "이순신;100;강감찬;98";
String name1 = data.substring(0,3);
String name2 = data.substring(8,11);
String score1 = data.substring(4,7);
String score2 = data.substring(12);
System.out.println(name1+":"+score1);
System.out.println(name2+":"+score2);
int iScore1 = Integer.parseInt(score1);
int iScore2 = Integer.parseInt(score2);
System.out.println("합계:"+(iScore1+iScore2));
}
-------------------------------------------------------------------------------------------------
StringBuilder : thread에 안전장치 없으나 성능 좋음
StringBuffer : thread에 안전장치 있음
먼저 클래스 객체를 생성해서 사용해야 함. (생성자)
StringBuilder sb1;
sb1 = new StringBuilder("Hello);
sb2 = new StringBuilder(100);
(p394 참조)
StringTokenizer stok = new StringTokenizer("사과 배 복숭아"); // 1개의 문자열 데이터로부터 구분자 기준으로 잘라내어 추출.
기본 구분자는 공백, 다른 종류면 추가로 표시
stok.nextToken();
stok.nextToken();
stok.nextToken();
문제5
A사원과 B사원의 실적. A사원 실적 합과 B사원 실적 합, 전체 합을 출력하시오.
String data = "a:89;b:56;a:54;b:32;b:45;a:77";
package basic_class;
import java.util.*;
public class String_test05 {
public static void main(String[] args) {
String data = "a:89;b:56;a:54;b:32;b:45;a:77";
StringTokenizer stok = new StringTokenizer(data, ";");
int aSum = 0, bSum = 0;
while (stok.hasMoreTokens()) {
String token = stok.nextToken();
String empCode = token.substring(0,2); //0부터 2 문자데이터 추출
String empAmt = token.substring(2); //점수 부분 추출
int amt = Integer.parseInt(empAmt); // 추출한 점수를 숫자로 변환
if(empCode.equals("a:")){
aSum = aSum + amt;
}
else { bSum = bSum + amt;
}
}
System.out.println("A의 합계 : "+aSum);
System.out.println("B의 합계 : "+bSum);
System.out.println("총합 : "+(aSum+bSum));
}
}
'자바의 기초문법' 카테고리의 다른 글
package와 접근제어 public, private, protected, final (0) | 2015.12.22 |
---|---|
날짜와 시간 자바 클래스: Date, Calendar, GregorianCalendar (0) | 2015.12.21 |
String 클래스: substring, indexOf, StringBuilder, StringBuffer (0) | 2015.12.21 |
레퍼런스 타입: instanceof, enum 열거타입, values/valueOf 메소드 (0) | 2015.12.18 |
클래스를 나눠 학점, 평균 구하는 문제 (0) | 2015.12.18 |