nextLine() 동작 수정
두 번째 코드 예제에서 nextLine()을 사용할 때 발생하는 문제는 nextInt()의 조합에서 비롯됩니다. 및 nextLine().
문제 nextInt()
nextLine()은 공백과 Enter 키를 누르기 전에 입력한 문자를 포함하여 전체 줄을 사용합니다. 그러나 nextInt()는 숫자 값만 사용합니다. 숫자 뒤에 숫자가 아닌 문자나 공백이 있으면 nextLine()이 이를 읽으려고 시도하여 예상치 못한 동작이 발생합니다.
해결책: 남은 줄바꿈 사용
nextLine()이 의도한 대로 전체 줄을 읽으려면 각 nextInt() 뒤에 nextLine() 호출을 추가하여 줄의 잔여 문자를 모두 사용할 수 있습니다. 이렇게 하면 nextLine()을 사용하여 문장을 읽을 때 완전한 줄을 받게 됩니다.
수정 예:
// Example #2 (Corrected) import java.util.Scanner; class Test { public void menu() { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("\nMenu Options\n"); System.out.println("(1) - do this"); System.out.println("(2) - quit"); System.out.print("Please enter your selection:\t"); int selection = scanner.nextInt(); scanner.nextLine(); // Consume remaining newline if (selection == 1) { System.out.print("Enter a sentence:\t"); String sentence = scanner.nextLine(); System.out.print("Enter an index:\t"); int index = scanner.nextInt(); System.out.println("\nYour sentence:\t" + sentence); System.out.println("Your index:\t" + index); } else if (selection == 2) { break; } } } }
위 내용은 `nextInt()` 이후 `nextLine()`이 오작동하는 이유는 무엇이며 어떻게 수정할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

javaachievesplatformincendenceThoughthehoughthejavavirtualmachine (JVM), hittoutModification.thejvmcompileSjavacodeIntOplatform-independentByTecode, whatitTengretsAndexeSontheSpecoS, toplacetSonthecificos, toacketSecificos

javaispowerfuldueToitsplatformincendence, 객체 지향적, RichandardLibrary, PerformanceCapabilities 및 StrongSecurityFeatures.1) Platform IndependenceAllowsApplicationStorunannyDevicesUpportingjava.2) 대상 지향적 프로그래밍 프로모션 Modulara

최고 Java 기능에는 다음이 포함됩니다. 1) 객체 지향 프로그래밍, 다형성 지원, 코드 유연성 및 유지 관리 가능성 향상; 2) 예외 처리 메커니즘, 시도 캐치-패치 블록을 통한 코드 견고성 향상; 3) 쓰레기 수집, 메모리 관리 단순화; 4) 제네릭, 유형 안전 강화; 5) 코드를보다 간결하고 표현력있게 만들기위한 AMBDA 표현 및 기능 프로그래밍; 6) 최적화 된 데이터 구조 및 알고리즘을 제공하는 풍부한 표준 라이브러리.

javaisnotentirelyplatformindent의 의존적 duetojvmvariationsandnativecodeintegration

TheJavavirtualMachine (JVM) isanabstractcomputingmachinecrucialforjavaexecutionasitsjavabytecode, "writeonce, runanywhere"기능을 가능하게합니다

javaremainsagoodlugageedueToitscontinuousevolutionandrobustecosystem.1) lambdaexpressionsenhancececeadeabilitys.2) Streamsallowforefficileddataprocessing, 특히 플레어로드 라트 웨이션

javaisgreatduetoitsplatform incendence, robustoopsupport, extensibraries 및 strongcommunity.1) platforminceptenceviajvmallowscodetorunonvariousplatforms.2) oopeatures inncapsulation, Nheritance, and Polymorphismenblularandscode.3)

Java의 5 가지 주요 특징은 다형성, Lambda Expressions, Streamsapi, 제네릭 및 예외 처리입니다. 1. 다형성을 사용하면 다른 클래스의 물체가 공통 기본 클래스의 물체로 사용될 수 있습니다. 2. Lambda 표현식은 코드를보다 간결하게 만듭니다. 특히 컬렉션 및 스트림을 처리하는 데 적합합니다. 3.StreamSapi는 대규모 데이터 세트를 효율적으로 처리하고 선언적 작업을 지원합니다. 4. 제네릭은 유형 안전 및 재사용 성을 제공하며 편집 중에 유형 오류가 잡히립니다. 5. 예외 처리는 오류를 우아하게 처리하고 신뢰할 수있는 소프트웨어를 작성하는 데 도움이됩니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

WebStorm Mac 버전
유용한 JavaScript 개발 도구

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음