처음에 테스트 케이스를 받아야하므로 정수형을 입력받아야한다.

그리고 나서 버퍼를 지워야하기 위해 nextLine을 사용

 

 

처음에 charAt을 사용해서 Hello라는 문구를 넣었을 때

숫자로 나왔다.

아스키 코드인 H(72) 와 o(111)의 합이 183이기 때문

 

그래서 찾아보니 문자열을 더하기 위해선 앞에 " " 를 붙여줘야 한다.

 

 

 

 

import java.util.Scanner;

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

        int T = sc.nextInt();
        sc.nextLine();

        for(int i = 0; i < T; i++){
            String str = sc.nextLine();
            System.out.println("" + str.charAt(0) + str.charAt(str.length() - 1));
        }
    }
}

'Java > 백준을 풀며' 카테고리의 다른 글

repeat(num)  (0) 2025.09.05
BigInteger  (1) 2025.08.28

백준 25314번(브론즈5) 문제를 풀며 문제발생

 

 

 


 

 

문자열을 반복하는 과정에서 메서드를 찾게 되었다.

 

.repeat(num> => num 안에는 숫자를 넣으면 된다.

System.out.println("long ".repeat(N / 4) + "int");

 

 

https://learn.microsoft.com/en-us/dotnet/api/java.lang.string.repeat?view=net-android-34.0

 

String.Repeat(Int32) Method (Java.Lang)

Returns a string whose value is the concatenation of this string repeated count times.

learn.microsoft.com

 

package Bronze5;

import java.util.Scanner;

public class num25314 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        int mul = num / 4;
        String plusNum = "long ";
        if(num <= 4){
            System.out.println("long int");
        }
        else if(num > 4){
            System.out.println(plusNum.repeat(mul) + "int");
        }
    }
}

 

이렇게 짜 보았는데 코드가 지저분한것 같아서

챗GPT에게 AS요청

 

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        System.out.println("long ".repeat(N / 4) + "int");
    }
}

 

다시 정리

 

package Bronze5;

import java.util.Scanner;

public class num25314 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        System.out.println("long ".repeat(N / 4) + "int");
    }
}

 

출력

 

 

'Java > 백준을 풀며' 카테고리의 다른 글

문자열연결 charAt(index)  (0) 2025.09.15
BigInteger  (1) 2025.08.28

 

백준 브론즈5를 풀다가 숫자를 나누려하는데 나누기가 되지 않는 상황 발생

 


 

그 이유는 사용가능 범위를 초과하였기 때문

 

 

 


 

 

그래서 BigInteger을 사용하여야 한다.

 

https://learn.microsoft.com/ko-kr/dotnet/api/java.math.biginteger?view=net-android-34.0

 

BigInteger 클래스 (Java.Math)

변경할 수 없는 임의 정밀도 정수입니다.

learn.microsoft.com

 

하지만 BigInteger은 산술 연산자를  사용하지 못하는데

그 이유는 객체이기 때문이다.

자바는 연산자 오버로딩을 지원하지 않는다.

 

 

따라서 우리는 이런 식으로 사용해야 한다.

 

 

 


 

 

백준에서는 클래스명을 Main으로 쓰지 않으면 컴파일 에러가 난다.

import java.math.BigInteger;
import java.util.Scanner;

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

        BigInteger n = sc.nextBigInteger();
        BigInteger m = sc.nextBigInteger();

        System.out.println(n.divide(m));
        System.out.println(n.remainder(m));
        sc.close();
    }
}

'Java > 백준을 풀며' 카테고리의 다른 글

문자열연결 charAt(index)  (0) 2025.09.15
repeat(num)  (0) 2025.09.05
package fc.java.test;

public class Human {
    public String name;
    public int age;
    private String phone;

    public Human(String name, int age, String phone) {
        this.name = name;
        this.age = age;
        this.phone = phone;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }

    public String getPhone(){
        return phone;
    }
}

 

package fc.java.test;

public class Test {
    public static void main(String[] args) {

        Human man = new Human("길동", 100, "010-1111-2222");
        System.out.println(man.getName() + "\t" + man.getAge() + "\t" + man.getPhone());
    }
}

