[JAVA] boolean, 문자열

장성욱·2025년 6월 30일

JAVA

목록 보기
16/23

boolean

자료형 중 한 종류

  • 2값만 저장이 가능 (true, false)
선언법
boolean found = true;
boolean isRainy = false;
  • boolean 변수
    조건의 상태를 저장할 때 유연하게 사용

  • 조건문과 함께 자주 사용

  • 논리연산자와 자주 사용

&&(그리고), !(부정, 반대의 의미)

equals( )

문자열을 비교할 때 사용

String a = a;
if (a.eqauls('a') {
	System.out.println("둘은 같음");
}

입력한 것들을 토대로 참 거짓을 판단하기에
a와 'a'의 순서는 상관없음

charAt()

문자열에서 특정 위치의 문자 하나를 꺼내주는 키워드

str.charAt(i)
ㄴ 문자열 str에서 i번째 문자를 꺼냄

.toLowerCase() / .toUpperCase()

문자열에 대문자를 소문자로 변환 / 문자열에 소문자를 대문자로 변환


문제1) 짝수가 있는지 확인

import java.util.ArrayList;
import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    ArrayList<Integer> list = new ArrayList<> ();

    for (int i = 0; i < 5; i ++) {
      System.out.printf("%d번째 숫자를 입력해 주세요 : ", i +1);
      int num = sc.nextInt();
      sc.nextLine();

      list.add(num);
    }
    boolean found = false; // 우선 거짓으로 선언
    for (int i = 0; i < list.size(); i ++) {
      if (list.get(i) % 2 == 0) {	// list의 i번째 인덱스가 짝수라면
        found = true;	// true로 변경
        break;	// 멈춤
      }
    }
    if (found) {	// 
      System.out.println("짝수가 있습니다.");
    }
    else {
      System.out.println("짝수가 없습니다.");
    }
  }
}

문제2) 비밀번호 확인

import java.util.Scanner;
class Main{
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String[] passwords = {"1234", "abcd", "qwer", "pass"};
    while(true) {
      System.out.print("비밀번호를 입력하세요 : ");
      String pw = sc.nextLine();

      boolean found = false;
      for (int i = 0; i < passwords.length; i ++) {
        if (pw.equals(passwords[i])) { 
        // pw랑 passwords[i]의 순서는 상관이 없음
          found = true;
          break;
        }
      }
      if (found) {
        System.out.println("로그인 성공");
        break;
      }
      else {
        System.out.println("비밀번호가 틀렸습니다.");
      }
    }
    sc.close();
  }
}

문제3) 문자 포함 여부

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("문자열 1개를 입력해 주세요 : ");
    String str = sc.nextLine();

    boolean found = false;
    for (int i = 0; i < str.length(); i ++) {
      if (str.charAt(i) == 'a') {
        found = true;
        break;
      }
    }
    if (found) {
      System.out.println("문자 a를 포함하고 있습니다.");
    }
    else {
      System.out.println("문자 a가 없습니다.");
    }
    sc.close();
  }
}

문제4) 대소문자 구분없이 문자의 개수 구하기


import java.util.Scanner;
class Main{
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int found_str_cnt = 0; // 찾을 문자열의 개수 

    System.out.print("문자열을 입력해 주세요 : ");
    String str = sc.nextLine();
    str = str.toLowerCase(); 
    // 입력받은 문자열을 소문자로 변환

    System.out.print("찾을 문자를 입력해 주세요 : ");
    String found_str = sc.nextLine();
    char fs = found_str.toLowerCase().charAt(0);
    // 입력받은 찾을 문자열을 소문자로 변환 후 문자로 꺼냄


    for (int i = 0; i < str.length(); i ++) {
      if (str.charAt(i) == fs) {  // 둘이 같다면 정수가 1씩 증가
        found_str_cnt ++;
      }
    }
    if (found_str_cnt > 0) {
      System.out.printf("%c의 개수 : %d",fs, found_str_cnt);
    }
    else {
      System.out.printf("입력하신 문자열에 %c가 존재하지 않습니다.");
    }
    sc.close();
  }
}
profile
https://frost-puck-b0f.notion.site/B-2610fdaef71d80c49d1bccdcb575dcb5

0개의 댓글