programing

Java에서 표준 입력에서 정수 값을 읽는 방법

randomtip 2022. 11. 2. 23:23
반응형

Java에서 표준 입력에서 정수 값을 읽는 방법

Java에서 정수 변수를 읽을 때 사용할 수 있는 클래스는 무엇입니까?

사용할 수 있습니다.java.util.Scanner(API):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

정규 표현 등으로 입력을 토큰화할 수도 있습니다.API에는 예가 있고 이 사이트에는 많은 예가 있습니다(예: 잘못된 유형을 입력했을 때 스캐너가 예외를 발생시키지 않도록 하려면 어떻게 해야 합니까?

Java 6을 사용하는 경우 다음 oneliner를 사용하여 콘솔에서 정수를 읽을 수 있습니다.

int n = Integer.parseInt(System.console().readLine());

여기 표준 입력에서 정수 값을 읽기 위한 두 가지 예를 제공합니다.

예 1

import java.util.Scanner;
public class Maxof2
{ 
  public static void main(String args[])
  {
       //taking value as command line argument.
        Scanner in = new Scanner(System.in); 
       System.out.printf("Enter i Value:  ");
       int i = in.nextInt();
       System.out.printf("Enter j Value:  ");
       int j = in.nextInt();
       if(i > j)
           System.out.println(i+"i is greater than "+j);
       else
           System.out.println(j+" is greater than "+i);
   }
 }

예 2

public class ReadandWritewhateveryoutype
{ 
  public static void main(String args[]) throws java.lang.Exception
  {
System.out.printf("This Program is used to Read and Write what ever you type \nType  quit  to Exit at any Moment\n\n");
    java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
     String hi;
     while (!(hi=r.readLine()).startsWith("quit"))System.out.printf("\nYou have typed: %s \n",hi);
     }
 }

저는 첫 번째 예를 선호합니다. 쉽고 꽤 이해하기 쉽기 때문입니다.
JAVA 프로그램은 다음 웹사이트에서 컴파일 및 실행할 수 있습니다.http://ideone.com

다음 항목을 확인합니다.

public static void main(String[] args) {
    String input = null;
    int number = 0;
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        input = bufferedReader.readLine();
        number = Integer.parseInt(input);
    } catch (NumberFormatException ex) {
       System.out.println("Not a number !");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

위의 두 번째 답변이 가장 간단합니다.

int n = Integer.parseInt(System.console().readLine());

질문은 "표준 입력에서 읽는 방법"입니다.

콘솔은 일반적으로 키보드와 디스플레이에 연결된 장치이며, 이 장치에서 프로그램을 시작합니다.

Java VM이 명령줄에서 시작되지 않거나 표준 입력 및 출력 스트림이 리디렉션되는 등 사용 가능한 Java 콘솔 장치가 없는지 테스트할 수 있습니다.

Console cons;
if ((cons = System.console()) == null) {
    System.err.println("Unable to obtain console");
    ...
}

콘솔을 사용하는 것은 간단한 숫자 입력 방법입니다.parseInt()/Double() 등과 조합됩니다.

s = cons.readLine("Enter a int: ");
int i = Integer.parseInt(s);    

s = cons.readLine("Enter a double: ");
double d = Double.parseDouble(s);

다음 항목을 체크합니다.

import java.io.*;
public class UserInputInteger
{
        public static void main(String args[])throws IOException
        {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        int number;
                System.out.println("Enter the number");
                number = Integer.parseInt(in.readLine());
    }
}

이로 인해 골치가 아프기 때문에 2014년 12월에 사용자가 사용할 수 있는 가장 일반적인 하드웨어 및 소프트웨어 도구를 사용하여 실행할 수 있는 솔루션을 업데이트했습니다.JDK/SDK/JRE/Netbeans 및 그 이후의 클래스, 템플릿 라이브러리 컴파일러, 에디터 및 디버거는 무료입니다.

이 프로그램은 Java v8 u25에서 테스트되었습니다.작성 및 구축은 다음과 같이 이루어집니다.
Netbeans IDE 8.0.2, JDK 1.8, OS는 win8.1(애플로지), 브라우저는 Chrome(더블애플로지)입니다.이는 UNIX-cmd-line OG가 최신 GUI-Web 기반 IDE를 제로 코스트에 처리하는 것을 지원하기 위한 것입니다.정보(및 IDE)는 항상 무료입니다.By Tapper7.모두를 위해서.

코드 블록:

    package modchk; //Netbeans requirement.
    import java.util.Scanner;
    //import java.io.*; is not needed Netbeans automatically includes it.           
    public class Modchk {
        public static void main(String[] args){
            int input1;
            int input2;

            //Explicity define the purpose of the .exe to user:
            System.out.println("Modchk by Tapper7. Tests IOStream and basic bool modulo fxn.\n"
            + "Commented and coded for C/C++ programmers new to Java\n");

            //create an object that reads integers:
            Scanner Cin = new Scanner(System.in); 

            //the following will throw() if you don't do you what it tells you or if 
            //int entered == ArrayIndex-out-of-bounds for your system. +-~2.1e9
            System.out.println("Enter an integer wiseguy: ");
            input1 = Cin.nextInt(); //this command emulates "cin >> input1;"

            //I test like Ernie Banks played hardball: "Let's play two!"
            System.out.println("Enter another integer...anyday now: ");
            input2 = Cin.nextInt(); 

            //debug the scanner and istream:
            System.out.println("the 1st N entered by the user was " + input1);
            System.out.println("the 2nd N entered by the user was " + input2);

            //"do maths" on vars to make sure they are of use to me:
            System.out.println("modchk for " + input1);
            if(2 % input1 == 0){
                System.out.print(input1 + " is even\n"); //<---same output effect as *.println
                }else{
                System.out.println(input1 + " is odd");
            }//endif input1

            //one mo' 'gain (as in istream dbg chk above)
            System.out.println("modchk for " + input2);
            if(2 % input2 == 0){
                System.out.print(input2 + " is even\n");
                }else{
                System.out.println(input2 + " is odd");
            }//endif input2
        }//end main
    }//end Modchk

언급URL : https://stackoverflow.com/questions/2506077/how-to-read-integer-value-from-the-standard-input-in-java

반응형