'Java' 카테고리의 다른 글

scanner.nextLine()  (0) 2025.01.08
package HelloWorld.src.fc.java.part3;

import java.util.Scanner;

public class CarTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("자동차 일련번호:");
        int carSn = scanner.nextInt();

        scanner.nextLine();

        System.out.print("자동차 이름:");
        String carName = scanner.nextLine();

        System.out.print("자동차 가격:");
        int carPrice = scanner.nextInt();

        scanner.nextLine();

        System.out.print("자동차 소유자:");
        String carOwner = scanner.nextLine();

        System.out.print("자동차 연식:");
        int carYear = scanner.nextInt();

        scanner.nextLine();

        System.out.print("자동차 타입:");
        String carType = scanner.nextLine();

        System.out.println(carSn + "\t" + carName + "\t" + carPrice + "\t" + carOwner + "\t" + carYear + "\t" + carType);

    }
}

 

 

이런식으로 중간에 scanner.nextLine();을 생략하면 마지막에 타입을 입력하지 못하고

바로 출력되는 경우가 생긴다.

그렇다고 모든 입력 끝에 scanner.nextLine();을 작성하진 않는다.

 

왜일가?

 

nextInt() 또는 nextDouble() 후에 nextLine()을 추가로 호출하는 이유는,

숫자 입력 후 남아 있는 줄바꿈 문자가 이후 nextLine()에서 처리되는 것을 방지하기 위해서이다.

'Java' 카테고리의 다른 글

생성자 매개변수  (1) 2025.02.13

 

package com.example.yaejunshin_finalproject;

public class Car {
    private int id;
    private String name;
    private int price;
    private String owner;
    private int year;

    public Car(int id, String name, int price, String owner, int year) {
        this.id = id;

        //차량 이름 검증(공백금지)
        if(name == null || name.isEmpty()){
            throw new IllegalArgumentException("차량 이름은 필수이며, 공백일 수 없습니다.");
        }
        this.name = name;

        //차량 가격 검증(0보다 커야 함)
        if(price <= 0){
            throw new IllegalArgumentException("차량 가격은 0 보다 커야 합니다.");
        }
        this.price = price;

        //차량 소유자 검증(null 또는 빈 문자열은 허용하지 않습니다.)
        if(owner == null || owner.isEmpty()){
            throw new IllegalArgumentException("차량 소유자는 필수이며, 공백일 수 없습니다.");
        }
        this.owner = owner;

        //차량 연식 검증(1950보다 커야함)
        if(year <= 1950){
            throw new IllegalArgumentException("차량 연식은 1950 보다 커야 합니다.");
        }
        this.year = year;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }

    public String getOwner() {
        return owner;
    }

    public int getYear() {
        return year;
    }

    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price='" + price + '\'' +
                ", owner='" + owner + '\'' +
                ", year=" + year +
                '}';
    }
}

 

 

package com.example.yaejunshin_finalproject;

public class User {
    private int id;
    private String name;
    private String email;

    public User(int id, String name, String email) {
        this.id = id;

        //유저 이름 검증(공백금지)
        if(name == null || name.isEmpty()){
            throw new IllegalArgumentException("null 또는 빈 문자열은 허용하지 않습니다.");
        }
        this.name = name;

        //유저 이메일 검증(필수이며 공백금지)
        if(email == null || email.isEmpty()){
            throw new IllegalArgumentException("유저 이메일은 필수이며, 공백일 수 없습니다.");
        }
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }
}

 

 

package com.example.yaejunshin_finalproject;

import java.time.LocalDate;
import java.time.LocalTime;

public class Reservation {
    private int id;
    private String name;
    private User user;
    private Car car;
    private LocalDate date;
    private LocalTime time;

