inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

172만명의 커뮤니티!! 함께 토론해봐요.

java scanner 오류

미해결

txt파일에는 아래와 같이 저장되어 있습니다. 점수가 가장 높은 학생의 이름을 출력해야하고 점수가 동일할 경우 모두 출력하는 프로그램입니다. 김일번 64 김이번 83 김삼번 26 김사번 36 김오번 78 김육번 54 김칠번 60 김팔번 85 김구번 45 김십번 85 프로그램을 실행했을 때 Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor ( Scanner.java:94 7 ) at java.base /java.util.Scanner.nex t ( Scanner.java:160 2 ) at java.base/java.util.Scanner.nextInt ( Scanner.java:226 7 ) at java.base/java.util.Scanner.nextInt ( Scanner.java:222 1 ) 이렇게 오류가 발생합니다. 해결방법 아시는 분 가르쳐주세요!!ㅜㅜ package kh; import java.io.*; import java.util.Scanner; class Student { //int id; String name; int grade; Student(String name, int grade) { //this.id=id; this.name=name; this.grade=grade; } } class StudentTable{ Student[] st; StudentTable(int size) { st=new Student[size]; } void maxStudent() { int maxGrade=0; for(Student student : st) { if(student.grade > maxGrade) { maxGrade = student.grade; } } System.out.println("최고 점수를 가진 학생:"); for(Student student : st) { if(student.grade == maxGrade) { System.out.println(" " + student.name + " " + student.grade); } } } } public class homework05{ public static void main(String[] args) { StudentTable stable; try { FileInputStream fin=new FileInputStream("C:\\Users\\user\\Desktop\\student_score.txt"); Scanner scanner = new Scanner(fin); int size=scanner.nextInt(); stable=new StudentTable(size); for(int i=0; i<stable.st.length; i++) { //int id=scanner.nextInt(); String name=scanner.next(); int grade=scanner.nextInt(); stable.st[i]=new Student(name,grade); System.out.println(" "+name+" "+grade); } scanner.close(); stable.maxStudent(); } catch(FileNotFoundException e) { System.out.println("file not exist"); } } }

  • java
dkfma0799 댓글 1 좋아요 0 조회수 275

localstorage.setItem 위치 질문

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

수업에서는 '카운트다운 시작' 버튼 눌러서 Starter 함수가 실행되면 로컬 스토리지가 setInterval 함수로 인해 비워지기 때문에, CounterMaker 함수 내에 if문을 작성하여 해결하고 있습니다. 저는 이 방법 말고 사진처럼 starter 함수 내부에서 setInterval 함수(clearTimer라고 작성한..) 호출 위치를 조정하여 해결하였는데, 이 방법에 문제가 있을지 궁금합니다!

  • react
  • node.js
  • seo
  • graphql
  • next.js
연민지 댓글 2 좋아요 0 조회수 256

404 오류 관련 질문

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

05-05-dynamic-routing-board-mutation 05-05-dynamic-routing-board-mutation-moved 계속해서 대조해보지만 게시글 등록하기를 누르고 moved 페이지로 넘어갈 때 404 오류가 뜹니다. catch에서 잡히지 않는걸로 보아 데이터 전송에서 문제가 있는건 아니지 않을까 싶은데, 아무리 봐도 해결책이 보이지 않아 질문 남깁니다.

  • react
  • node.js
  • seo
  • graphql
  • next.js
winnaba61 댓글 2 좋아요 0 조회수 304

알고 있던 내용과 달라서 조금 혼동됩니다.

해결됨

김영한의 실전 자바 - 기본편

안녕하세요 영한님. 자바를 복습하고 있는 학생입니다. 이번 파트 정말 이해가 잘 되게 설명해주셔서 내용을 이해하는데는 어려움이 없었는데 기존에 알고 있던 지식때문인지 혼동되는 부분이 있어 질문드립니다. 기존에 알고 있는 지식은 자식 인스턴스 생성시 '부모의 필드 값과 가상 메서드 테이블 등의 메타 정보를 포함하는 하나의 인스턴스 생성' 이었습니다. 그런데 이번 강의 내용에선 '외부에서 볼때는 하나의 인스턴스를 생성하는 것 같지만 내부에서는 부모와 자식 모두 생성되고 공간도 구분' 이라고 하셨습니다. 그렇다면 이 문장을 ' 부모부터 자식 클래스까지의 모든 인스턴스를 생성 ' 이라고 봐야하나요? 아니면 '부모부터 자식까지의 모든 메타 정보를 포함하는 하나의 인스턴스 를 생성' 이라고 봐야하나요? 뒤에서 배울 super()를 통해 자식 인스턴스 생성시 부모 생성자를 필수로 호출하므로 '모든 인스턴스'를 생성하는 것도 말이 될 거 같지만 만약 모든 인스턴스를 메모리에 생성한다면 메모리가 비효율적으로 사용되는 것도 같아 이 부분이 좀 헷갈립니다.

  • java
  • 객체지향
TH Kwon 댓글 1 좋아요 0 조회수 452

db 시퀄라이즈 관계 설정 및 백엔드 요청 질문입니다!

해결됨

[리뉴얼] React로 NodeBird SNS 만들기

안녕하세요 제로초님, 강의 잘듣고잇습니다!!! db시퀄라이즈 관계 설정? 질문좀 드리려고요. 강의듣고 블로그를 만들어보려고 백/프론트 구상하고 있는데요, db table설정?을 어떻게 해야할지 헷갈려서요. 메인 페이지는 전체 post를 카테고리(메뉴)별로 나눠서 보여줍니다. 메뉴[ study / TIL / portfolio ]를 클릭하면 해당 categories로 저장한 게시글을 보여줍니다 (노란화살표) 포스트 작성할 때는 하나의 categories를 선택합니다. 각 게시글은 하나의 카테고리만 가집니다! 헷갈리는 부분은 메뉴탭을 눌러서 study / TIL 로 이동했을 때, 전체 post를 가져오는 게 아니라 해당 categories의 post만 가져오고 싶은데, db를 활용해야 하는건지, 백엔드에서 필터링 과정을 해야 하는건지, 헷갈립니다 이때 categories를 관계형 테이블?로 만들어서 해당 카테고리로 post를 가져올 수 있나요???? 백엔드가 전체 db에서 post를 findAll로 가져와, 카테고리로 필터링해서 프론트로 넘겨줘야 하나요? 서버에서 전체 post를 받아서 프론트에서 필터링해서 각 컴포넌트에서 사용해야 하나요?? 흠. 뭔가 여러 방법이 떠오르긴 하는데 아직 시도해보지는 않았고 ㅎㅎㅎ 효율적인 방법이 뭔지 알고싶어요!! 제로초님이라면 어떤 방법을 사용하시나요?

  • react
  • redux
  • node.js
  • express
  • next.js
나를응원해 댓글 1 좋아요 1 조회수 202

Next와 React-query의 prefetch에 대해

미해결

Next + React Query로 SNS 서비스 만들기

안녕하세요 ! Next14 버전과 tanstack-qeury를 이용해 프로젝트를 진행하던 도중 궁금한 점이 생겨 질문드립니다. Next의 서버 컴포넌트에서 data를 prefetching 하여 사용하려면 다음과 같은 단계를 밟아야 하는 것으로 알고 있습니다. 1. 서버 컴포넌트에서 queryClient.prefetchQuery를 사용해 데이터를 불러오고 이를 dehydrate하여 HydrationBoundary 내에 state로 넘겨준다. 2. 데이터를 사용하는 컴포넌트에서 useQuery로 동일한 데이터를 불러오면 해당 데이터는 prefetch 된 상태로 넘어와 이를 사용한다. 현재 이를 토대로 아래 예시코드와 같이 작성하여 사용중입니다. 이 때 하위 컴포넌트에서 prefetch한 데이터를 사용하려면 useQuery를 써야하기에, 'use client' 를 사용해야하고, 그렇게 되면 그 하위 컴포넌트도 전부 Client Boundary에 들어오게 되는 것으로 알고있는데, 그럼 "Next를 사용하며 얻을 수 있는 장점이 줄어들지 않나 ?" 라는 의문이 생겼습니다. 제가 사용법을 잘못 알고있다거나 Next의 개념에 대해 부족한걸까요 ? 또, HydrationBoundary로 감싸지 않고 queryClient.getQueryData를 이용해 직접 데이터를 가져와 이를 props로 전달해도 기능은 정상적으로 작동하는데, 이 둘의 차이점이 정확히 무엇인가요 ? // 서버 컴포넌트 import { HydrationBoundary, dehydrate, QueryClient, } from "@tanstack/react-query"; import { QUERY_KEY } from "@/constants"; import { requestGetPushAlarmList } from "@/apis/notification"; import NotificationClient from "./Client"; export default async function Page() { const queryClient = new QueryClient(); await queryClient.prefetchQuery({ queryKey: [QUERY_KEY.PUSH_LIST], queryFn: () => requestGetPushAlarmList({}), }); // const { rows: pushList } = queryClient.getQueryData([ // QUERY_KEY.PUSH_LIST, // ]) as unknown as Rows<PushAlarm>; 예시 2. getQueryData로 데이터에 접근 return ( <HydrationBoundary state={dehydrate(queryClient)}> <NotificationClient /> </HydrationBoundary> // <NotificationList pushList={pushList} /> 예시2. props로 직접 데이터 전달 ); } // 하위 컴포넌트 "use client"; import { useQuery } from "@tanstack/react-query"; import { requestGetPushAlarmList } from "@/apis/notification"; import { QUERY_KEY } from "@/constants"; import NotificationList from "./_components/NotificationList"; import ScreenBox from "@/components/ui/ScreenBox"; import Empty from "@/components/ui/Empty"; export default function NotificationClient() { const { data } = useQuery({ queryKey: [QUERY_KEY.PUSH_LIST], queryFn: () => requestGetPushAlarmList({}), select: (data) => data.rows, }); return ( <> {!data?.length ? ( <ScreenBox.CenterBody> <Empty message="알림이 없습니다." /> </ScreenBox.CenterBody> ) : ( <NotificationList pushList={data} /> )} </> ); }

  • next.js
  • react-query
이자이 댓글 2 좋아요 0 조회수 1624

ctrl + shift + enter 단축키 질문

미해결

김영한의 자바 입문 - 코드로 시작하는 자바 첫걸음

[질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예) [질문 내용] 비교 연산자 강의 8분 30초 경에 세미콜론이 없는 문장에서 커서가 괄호 안에 있는 경우 윈도우 환경 기준 ctrl + shift + enter 를 사용하면 세미콜론이 생기면서 커서가 문장 맨 뒤로 간다고 말씀해주셔서 동일하게 따라해봤는데 작동하지 않습니다. 단축키가 변한건가요? 한영키도 눌러봤습니다.

  • java
  • 인텔리제이
최용욱 댓글 2 좋아요 0 조회수 1234

서버 컴포넌트에서 Server Actions 사용하기

미해결

Next + React Query로 SNS 서비스 만들기

깃허브에 올려놓은 소스(next-app-router-z /ch3-1)을 다운받은후에 403 에러발생을 확인하기 위해서 아래의 주석을 해제했습니다. src/mocks/handlers.ts http.post('/api/users', async ({ request }) => { console.log('회원가입'); return HttpResponse.text(JSON.stringify('user_exists'), { status: 403, }) }) }), PostMan 에서 http://localhost:9090/api/users?id=js&password=pass&name=js7777 호출을 하면 status 값이 의도한 대로 403 Forbidden 이 출력이 됩니다. 그런데, 브라우저 개발자모드 Network 에서 보면 Status 값이 200 으로 출력됩니다. 서버에서는 분명 403 상태로 보냈고, PostMan에서도 403으로 상태값이 넘어오는데, 왜? 개발자 도구(Network)에서만 상태값이 200으로 출력되는지 모르겠습니다.

  • react
  • next.js
  • react-query
  • next-auth
  • msw
