난 내가 일할 수 없다고 하지만 이해했소 계산기에는 만들어 보았습니다. # 39 를 getuser input_ _how, don& 수 있을지 알 수 없다.
사용자 입력 자바 가상 머신 (jvm) 에 어떻게 해야 할까요?
가장 간단한 방법 중 하나를 사용할 수 있는 '스캐너' 로케이터로 다음과 같습니다.
import java.util.Scanner;
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();
요구 사항을 토대로 다음 옵션을 사용할 수 있습니다.
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
import java.io.BufferedReader;
import java.io.InputStreamReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);
import java.io.DataInputStream;
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
'클래스' 에서 '방법' 이 readLine 다탱푸트스트림 deprecated 왔다. 이전 구체화하십시오 값을 얻을 수 있는 솔루션 (부퍼드레이더 콩지름에
import java.io.Console;
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
분명히, 이 방법은 제대로 작동하지 않는 일부 ide.
['부퍼드레이더'] getuser 입력입니다 사용할 수 있습니다 (http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html).
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.println("Enter your Account number: ");
accStr = br.readLine();
'그러니' 아치스트 값을 저장하는 것 '이' 문자열 구문 분석 충족되었으며 'int' 를 사용하여 ['안테거스파르세인트'] (http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html # parseInt-java.lang.String-).
int accInt = Integer.parseInt(accStr);
하나님께용서를 사용자 또는 두 개의 숫자를 입력할 수 있고, 곱셈, 나눗셈 및 인쇄인쇄 subtract 또는 추가할 수 있는 수치가 대한 사용자 투입물 비헤이비어를 마찬가지로 한 계산기에는.
따라서 스캐너 클래스용 합니다. '와' 가져오기의 코드에서 제바스티레비스카너 를 사용해야 합니다.
Scanner input = new Scanner(System.in);
입력 변수 이름을.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
s = input.next(); // getting a String value
System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer
System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double
어떻게 이 다르다. '린퍼t.네스트 (),', 'i = 린퍼t.네스틴트 (),', '영업사원이에요 = 린퍼t.네스트도이블레 ();
같은 길을 따라 문자열으로 따르면, int 및 더블 t forget 가져오기의 기술서임을 Don& 미삭. # 39, 맨 위에 코드에.
자세한 내용은 블로그 포스트 [" 점점 사용자 Inputs" 클래스, 스캐너,] (http://javalearnsimply.weebly.com/5/post/2014/02/scanner-class-and-getting-user-inputs.html).
'최고의 두 가지 부퍼드레이더' 와 '스캐너'.
가장 널리 사용되는 방식은 스캐너 '와' 때문에 간편하고 손쉽게 구현할 수 있을 뿐만 아니라 개인적으로 선호하는 등 강력한 유틸리티에는 텍스트를 로 원시 데이터 분석할 수 있다.
데이터 블록의 부페레딘푸트스트림 싱글바이트 아닌 한 번에 약 판독값
읽을 수 있는 자, 챨 어레이에는 및 방향선
빠른 성능을
경우 많은 양의 데이터를 입력 부퍼드레이더 수 있습니다 '-' 으로 거듭날 수 있도록 최선을 다하겠습니다
Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name"); // prompt user
name = scanner.next(); // get user input
(자세한 대한 정보를 '부퍼드레이더' 참조 사용할 수 있는 방법을 부퍼드레이더 를 판독값 줄의 자)
import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class
public class RunScanner {
// main method which will run your program
public static void main(String args[]) {
// create your new scanner
// Note: since scanner is opened to "System.in" closing it will close "System.in".
// Do not close scanner until you no longer want to use it at all.
Scanner scanner = new Scanner(System.in);
// PROMPT THE USER
// Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
System.out.println("Please enter a number");
// use "try" to catch invalid inputs
try {
// get integer with "nextInt()"
int n = scanner.nextInt();
System.out.println("Please enter a decimal"); // PROMPT
// get decimal with "nextFloat()"
float f = scanner.nextFloat();
System.out.println("Please enter a word"); // PROMPT
// get single word with "next()"
String s = scanner.next();
// ---- Note: Scanner.nextInt() does not consume a nextLine character /n
// ---- In order to read a new line we first need to clear the current nextLine by reading it:
scanner.nextLine();
// ----
System.out.println("Please enter a line"); // PROMPT
// get line with "nextLine()"
String l = scanner.nextLine();
// do something with the input
System.out.println("The number entered was: " + n);
System.out.println("The decimal entered was: " + f);
System.out.println("The word entered was: " + s);
System.out.println("The line entered was: " + l);
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input entered. Please enter the specified input");
}
scanner.close(); // close the scanner so it doesn't leak
}
}
<, sup>, 참고: 콘솔 등 다른 클래스 ',' 도 '와' 다탱푸트스트림 실용적인 alternatives.< /sup>.
',' 같은 강력한 기능을 보유하고 있어 일부 콘솔입니다 sup> <, 그러나 모든 IDE& 비밀번호란 읽을 수 있는 기능을 사용할 수 없습니다 # 39, s (Eclipse 등). 이런 이유 때문에 Eclipse 실행하는 응용 프로그램이 아닌 백그라운드 프로세스로 최상위 프로세스와 시스템 콘솔이군요. 슬라이드에서는 링크 를 구현하는 방법에 대한 유용한 예 ',' 콘솔입니다 class.< /sup>.
',' 다탱푸트스트림 sup> <, 주로 읽는 데 사용되는 기본 입력 스트림을 통해 입력되는 프리미티브 데이터 형식, 머신에 의존 있는 것입니다. '보통' 다탱푸트스트림 읽는 데 사용되는 이진 데이터. 또한 특정 데이터 유형을 판독값 편의를 위한 방법. 예를 들어, 읽을 수 있는 방법을 가지고 있으며, /sup> 안에 선 them.< UTF 문자열이어야 포함할 수 있습니다.
그러나 이는 sup> <, 그래서 더 열심히, 더 복잡한 클래스 및 구현하십시오 초보자도 사용하지 않는 것이 좋습니다. 슬라이드에서는 링크 를 구현하는 방법을 ',' 유용한 예제에서와 다탱푸트스트림 .< /sup>.
이 프로그램은 사용자가 숫자를 입력할 수 있느냐. 그 후, 이 프로그램은 수와 자리 숫자 합한 인쇄합니다.
import java.util.Scanner;
public class PrintNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
int sum = 0;
System.out.println(
"Please enter a number to show its digits");
num = scan.nextInt();
System.out.println(
"Here are the digits and the sum of the digits");
while (num > 0) {
System.out.println("==>" + num % 10);
sum += num % 10;
num = num / 10;
}
System.out.println("Sum is " + sum);
}
}
다음은 제바스티레비스카너 사용자 프로그램을 사용하여 질문을 '에서':
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
int input = 0;
System.out.println("The super insano calculator");
System.out.println("enter the corrosponding number:");
Scanner reader3 = new Scanner(System.in);
System.out.println(
"1. Add | 2. Subtract | 3. Divide | 4. Multiply");
input = reader3.nextInt();
int a = 0, b = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
// get user input for a
a = reader.nextInt();
Scanner reader1 = new Scanner(System.in);
System.out.println("Enter the scend number");
// get user input for b
b = reader1.nextInt();
switch (input){
case 1: System.out.println(a + " + " + b + " = " + add(a, b));
break;
case 2: System.out.println(a + " - " + b + " = " + subtract(a, b));
break;
case 3: System.out.println(a + " / " + b + " = " + divide(a, b));
break;
case 4: System.out.println(a + " * " + b + " = " + multiply(a, b));
break;
default: System.out.println("your input is invalid!");
break;
}
}
static int add(int lhs, int rhs) { return lhs + rhs; }
static int subtract(int lhs, int rhs) { return lhs - rhs; }
static int divide(int lhs, int rhs) { return lhs / rhs; }
static int multiply(int lhs, int rhs) { return lhs * rhs; }
}
'시스템' 을 사용하여 클래스를 내려받습니다 입력입니다.
http://fresh2refresh.com/java-tutorial/java-input-output/:
>. 어떻게 데이터가 수락됨 키보드를 통해? >. -
>. 세 객체에는 필요하다,
>. 1. System.in >. 2. 린퍼트슈타림레이더 >. 3. 부퍼드레이더 >. >. >. 린퍼트슈타림레이더 부퍼드레이더 클래스 (java.io) 및 패키지 있다. >. 데이터가 수신되었습니다 (System.in) 에 의해 형태로 바이트입니다 키보드에서 린퍼타슬림 객체에는. >. 다음 린퍼트슈타림레이더 문자이어야 판독합니다 바이트입니다 및 디코딩하여 묶습니다. >. 텍스트 판독합니다 문자 입력 에서 마지막으로 부퍼드레이더 객체에는 스트리밍합니다, 버퍼링 때문에 효율적인 판독값 어레이에는 문자이어야 제공하기 위한 문자 및 방향선.
InputStreamReader inp = new InputStreamReader(system.in);
BufferedReader br = new BufferedReader(inp);
단 한 명의 추가 정보를. # 39 don& 경우 메모리 자원 누수 전날에약혼자에게 닫으십시오 싶지 않다, 위험 / 스캐너 스트리밍합니다 완료했으면:
myScanner.close();
참고로 이러한 점을 잘 jave 1.7 이상을 컴파일하십시오 경고 (# 39 don& t ask, 어떻게 알고 있어요 :-)
import java.util.Scanner;
class Daytwo{
public static void main(String[] args){
System.out.println("HelloWorld");
Scanner reader = new Scanner(System.in);
System.out.println("Enter the number ");
int n = reader.nextInt();
System.out.println("You entered " + n);
}
}
이것은 일반적인 요구 사항을 해결하는 더 개발했습니까 버전의 수락됨 오토메이티드 2:
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter integers. Type 0 to exit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == 0) {
done = true;
}
else {
// do something with the input
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Please enter integers. Type 0 to exit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: 0
Exiting...
참고로 네스틀린 () ',' 나쁜 입력입니다 트리거됩니다 반복적으로 같은 예외 없이 무한 루프. 다음 () '대신' 너회가 사용할 수 있는 상황에서 이 같은 사실을 알고 있지만, '은' 입력입니다 따라 여러 발령합니다 공백이 존재한다.
이는 자바 가상 머신 (jvm) 에, 네가 해야 할 일은 아주 단순해졌습니다 입력입니다 얻을 수 있다.
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class Myapplication{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a;
System.out.println("enter:");
a = in.nextInt();
System.out.println("Number is= " + a);
}
}
이렇게 getuser 입력입니다 부퍼드레이더 사용할 수 있습니다.
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
이것은 어떻게 적용할
String name = br.readline();
사용자가 자신의 이름으로, 콘솔, " 외면하였나니 추상형데이터타입 꽂으십시오 구체화하십시오 name". 해당 정보를 저장하는 것이다.
저장할 수 있는 경우, 코드는 다음과 같습니다.
int x = Integer.parseInt(br.readLine());
홉 (hop) 따라서!