    public Reservation(int id, String name, User user, Car car, LocalDate date, LocalTime time) {
        this.id = id;
        this.name = name;
        this.user = user;
        this.car = car;
        this.date = date;
        this.time = time;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public User getUser() {
        return user;
    }

    public Car getCar() {
        return car;
    }

    public LocalDate getDate() {
        return date;
    }

    public LocalTime getTime() {
        return time;
    }

    @Override
    public String toString() {
        return "Reservation{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", user=" + user +
                ", car=" + car +
                ", date=" + date +
                ", time=" + time +
                '}';
    }
}

src - webapp - new - other - jsp

<%@ page contentType="text/html;charset=utf-8"%>
<%@ taglib prefix="c"   uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
	<title>JSTL</title>
</head>
<body>
<c:set var="to"   value="10"/>
<c:set var="arr"  value="10,20,30,40,50,60,70"/> 
<c:forEach var="i" begin="1" end="${to}">
	${i}
</c:forEach>
<br>
<c:if test="${not empty arr}">
	<c:forEach var="elem" items="${arr}" varStatus="status">
		${status.count}. arr[${status.index}]=${elem}<BR>
	</c:forEach>
</c:if>	
<c:if test="${param.msg != null}">
	msg=${param.msg} 
	msg=<c:out value="${param.msg}"/>
</c:if>
<br>
<c:if test="${param.msg == null}">메시지가 없습니다.<br></c:if>
<c:set var="age" value="${param.age}"/>
<c:choose>
	<c:when test="${age >= 19}">성인입니다.</c:when>
	<c:when test="${0 <= age && age < 19}">성인이 아닙니다.</c:when>
	<c:otherwise>값이 유효하지 않습니다.</c:otherwise>
</c:choose>
<br>
<c:set var="now" value="<%=new java.util.Date() %>"/>
Server time is <fmt:formatDate value="${now}" type="both" pattern="yyyy/MM/dd HH:mm:ss"/>	
</body>
</html>

 

 

 

 

 

필터를 만들어서 jsp에 적용되는지 확인

package com.fastcampus.ch2;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

// 필터를 적용할 요청의 패턴 지정 - 모든 요청에 필터를 적용.
@WebFilter(urlPatterns="/*")
public class PerformanceFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 초기화 작업
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 1. 전처리 작업
		long startTime = System.currentTimeMillis();

		// 2. 서블릿 또는 다음 필터를 호출
		chain.doFilter(request, response); 
		
		// 3. 후처리 작업
		System.out.print("["+((HttpServletRequest)request).getRequestURI()+"]");
		System.out.println(" 소요시간="+(System.currentTimeMillis()-startTime)+"ms");
	}

	@Override
	public void destroy() {
		// 정리 작업
	}

}

 

첫 호출에 시간이 오래걸린다.

+ 여러개에 적용가능하고 전처리, 후처리 코드는 사실 없어도 된다.

 

 

서블릿은 기본적으로 lazy-init 이지만 loadOnStartup으로 인해 처음에 초기화 가능

그리고 아래는 호출을 할때 우선순위이다.

 

아래와 같이 /hello.do 로 오면 default가 처리한다 (정적 리소스)

 

 

 

 

 

 

el을 실습해 볼 것이다.

 

Car 클래스를 만들고

 

package com.fastcampus.ch2;

public class Car    { 
	private String color = "red"; 
	public String getColor() { return color; }
}

 

 

Person 클래스를 하나 만든다.

package com.fastcampus.ch2;

public class Person { 
	private Car car = new Car(); 
	public  Car getCar() { return car; }
}

 

 

 

src - main - webapp - new - other -jsp 

 

 

<%@ page contentType="text/html;charset=utf-8"%>
<%@ taglib prefix="c"   uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page import="com.fastcampus.ch2.*" %>
<%
	Person person = new Person();
	request.setAttribute("person", person);
	request.setAttribute("name", "남궁성");   
	request.setAttribute("list", new java.util.ArrayList());	
%>
<html>  
<head>   
	<title>EL</title>   