박정식 댓글 2 좋아요 0 조회수 408

추천탭 게시글작성 오류

미해결

Next + React Query로 SNS 서비스 만들기

추천탭에서 게시글을 작성하면 새로고침 시 사라져버리고 추천탭에서 게시한 게시글이 "팔로우 중" 탭에서 존재하여 좋아요 버튼을 클릭하면 새로고침 시 다시 추천탭에도 해당 게시글이 나타납니다. 도무지 뭐가문제인지 모르겠네요ㅠㅠ "use client" import { MouseEventHandler } from 'react'; import style from './post.module.css'; import cx from 'classnames'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { Post } from '@/model/Post'; type Props = { white? : boolean; postId: number; } export default function ActionButtons({white, postId}: Props) { const queryClient = useQueryClient(); const commented = true; const reposted = true; const liked = false; const heart = useMutation({ mutationFn: () => { return fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/posts/${postId}/heart`, { method: 'post', credentials: 'include', }) }, // 클릭한 하트 상태를 실시간으로 true로 만들어줌 // post에서 검색결과,추천,팔로잉,답글 등등 쿼리키가 다양한대 어떤 쿼리키인지 무슨상황인지 알 수가 없다. // 그래서 전부 다 해줘야 한다. onMutate() { const queryCache = queryClient.getQueryCache(); const queryKeys = queryCache.getAll().map(cache => cache.queryKey); console.log('queryKeys',queryKeys); queryKeys.forEach((querykey) => { if(querykey[0] === 'posts') { const value:Post | Post[] | undefined = queryClient.getQueryData(querykey); // 게시글 console.log(value) // 싱글포스트 일 수도 있기때문에 조건문 걸어줌. if(Array.isArray(value)){ const index = value.findIndex((v) => postId == v.postId); // 찾고자 하는 게시글이 있는지 확인 if(index > -1) { const shallow = [...value]; shallow[index] = { ...shallow[index], } // 옅은 복사해준것을 쿼리에 전송 queryClient.setQueryData(querykey, shallow); } }else { // 싱글 포스트인 경우 } } }); }, onError() { }, onSettled() { } }) // 댓글 const onClickComment = () => {} // 리트윗 const onClickRepost = () => { } // 좋아요 const onClickHeart:MouseEventHandler<HTMLButtonElement> = (e) => { e.stopPropagation(); if(liked){ // unheart.mutate(); }else{ heart.mutate(); } } return ( <div className={style.actionButtons}> <div className={cx(style.commentButton, { [style.commented]: commented }, white && style.white)}> <button onClick={onClickComment}> <svg width={24} viewBox="0 0 24 24" aria-hidden="true"> <g> <path d="M1.751 10c0-4.42 3.584-8 8.005-8h4.366c4.49 0 8.129 3.64 8.129 8.13 0 2.96-1.607 5.68-4.196 7.11l-8.054 4.46v-3.69h-.067c-4.49.1-8.183-3.51-8.183-8.01zm8.005-6c-3.317 0-6.005 2.69-6.005 6 0 3.37 2.77 6.08 6.138 6.01l.351-.01h1.761v2.3l5.087-2.81c1.951-1.08 3.163-3.13 3.163-5.36 0-3.39-2.744-6.13-6.129-6.13H9.756z"></path> </g> </svg> </button> <div className={style.count}>{1 || ''}</div> </div> <div className={cx(style.repostButton, reposted && style.reposted, white && style.white)}> <button onClick={onClickRepost}> <svg width={24} viewBox="0 0 24 24" aria-hidden="true"> <g> <path d="M4.5 3.88l4.432 4.14-1.364 1.46L5.5 7.55V16c0 1.1.896 2 2 2H13v2H7.5c-2.209 0-4-1.79-4-4V7.55L1.432 9.48.068 8.02 4.5 3.88zM16.5 6H11V4h5.5c2.209 0 4 1.79 4 4v8.45l2.068-1.93 1.364 1.46-4.432 4.14-4.432-4.14 1.364-1.46 2.068 1.93V8c0-1.1-.896-2-2-2z"></path> </g> </svg> </button> <div className={style.count}>{1 || ''}</div> </div> <div className={cx([style.heartButton, liked && style.liked, white && style.white])}> <button onClick={onClickHeart}> <svg width={24} viewBox="0 0 24 24" aria-hidden="true"> <g> <path d="M16.697 5.5c-1.222-.06-2.679.51-3.89 2.16l-.805 1.09-.806-1.09C9.984 6.01 8.526 5.44 7.304 5.5c-1.243.07-2.349.78-2.91 1.91-.552 1.12-.633 2.78.479 4.82 1.074 1.97 3.257 4.27 7.129 6.61 3.87-2.34 6.052-4.64 7.126-6.61 1.111-2.04 1.03-3.7.477-4.82-.561-1.13-1.666-1.84-2.908-1.91zm4.187 7.69c-1.351 2.48-4.001 5.12-8.379 7.67l-.503.3-.504-.3c-4.379-2.55-7.029-5.19-8.382-7.67-1.36-2.5-1.41-4.86-.514-6.67.887-1.79 2.647-2.91 4.601-3.01 1.651-.09 3.368.56 4.798 2.01 1.429-1.45 3.146-2.1 4.796-2.01 1.954.1 3.714 1.22 4.601 3.01.896 1.81.846 4.17-.514 6.67z"></path> </g> </svg> </button> <div className={style.count}>{0 || ''}</div> </div> </div> ) }

  • react
  • next.js
  • react-query
  • next-auth
  • msw
Jinhye Kim 댓글 3 좋아요 0 조회수 340

도메인 연결 후 게시글 작성..

미해결

[리뉴얼] React로 NodeBird SNS 만들기

안녕하세요 도메인 연결 후 로그인과 로그아웃이 잘 되고, 새로고침 시에도 유지가 되는데요~ 게시글이 작성은 안됩니다 ㅠㅠ 회원가입은 되구요! 이 다음 강의 S3를 연결하면 게시글이 작성이 되는게 맞을까요? 아니면 현재 오류가 있는건가여..

  • react
  • redux
  • node.js
  • express
  • next.js
hyuri 댓글 4 좋아요 0 조회수 377

웹사이트에서 바로 한글로 번역되는거 어떤 프로그램쓰시는건가요?

해결됨

기초부터 배우는 Next YTMusic 클론 코딩 (with next.js 14, UI 마스터)

안녕하세요. 처음 15초쯤에 nextjs소개하면서 나오는 번역프로그램은 어떤걸 쓰시는건가요? 편리해보여서요~

  • react
  • 인터랙티브-웹
  • 클론코딩
  • next.js
  • tailwind-css
  • zustand
김진우 댓글 1 좋아요 1 조회수 350

next14 app router 배포 nginx index.html 물리기

해결됨

Next + React Query로 SNS 서비스 만들기

프로젝트를 하다가 next를 배포해서 nginx에 물리려고 했는데 index html 을 찾아서 물려줘야 된다고 해서 강의에서 나온 nextConfig 에서 output:'export 를 해주면 index html 이 뜨는건 확인을 하였습니다. 근데 문제는 제가 서버에서의 기능을 많이 썼기 때문에 정적으로 배포가 어려움이 있었습니다. 다른 방법이 있을까요..?

  • next.js
  • 배포
  • nginx
sanguu516 댓글 1 좋아요 0 조회수 776

Next에서 자동 로그인 구현

미해결

안녕하세요 😃 현재 Next.js 사용해 프로젝트 진행중인데 한번 로그인하면 웹에 재접속 시 자동으로 로그인 처리되도록 하고 싶습니다. 현업에서는 어떤 방식으로 진행하는지 궁금합니다! 답변 주시면 정말 정말 감사합니다!!

  • next.js
  • 프론트엔드
  • 자동로그인
  • jwt
  • 토큰관리
  • 현업
  • 로그인
  • 구현
  • 질문
  • 도와주세요
이하은 댓글 1 좋아요 0 조회수 600

리액트쿼리 prefetch 시에 QueryClient 생성에 대해 질문드립니다.

해결됨

Next + React Query로 SNS 서비스 만들기

csr 에서는 useQueryClient로 생성된 QueryClient를 가져와 사용하는 반면에 ssr 에서 prefetch 할 때에는 QueryClient 를 새로 생성해서 사용하시더라구요. 그럼 ssr에서 생긴 QueryClient csr에서 생긴 QueryClient 두개가 존재하게 되는데, 리액트쿼리가 hydrate 하는 과정에서 알아서 합쳐주는 건지 그 원리가 궁금합니다. 2. prefetch를 할 때마다 QueryClient를 새로 생성해야 하는지 아니면 ssr에서 사용할 QueryClient를 하나 생성해서 공유하는 방식으로 사용해야 하는 것인지, 또 공유해서 사용한다면 예제가 있을까요? 만약 prefetch 할 때마다 QueryClient를 새로 생성해야 한다면 성능상에 문제는 없을까요? prefetch를 난발하는 것을 멈추고 조심히 사용해야 할까요? 강의 덕분에 많이 배웠습니다. 좋은 강의 감사합니다.

  • react
  • next.js
  • react-query
  • next-auth
  • msw
CARL 댓글 1 좋아요 1 조회수 304

H2 초반 연결문제

미해결

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] 여기에 질문 내용을 남겨주세요. 연견을 누르면 아래와같은 오류가 나옵니다

  • java
  • spring
  • mvc
  • spring-boot
백종원 댓글 2 좋아요 0 조회수 584

String str = "Hello, Java! Welcome to Java";과 String str1 = str.concat("!!!");의 객체값 비교

미해결

김영한의 실전 자바 - 중급 1편

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. package lang.String.method; public class StringChangeMain1 { public static void main(String[] args) { String str = "Hello, Java! Welcome to Java"; //x001 Object object = new Object(); String str1 = str.concat("!!!"); //x002 System.out.println(str); System.out.println(str1); str = object.toString(); str1 = object.toString(); System.out.println(str1.equals(str)); System.out.println(str1==str); System.out.println(str); System.out.println(str1); } } 결과로 Hello, Java! Welcome to Java Hello, Java! Welcome to Java!!! true false java.lang.Object@b4c966a java.lang.Object@b4c966a 가 나오는데, 배운 내용대로라면 str1은 str과 다른 새로운 객체값니간, str이랑 다른 객체값이 나올거라 생각했는데, str과 같은 객체값이 출력이 되어서 질문드립니다. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] 여기에 질문 내용을 남겨주세요.

  • java
  • 객체지향
김동현 댓글 1 좋아요 0 조회수 315

Enum 내부에 인스턴스 생성 불가

해결됨

김영한의 실전 자바 - 중급 1편

========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예) [질문 내용] Enum 타입이 생성자를 private로 하여 외부 생성을 막은 클래스와 거의 동일하다고 하셨는데 그 부분에 이해가 안되는 부분이 생겨 질문 드립나다. public class Grade { public static final Grade BASIC = new Grade(); public static final Grade GOLD = new Grade(); public static final Grade DIAMOND = new Grade(); private Grade() { } //자기 자신의 클래스에서 새로운 인스턴스 생성 (가능) public static Grade generate() { return new Grade(); } } 위의 코드처럼 class로 만든 경우 private으로 외부 인스턴스 생성을 막아도 자신 클래스 내부에서는 새로운 인스턴스 생성하는 코드에 빨간줄이 나타나지 않았습니다. public enum Grade { BASIC, GOLD, DIAMOND //자기 자신의 클래스에서 새로운 인스턴스 생성 (불가능) public static Grade generate() { return new Grade(); } 강의에서 위의 코드와 거의 동일한 코드라고 해주셨던 Enum타입으로 클래스를 만들경우는 아래의 generate 메서드에서 새로운 인스턴스를 만들 수 없다며 빨간줄이 생깁니다. 위의 코드와 아래 코드의 어떤 부분에서 이러한 차이가 생기는지 궁금합니다. 단순히 private으로 외부 인스턴스 생성만 막은 경우라면 자기 자신 안에서는 인스턴스 생성이 가능해야 할 것 같은데 어째서 Enum에서는 자기 자신 내부에서 생성이 불가능한 건가요? private으로 외부 생성을 막더라도 저런식의 generate 메서드를 만들면 외부에서 인스턴스 생성이 가능해 지지 않을까 하는 생각에 만들다가 이런 차이를 발견해 질문 드립니다.

  • java
  • 객체지향
오스즈 댓글 2 좋아요 0 조회수 439

백틱 적용이 안 돼요..

해결됨

[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스

위 화면과 같이 백틱으로 감싸서 사용할 때, 적용이 안 되는데, 서칭을 해보면 Browser 호환 문제라는 말들이 있습니다. 영상에서와 같은 Chrome을 통한 Console창에서 실습 중인데 무엇이 문제일까요?

  • react
  • node.js
  • seo
  • graphql
  • next.js
gun5873 댓글 2 좋아요 0 조회수 647

서버 실행 실패

미해결

자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]

> Task :LibraryAppApplication.main() FAILED . ____ _ /\\ / ___'_ __ ( _)_ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.7.6) 2024-04-04 17:09:40.815 INFO 12468 --- [ main] c.g.libraryapp.LibraryAppApplication : Starting LibraryAppApplication using Java 17.0.9 on KONG with PID 12468 (C:\Project\project\library-app\build\classes\java\main started by jinju in C:\Project\project\library-app) 2024-04-04 17:09:40.819 INFO 12468 --- [ main] c.g.libraryapp.LibraryAppApplication : No active profile set, falling back to 1 default profile: "default" 2024-04-04 17:09:41.422 INFO 12468 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2024-04-04 17:09:41.474 WARN 12468 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'userRepository' defined in com.group.libraryapp.domain.user.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot register bean definition [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in com.group.libraryapp.domain.user.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration] for bean 'userRepository': There is already [Root bean: class [null]; scope=; abstract=false; lazyInit=null; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=userConfiguration; factoryMethodName=userRepository; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/group/libraryapp/config/UserConfiguration.class]] bound. 2024-04-04 17:09:41.505 INFO 12468 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2024-04-04 17:09:41.521 ERROR 12468 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: The bean 'userRepository', defined in com.group.libraryapp.domain.user.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration, could not be registered. A bean with that name has already been defined in class path resource [com/group/libraryapp/config/UserConfiguration.class] and overriding is disabled. Action: Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true Execution failed for task ':LibraryAppApplication.main()'. > Process 'command 'C:/Program Files/Java/jdk-17/bin/java.exe'' finished with non-zero exit value 1 찾아본 결과 이 문제는 Spring 애플리케이션의 빈(bean) 정의 중에 중복이 발생하여 발생한 것으로 보입니다. 에러 메시지에 따르면 userRepository 빈이 이미 UserConfiguration 클래스에서 정의되어 있으며, 또한 Spring Data JPA가 자체적으로 해당 빈을 생성하려고 시도하고 있는 것으로 보인다고 합니다. 혹시 UserConfiguration 부분에 변경이 적용 안된게 있어서 그런걸까요? 저 bean 부분을 지워도 .UserServiceV1 때문에 컴파일 에러가 발생하더라구요,.,..

  • java
  • spring
  • aws
  • mysql
  • spring-boot
  • jpa
댓글 3 좋아요 0 조회수 628

강좌 보면서 개인프로젝트에 적용중입니다. build시 "Arrow" cannot be used as a JSX component 에러가 납니다.

해결됨

Next + React Query로 SNS 서비스 만들기

./src/_components/Carousel.tsx 110:6 Warning: React Hook useEffect has a missing dependency: 'nextFn'. Either include it or remove the dependency array. react-hooks/exhaustive-deps (....lint warning문구 생략) info - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules Linting and checking validity of types .Failed to compile. ./src/_components/Carousel.tsx:137:12 Type error: 'Arrow' cannot be used as a JSX component. Its type 'FC<PropsWithChildren<ArrowProps>>' is not a valid JSX element type. Type 'FunctionComponent<PropsWithChildren<ArrowProps>>' is not assignable to type '(props: any, deprecatedLegacyContext?: any) => ReactNode'. Type 'ReactElement<any, any> | null' is not assignable to type 'ReactNode'. Type 'ReactElement<any, any>' is not assignable to type 'ReactNode'. Property 'children' is missing in type 'ReactElement<any, any>' but required in type 'ReactPortal'. 135 | className={`h-full w-full ${inArrow ? 'absolute' : ''} max-w-full`}> 136 | {!!showNavButton && ( > 137 | <Arrow | ^ 138 | direction="left" 139 | executeFn={prevFn} 140 | inArrow={inArrow} error Command failed with exit code 1. 'use client'; import { FC, PropsWithChildren, useEffect, useState } from 'react'; interface ArrowProps { direction: 'left' | 'right'; executeFn: () => void; inArrow?: boolean; hoverStyle?: string; } const Arrow: FC<PropsWithChildren<ArrowProps>> = ({ direction, executeFn, inArrow, hoverStyle, children, ...props }) => { const [hoverColor, setHoverColor] = useState(hoverStyle || undefined); useEffect(() => { hoverStyle && setHoverColor(`hover:${hoverStyle}`); }, [hoverStyle]); const returnString = direction === 'left' ? '<' : '>'; return ( <div onClick={executeFn} className={`${inArrow ? 'absolute z-50' : ''} ${direction === 'left' ? 'left-0 top-0 rounded-l-lg' : 'right-0 top-0 rounded-r-lg'} center-vertical flex h-full w-[30px] cursor-pointer text-[30px] ${hoverColor && hoverColor}`} {...props}> {returnString} {children} </div> ); }; export default Arrow; next build를 했을때 해당 에러가 Arrow컴포넌트에서 발생하였습니다. Arrow컴포넌트에서 제가 정의한 FC<PropsWithChildren<ArrowProps>>타입이 유효한 JSX element type이 아니라는 메시지 인거 같습니다. 이 에러가 나는 이유가 유효한 JSX엘리먼트가 아니어서 일것같아서 return 하는 jsx문법에 오류가 있는지 확인하려 div 겉에도 fragment로 감싼다거나 returnString을 해주는 중괄호 부분도 fragment로 감싸거나 children도 감싸보았습니다. 그러나 똑같은 에러가 발생하고 있는 상황입니다. const returnString = direction === 'left' ? '<' : '>'; 혹시 위의 코드가 문제가 발생할까 싶어서 SVG파일을 만들어 조건에따라 왼쪽 오른쪽 SVG 파일 컴포넌트를 return 문 안에서 렌더링 해주었는데 여기서도 동일한 에러가 발생하였습니다. Type error: 'LeftSvg' cannot be used as a JSX component. Its type '({ className, width, height, onClick, cyAttribute, }: { className?: string | undefined; width?: number | undefined; height?: number | undefined; onClick?: (() => void) | undefined; cyAttribute?: string | undefined; }) => JSX.Element' is not a valid JSX element type. Type '({ className, width, height, onClick, cyAttribute, }: { className?: string | undefined; width?: number | undefined; height?: number | undefined; onClick?: (() => void) | undefined; cyAttribute?: string | undefined; }) => JSX.Element' is not assignable to type '(props: any, deprecatedLegacyContext?: any) => ReactNode'. Type 'Element' is not assignable to type 'ReactNode'. Property 'children' is missing in type 'Element' but required in type 'ReactPortal'. 24 | }, [hoverStyle]); 25 | > 26 | const returnString = direction === 'left' ? <LeftSvg /> : <RightSvg />; | ^ 27 | 28 | return ( 29 | <div error Command failed with exit code 1. 참고로 'DatePicker' cannot be used as a JSX component. Its instance type 'ReactDatePicker<undefined, undefined>' is not a valid JSX element. 이런 에러가 타입에러 발견 된 적이 있어서 package.json파일에 "resolutions": { "@types/react": "^18.0.0" }, resolutions로 버전을 위와 같이 맞춰주어서 해결한 적이 있습니다.

  • react
  • next.js
  • react-query
  • next-auth
  • msw
tittogam 댓글 2 좋아요 0 조회수 405

인기 태그

인프런 TOP Writers

주간 인기글