[문제 1]
- 문자열을 입력받아라
- 단, 입력받은 문자열을 일부 추출해야한다
- 입력받은 문자열과 img 확장자 파일이 일치한지 비교해라
- 일치할경우 이미지파일임을 나타내라
- for 구문으로 작성해라
- main코드를 완성하세요
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("파일명을 입력하세요. 단, 확장자 포함 : ");
String name = sc.next();
String[] img = {"png", "jpeg", "jpg", "gif", "jiff"};
}
[코드 완성 예시]
더보기
더보기
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("파일명을 입력하세요. 단, 확장자 포함 : ");
String name = sc.next();
int num = name.lastIndexOf(".");
String newName = name.substring(num+1);
boolean flag = true;
String[] img = {"png", "jpeg", "jpg", "gif", "jiff"};
for(int i=0; i< img.length ; i++) {
if (newName.equals(img[i])) {
flag = true;
break;
} else {
flag = false;
}
}
if(flag) {
System.out.println("이미지 파일이 맞습니다.");
} else {
System.out.println("이미지 파일이 아닙니다.");
}
/* if구문으로 사용한 것
if(newName.equals("png") || newName.equals("jpeg") || newName.equals("jpg") || newName.equals("gif") || newName.equals("jiff")) {
System.out.println("이미지 파일입니다.");
} else {
System.out.println("이미지 파일이 아닙니다");
}
*/
}
① 확장자 파일이 무엇인지, 이를 추출하기 위해서 어디를 접근해야하는지 판단 필요
⇒ "."을 통해 확장자 파일 판단
② 추출한 코드를 사용할 시, 어디서부터 출력되는지 확인
③ 문자열의 같음을 판단하기 위해 equlas 사용
④ for구문을 이용하여 img파일 배열문 확인 및 판단
[문제2]
- String name 안에 글을 보고 "f"가 몇번 출력되는지 코드를 작성해라
- f의 위치 및 반복횟수를 찾아라
- main코드를 완성하세요
public static void main(String[] args) {
String name = "finfal.pdf";
//Q.finfal.pdf에서 f가 몇변 나오는지 코드를 작성해보세요
}
[코드 완성 예시]
더보기
더보기
public static void main(String[] args) {
String name = "finfal.pdf";
int count = 0;
int result = 0;
for(int i=0; i<name.length();i++) {
int num1 = name.indexOf("f", result);
if(result == -1) {
break;
} else if(num1 == result) {
System.out.println("f의 위치 : " + num1);
}
result++;
}
}
int result = 0;
while(true) {
result = name.indexOf("f", result);
if(result == -1) {
break;
}
System.out.println("f의 위치 : " + result);
result++;
}
① index 범위를 벗어나면 -1을 나타내는 구문인 점을 이용해라
[문제 3]
- str에서 key로 주어지는 문자를 찾고, 찾은 수를 출력
- indexof()를 반복문과 함께 풀어라
- main코드를 완성해라
public static void main(String[] args) {
String str = "start hello java, hello spring, hello jpa";
String key = "hello";
// 코드 작성
}
[코드 완성 예시]
더보기
더보기
int num = 0;
int count = 0;
for(int i=0; i<str.length();i++) {
num = str.indexOf("hello", num);
if(num == -1) {
break;
}
//System.out.println(num);
str = str.substring(num+1);
System.out.println(str);
count++;
}
System.out.println("hello의 개수 : " + count);
① for구문 없이 나타내기 위한 방법 고민
② substring 구문 이용하기
public static void main(String[] args) {
String str = "start hello java, hello spring, hello jpa";
String key = "hello";
//substring으로 접근 --> 일부 추출 --> 접근
// 코드 작성
int count = 0;
int index = str.indexOf(key); //index위치
while(index >= 0) { //index의 범위가 0보다 커야함 == -1이 되면 안됨
index = str.indexOf(key, index+1);
count++;
}
System.out.println("hello의 개수 : " + count);
}
728x90
'Java > [문제]' 카테고리의 다른 글
[국비][문제] 배열에서 필요한 것 찾고, 지운 후 새로운 배열에 담기 (0) | 2024.06.06 |
---|---|
[국비][문제] 주민등록번호 유효성 판단, 지역별 날씨 분류 (0) | 2024.06.04 |