○ 코딩 작성 중 실수 내용

- 코딩테스트 문제를 풀던 중 JAVA 제곱근을 사용해야 하는 코드가 나왔는데 Math.pow(a,b)가 아닌 a^b를 사용

 

○ 원인 파악

- '^'는 XOR 논리연산자

A B A XOR B
0 0 0
0 1 1
1 0 1
1 1 0

(ex. JAVA에서 4^7 실행 시-> 2진법 100 , 111의 XOR 연산자로 011 정답 3)

- 알고 있었으나 습관적으로 a^b라고 사용

- 왜 저게 습관이 되었는지 생각해보니 컴퓨터상으로 문서작성(hwp, word) 을 할 때 제곱근을 표현할 수 없어 자주 a^b라고 작성했는데 JAVA에도 무심코 사용하면서 오류 발생

- 코딩테스트 진행 시 알게모르게 작성했다가 Error원인이 파악 안되면서 이상한 곳에서 시간을 잡아먹는것을 방지하지 위해 오답노트 작성

○ 문제링크

https://www.hackerrank.com/challenges/java-stdin-stdout/problem

 

Java Stdin and Stdout II | HackerRank

Familiarize yourself with Standard Input/Output.

www.hackerrank.com

 

○ 문제 내용 요약

Input Format

There are three lines of input:

  1. The first line contains an integer.
  2. The second line contains a double.
  3. The third line contains a String.

Output Format

There are three lines of output:

  1. On the first line, print String: followed by the unaltered String read from stdin.
  2. On the second line, print Double: followed by the unaltered double read from stdin.
  3. On the third line, print Int: followed by the unaltered integer read from stdin.

To make the problem easier, a portion of the code is already provided in the editor.

Note: If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int i = scan.nextInt();
        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

 

○ 문제의 핵심

- scan.nextInt() 동작 이후 scan.nextLine() 진행시 개행문자 '\n' 이 개행문자로 남아 다음 본문을 재대로 인식하지 못한 부분을 해결

 

○ 해결방법

1. int, double도 scan.nextLine()으로 입력받은 후 Integer.parseInt(String); Double.parseDouble(String); 으로 변경

(BUT, 해당 문제는 최초에 Write your Code here 전 int i 를 받고 있어 다음 문장을 작성해야하므로 Integer.parseInt(String) 를 사용할 수 없음)

2. 숫자 먼저 받은 후(int, Double) String을 받기전 scan.nextLine(); 으로 개행문자 제거

다음 scan.nextLine(); 을 이용해 정상적인 문자열 scan 진행

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int i = scan.nextInt();
        // Write your code here.
        double d = scan.nextDouble();
        scan.nextLine();
        String s = scan.nextLine();

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

Controller에서 작업 중 특정 back URL로 redirect를 하는 상황이 생긴다.

아래와 같이 작성하면 된다.

 

URL redirect 소스코드(Java)

	@RequestMapping("redirect")
	public String redirectTest(String url){
		return "redirect:" + url;
	}

 

이렇게 보내면 redirect를 이용해서 URL을 보낼 수 있지만 parameter도 필요하다면?

다양한 방법이 있지만 java에 model과 jsp에 jquery를 이용해 redirect하는 방법을 제시하고자 한다.

 

URL redirect parameter 추가 소스코드(Java, jsp)

	@RequestMapping("redirect")
	public String redirectTest(String url, Model model){
		model.addAttribute("name","호파");
		model.addAttribute("local","seoul");
		model.addAttribute("sex","m");
		model.addAttribute("redirectUrl",url);
		return "redirect" //view->redirect.jsp를 호출
	}

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>




redirectTest




'Programming > JAVA' 카테고리의 다른 글

TCP/IP Socket 통신 프로그래밍 (Java Sample 소스코드)  (0) 2018.05.01

+ Recent posts