logo

Java에서 문자열 입력을 받는 방법

자바 nextLine() 메소드

그만큼 다음라인() Scanner 클래스의 메소드는 사용자로부터 문자열을 가져오는 데 사용됩니다. 이는 다음에서 정의됩니다. java.util.스캐너 수업. nextLine() 메서드는 줄 끝까지 텍스트를 읽습니다. 해당 줄을 읽은 후 커서를 다음 줄로 이동합니다.

메소드의 서명은 다음과 같습니다.

 public String nextLine() 

이 메서드는 건너뛴 줄을 반환합니다. 어떤 매개변수도 허용하지 않습니다. 라인을 찾지 못하면 던집니다. NoSuchElementException . 그것도 던진다 IllegalStateException 스캐너가 닫혀 있는 경우.

nextLine() 메소드의 예

 import java.util.*; class UserInputDemo1 { public static void main(String[] args) { Scanner sc= new Scanner(System.in); //System.in is a standard input stream System.out.print('Enter a string: '); String str= sc.nextLine(); //reads string System.out.print('You have entered: '+str); } } 

산출:

Java에서 문자열 입력을 받는 방법

자바 next() 메소드

자바 다음() 메소드는 공간 ID가 발견되기 전에 입력을 읽을 수 있습니다. 공백으로 구분된 두 단어를 읽을 수 없습니다. 입력을 읽은 후 같은 줄에 커서를 유지합니다.

메소드의 서명은 다음과 같습니다.

 public String next() 

이 메서드는 이 스캐너에서 다음 완전한 토큰을 반환합니다. 어떤 매개변수도 허용하지 않습니다. 그것은 던진다 NoSuchElementException 더 이상 토큰을 사용할 수 없는 경우. 그것도 던진다 IllegalStateException 스캐너가 닫혀 있는 경우.

next() 메소드의 예

 import java.util.*; class UserInputDemo2 { public static void main(String[] args) { Scanner sc= new Scanner(System.in); //System.in is a standard input stream System.out.print('Enter a string: '); String str= sc.next(); //reads string before the space System.out.print('You have entered: '+str); } } 

산출:

Java에서 문자열 입력을 받는 방법

Java 뒤에 쓰는 모든 내용은 메서드에 의해 건너뛰고 Java라는 단어만 읽는다는 것을 알 수 있습니다.