</head>  
<body>   
person.getCar().getColor()=<%=person.getCar().getColor()%> <br>
person.getCar().getColor()=${person.getCar().getColor()} <br>
person.getCar().getColor()=${person.car.color} <br>    
name=<%=request.getAttribute("name")%> <br>   
name=${requestScope.name} <br>
name=${name} <br>
id=<%=request.getParameter("id")%> <br>
id=${pageContext.request.getParameter("id")} <br>
id=${param.id} <br>
"1"+1 = ${"1"+1} <br>
"1"+="1" = ${"1"+="1"} <br>
"2">1 = ${"2">1} <br>   
null = ${null}<br>
null+1 = ${null+1} <br>
null+null = ${null+null} <br>
"" + null = ${""+null} <br>   
""-1 = ${""-1} <br> 
empty null=${empty null} <br>
empty list=${empty list} <br>
null==0 = ${null==0} <br>
null eq 0 = ${null eq 0} <br>
name == "남궁성"=${name=="남궁성"} <br>
name != "남궁성"=${name!="남궁성"} <br>
name eq "남궁성"=${name eq "남궁성"} <br>  
name ne "남궁성"=${name ne "남궁성"} <br>  
name.equals("남궁성")=${name.equals("남궁성")} <br>   
</body>
</html>

 

실행을 해보면 결과물

이제 변환되는 과정을 볼 것이다.

 

deploy 경로를 복사 후 Don't Save

 

 

탐색기로 이동 후 뒤로가기 한번 한 후 - work - Catalina - localhost - app -org - apache - jsp

 

위에 폴더를 타고 들어가면 스프링이 변환 된 뷰 이고

 

el_jsp.java 서블릿 소스 파일

위에 class는 컴파일 된 것이다.

 

 

만약에 실행이 잘 되지 않아서 지우고 싶으면 여기서 맨 위 폴더를 지우고 제외하거나

이러한 방식으로 지울 수 있다.

 

jsp를 변경 시 적용 안될 때 사용하고 다시 실행하면 만들어진다.

 

request에 map형태로 저장하는 과정

 

 

 

위에 처럼 저장을 하지 않으면

아래 방법으로는 el에서 표시할 수 없다.

 

el에서 "1" + 1 = 11가 아닌 문자열이 숫자로 바뀌어서 2로 출력됨.

 

저장소는 총 4가지가 있다.

1.pageContext

2. application

3. session

4. request

 

같은 페이지 안에섬나 접근 가능

요청할때마다 초기화 됨

 

 

어플리케이션 저장소를 모두 저장하기에 id를 저장하기엔 좋지 않다.

 

 

세션은 1대1이기에 사용자 수 만큼 개수가 생긴다.

따라서 최소한의 데이터만 저장해야 한다.

 

 

request 저장소는 첫번째 jsp에서받지 않고 두번째로 받을 수 있다.

 

요약

 

 

package com.fastcampus.ch2;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.service(req, resp);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}

}

 

 

호출이 언제 되는지 확인

package com.fastcampus.ch2;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet{

	@Override
	public void init() throws ServletException {
		// 서블릿이 초기화 될 때 자동 호출되는 메서드
		// 1. 서블릿의 초기화 작업 담당
		System.out.println("[HelloServlet] init() is called");
	}
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("[HelloServlet] service() is called");
	}

	@Override
	public void destroy() {
		System.out.println("[HelloServlet] destroy() is called");
	}

	

}

 

init은 처음에만 호출되고 새로고침하면 service는 계속 호출된다.

 

 

코드를 수정하고 저장하면 재시작 되므로

destroy가 호출됨

 

 

 

JSP

 

 

 

<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.Random" %>
<%-- <%! 클래스 영역 %> --%>
<%!  
	int getRandomInt(int range){
		return new Random().nextInt(range)+1;
	}
%>
<%-- <%  메서드 영역 - service()의 내부 %> --%>
<%
	int idx1 = getRandomInt(6);
	int idx2 = getRandomInt(6);
%>
<html>
<head>
	<title>twoDice.jsp</title>
</head>
<body>
	<img src='resources/img/dice<%=idx1%>.jpg'>
	<img src='resources/img/dice<%=idx2%>.jpg'>
</body>
</html>

 

별도로 매핑해주지 않아도 jsp는 자동으로 매핑이 된다.

 

 

 

 

서블릿 : lazy-init

spring : early-init

 

 

서비스 메서드에 기본으로 생성되어 있는 것들은 사용가능

+ Recent posts