Java中如何获取用户输入?

发布于 2024-10-22 02:29:34 字数 74 浏览 2 评论 0 原文

我尝试创建一个计算器,但无法让它工作,因为我不知道如何获取用户输入

Java中如何获取用户输入?

I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.

How can I get the user input in Java?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

江城子 2024-10-29 02:29:34

最简单的方法之一是使用 Scanner对象如下:

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();

One of the simplest ways is to use a Scanner object as follows:

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();
素染倾城色 2024-10-29 02:29:34

您可以根据需要使用以下任意选项。

扫描仪

import java.util.Scanner; 
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReaderInputStreamReader

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);

DataInputStream

import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

DataInputStream 类中的 readLine 方法已被弃用。要获取字符串值,您应该将之前的解决方案与 BufferedReader 结合使用


Console class

import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

显然,这种方法在某些IDE中效果不佳。

You can use any of the following options based on the requirements.

Scanner class

import java.util.Scanner; 
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReader and InputStreamReader classes

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);

DataInputStream class

import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader


Console class

import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

Apparently, this method does not work well in some IDEs.

小草泠泠 2024-10-29 02:29:34

您可以使用 Scanner 类或控制台类

Console console = System.console();
String input = console.readLine("Enter input:");

You can use the Scanner class or the Console class

Console console = System.console();
String input = console.readLine("Enter input:");
沙与沫 2024-10-29 02:29:34

您可以使用 BufferedReader

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;  

System.out.println("Enter your Account number: ");
accStr = br.readLine();

它将在 accStr 中存储一个 String 值,因此您必须使用 int 将其解析为 int 。 oracle.com/javase/8/docs/api/java/lang/Integer.html#parseInt-java.lang.String-" rel="noreferrer">Integer.parseInt

int accInt = Integer.parseInt(accStr);

You can get user input using BufferedReader.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;  

System.out.println("Enter your Account number: ");
accStr = br.readLine();

It will store a String value in accStr so you have to parse it to an int using Integer.parseInt.

int accInt = Integer.parseInt(accStr);
涙—继续流 2024-10-29 02:29:34

以下是获取键盘输入的方法:

Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");  
String name = scanner.next(); // Get what the user types.

Here is how you can get the keyboard inputs:

Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");  
String name = scanner.next(); // Get what the user types.
夜雨飘雪 2024-10-29 02:29:34

最好的两个选项是 BufferedReader 和 Scanner。

最广泛使用的方法是 Scanner,我个人更喜欢它,因为它简单且易于实现,以及将文本解析为原始数据的强大实用程序。

使用 Scanner 的优点

  • 易于使用 Scanner
  • 轻松输入数字(int、short、byte、float、long 和 double)
  • 例外情况是不勾选哪个更方便。程序员要文明一点,指定或捕获异常。
  • 能够读取行、空格和正则表达式分隔的标记

BufferedInputStream 的优点

  • BufferedInputStream 是一次读取数据块而不是单个字节
  • 可以读取字符、字符数组和行
  • < a href="https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/" rel="noreferrer">抛出检查异常
  • 快速性能
  • 同步(您无法在线程之间共享 Scanner)

总体而言,每种输入法都有不同的用途.

  • 如果您输入大量数据,BufferedReader 可能会
    对您更好

  • 如果您输入大量数字扫描仪会自动解析
    这非常方便

对于更基本的用途我会推荐Scanner因为它更容易使用并且更容易编写程序。以下是如何创建扫描仪的快速示例。我将在下面提供如何使用 Scanner 的全面示例

Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name");       // prompt user
name = scanner.next();                     // get user input

(有关 BufferedReader 的更多信息,请参阅 如何使用 BufferedReader 并参阅 读取字符行)


java.util.Scanner

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
    }
}

注意:其他类,例如 ConsoleDataInputStream 也是可行的替代方案。

Console 具有一些强大的功能,例如然而,并非所有 IDE(例如 Eclipse)都具有读取密码的功能。发生这种情况的原因是 Eclipse 将您的应用程序作为后台进程运行,而不是作为带有系统控制台的顶级进程运行。 这里是一个链接,指向有关如何实现控制台的有用示例 code> 类。

DataInputStream 主要用于以与机器无关的方式从底层输入流中将输入作为原始数据类型读取。 DataInputStream 通常用于读取二进制数据。它还提供了读取某些数据类型的便捷方法。例如,它有一个读取 UTF 字符串的方法,其中可以包含任意数量的行。

但是,它是一个更复杂的类,更难实现,因此不建议初学者使用。 这里是一个链接,指向如何实现 DataInputStream.

The best two options are BufferedReader and Scanner.

The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.

Advantages of Using Scanner

  • Easy to use the Scanner class
  • Easy input of numbers (int, short, byte, float, long and double)
  • Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
  • Is able to read lines, white spaces, and regex-delimited tokens

Advantages of BufferedInputStream


Overall each input method has different purposes.

  • If you are inputting large amount of data BufferedReader might be
    better for you

  • If you are inputting lots of numbers Scanner does automatic parsing
    which is very convenient

For more basic uses I would recommend the Scanner because it is easier to use and easier to write programs with. Here is a quick example of how to create a Scanner. I will provide a comprehensive example below of how to use the Scanner

Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name");       // prompt user
name = scanner.next();                     // get user input

(For more info about BufferedReader see How to use a BufferedReader and see Reading lines of Chars)


java.util.Scanner

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
    }
}

Note: Other classes such as Console and DataInputStream are also viable alternatives.

Console has some powerful features such as ability to read passwords, however, is not available in all IDE's (such as Eclipse). The reason this occurs is because Eclipse runs your application as a background process and not as a top-level process with a system console. Here is a link to a useful example on how to implement the Console class.

DataInputStream is primarily used for reading input as a primitive datatype, from an underlying input stream, in a machine-independent way. DataInputStream is usually used for reading binary data. It also provides convenience methods for reading certain data types. For example, it has a method to read a UTF String which can contain any number of lines within them.

However, it is a more complicated class and harder to implement so not recommended for beginners. Here is a link to a useful example how to implement a DataInputStream.

草莓味的萝莉 2024-10-29 02:29:34

您可以编写一个简单的程序来询问用户名并打印回复使用的输入内容。

或者要求用户输入两个数字,您可以对这些数字进行加、乘、减或除操作,并打印用户输入的答案,就像计算器的行为一样。

所以你需要 Scanner 类。您必须import java.util.Scanner;并且在代码中您需要使用

Scanner input = new Scanner(System.in);

Input是一个变量名。

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

看看有何不同:input.next();i = input.nextInt();d = input.nextDouble();

根据 String,int 和 double 的变化方式与其余的相同。不要忘记代码顶部的 import 语句。

另请参阅博客文章 "扫描仪类并获取用户输入”

You can make a simple program to ask for user's name and print what ever the reply use inputs.

Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.

So there you need Scanner class. You have to import java.util.Scanner; and in the code you need to use

Scanner input = new Scanner(System.in);

Input is a variable name.

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

See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();

According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.

Also see the blog post "Scanner class and getting User Inputs".

秋风の叶未落 2024-10-29 02:29:34

要读取一行或字符串,您可以将 BufferedReader 对象与 InputStreamReader 对象结合使用,如下所示:

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();

To read a line or a string, you can use a BufferedReader object combined with an InputStreamReader one as follows:

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
两相知 2024-10-29 02:29:34

在这里,程序要求用户输入一个数字。之后,程序打印数字的位数以及数字的总和。

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);            
    }
}

Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.

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);            
    }
}
不美如何 2024-10-29 02:29:34

这是使用 java.util.Scanner 的问题中的程序:

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; }
}

Here is your program from the question using java.util.Scanner:

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; }
}
无远思近则忧 2024-10-29 02:29:34
Scanner input = new Scanner(System.in);
String inputval = input.next();
Scanner input = new Scanner(System.in);
String inputval = input.next();
眼睛会笑 2024-10-29 02:29:34
Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();
Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();
情绪操控生活 2024-10-29 02:29:34

只是一个额外的细节。如果您不想冒内存/资源泄漏的风险,则应该在完成后关闭扫描器流:

myScanner.close();

请注意,java 1.7 及更高版本将其捕获为编译警告(不要问我是怎么知道的:-)

Just one extra detail. If you don't want to risk a memory/resource leak, you should close the scanner stream when you are finished:

myScanner.close();

Note that java 1.7 and later catch this as a compile warning (don't ask how I know that :-)

醉南桥 2024-10-29 02:29:34

这是已接受答案的更完善版本,可满足两个常见需求:

  • 重复收集用户输入,直到输入退出值
  • 处理无效输入值(本例中为非整数)

代码

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...

请注意,如果没有 nextLine(),错误的输入将在无限循环中重复触发相同的异常。根据具体情况,您可能需要使用 next() 来代替,但要知道像 this has paths 这样的输入会生成多个异常。

Here is a more developed version of the accepted answer that addresses two common needs:

  • Collecting user input repeatedly until an exit value has been entered
  • Dealing with invalid input values (non-integers in this example)

Code

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();
    }
}

Example

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...

Note that without nextLine(), the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.

她比我温柔 2024-10-29 02:29:34
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);

    }
}
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);

    }
}
破晓 2024-10-29 02:29:34

main() 旁边添加 throws IOException,然后

DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();

Add throws IOException beside main(), then

DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();
红玫瑰 2024-10-29 02:29:34

在java中获取输入非常简单,你所要做的就是:

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);
    }
}

It is very simple to get input in java, all you have to do is:

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);
    }
}
琉璃梦幻 2024-10-29 02:29:34
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);
     }
}
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);
     }
}
半世晨晓 2024-10-29 02:29:34

您可以使用 BufferedReader 获取这样的用户输入:

    InputStreamReader inp = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(inp);
    // you will need to import these things.

这就是应用它们的方式

    String name = br.readline(); 

因此,当用户在控制台中输入他的名字时,“字符串名称”将存储该信息。

如果它是您要存储的数字,代码将如下所示:

    int x = Integer.parseInt(br.readLine());

希望这有帮助!

You can get user input like this using a BufferedReader:

    InputStreamReader inp = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(inp);
    // you will need to import these things.

This is how you apply them

    String name = br.readline(); 

So when the user types in his name into the console, "String name" will store that information.

If it is a number you want to store, the code will look like this:

    int x = Integer.parseInt(br.readLine());

Hop this helps!

太阳男子 2024-10-29 02:29:34

可以是这样的...

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.println("Enter a number: ");
    int i = reader.nextInt();
    for (int j = 0; j < i; j++)
        System.out.println("I love java");
}

Can be something like this...

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.println("Enter a number: ");
    int i = reader.nextInt();
    for (int j = 0; j < i; j++)
        System.out.println("I love java");
}
柠檬心 2024-10-29 02:29:34

您可以使用Scanner获取用户输入。您可以使用正确的方法对不同的数据类型进行正确的输入验证,例如针对 Stringnext() 或针对 Integer 的 nextInt()

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);

//reads until the end of line
String aLine = scanner.nextLine();

//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);

//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);


//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();

scanner.close();

You can get the user input using Scanner. You can use the proper input validation using proper methods for different data types like next() for String or nextInt() for Integer.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);

//reads until the end of line
String aLine = scanner.nextLine();

//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);

//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);


//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();

scanner.close();
述情 2024-10-29 02:29:34
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to the best program in the world! ");
        while (true) {
            System.out.print("Enter a query: ");
            Scanner scan = new Scanner(System.in);
            String s = scan.nextLine();
            if (s.equals("q")) {
                System.out.println("The program is ending now ....");
                break;
            } else  {
                System.out.println("The program is running...");
            }
        }
    }
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to the best program in the world! ");
        while (true) {
            System.out.print("Enter a query: ");
            Scanner scan = new Scanner(System.in);
            String s = scan.nextLine();
            if (s.equals("q")) {
                System.out.println("The program is ending now ....");
                break;
            } else  {
                System.out.println("The program is running...");
            }
        }
    }
}
歌枕肩 2024-10-29 02:29:34

这是使用 System.in.read() 函数的简单代码。这段代码只是写出输入的内容。如果您只想接受一次输入,则可以摆脱 while 循环,并且如果您愿意,可以将答案存储在字符数组中。

package main;

import java.io.IOException;

public class Root 
{   
    public static void main(String[] args)
    {
        new Root();
    }

    public Root()
    {
        while(true)
        {
            try
            {
                for(int y = 0; y < System.in.available(); ++y)
                { 
                    System.out.print((char)System.in.read()); 
                }
            }
            catch(IOException ex)
            {
                ex.printStackTrace(System.out);
                break;
            }
        }
    }   
}    

This is a simple code that uses the System.in.read() function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.

package main;

import java.io.IOException;

public class Root 
{   
    public static void main(String[] args)
    {
        new Root();
    }

    public Root()
    {
        while(true)
        {
            try
            {
                for(int y = 0; y < System.in.available(); ++y)
                { 
                    System.out.print((char)System.in.read()); 
                }
            }
            catch(IOException ex)
            {
                ex.printStackTrace(System.out);
                break;
            }
        }
    }   
}    
嗳卜坏 2024-10-29 02:29:34

我喜欢以下内容:

public String readLine(String tPromptString) {
    byte[] tBuffer = new byte[256];
    int tPos = 0;
    System.out.print(tPromptString);

    while(true) {
        byte tNextByte = readByte();
        if(tNextByte == 10) {
            return new String(tBuffer, 0, tPos);
        }

        if(tNextByte != 13) {
            tBuffer[tPos] = tNextByte;
            ++tPos;
        }
    }
}

例如,我会这样做:

String name = this.readLine("What is your name?")

I like the following:

public String readLine(String tPromptString) {
    byte[] tBuffer = new byte[256];
    int tPos = 0;
    System.out.print(tPromptString);

    while(true) {
        byte tNextByte = readByte();
        if(tNextByte == 10) {
            return new String(tBuffer, 0, tPos);
        }

        if(tNextByte != 13) {
            tBuffer[tPos] = tNextByte;
            ++tPos;
        }
    }
}

and for example, I would do:

String name = this.readLine("What is your name?")
江南烟雨〆相思醉 2024-10-29 02:29:34

正如其他人所发布的那样,可以使用扫描仪进行键盘输入。但在这个高度图形化的时代,制作没有图形用户界面(GUI)的计算器是毫无意义的。

在现代 Java 中,这意味着使用 Scene Builder 等 JavaFX 拖放工具来放置输出一个类似于计算器控制台的 GUI。
请注意,使用 Scene Builder 直观上很简单,并且不需要您已有的事件处理程序的额外 Java 技能。

对于用户输入,GUI 控制台顶部应该有一个宽文本字段。

用户可以在此处输入他们想要执行功能的数字。
在文本字段下方,您将有一组功能按钮,用于执行基本功能(即加/减/乘/除和记忆/调用/清除)功能。
一旦设计好 GUI,您就可以添加“控制器”引用,将每个按钮功能链接到其 Java 实现,例如调用项目控制器类中的方法。

此视频有点旧,但仍然显示了场景生成器的使用方法是多么简单。

Keyboard entry using Scanner is possible, as others have posted. But in these highly graphic times it is pointless making a calculator without a graphical user interface (GUI).

In modern Java this means using a JavaFX drag-and-drop tool like Scene Builder to lay out a GUI that resembles a calculator's console.
Note that using Scene Builder is intuitively easy and demands no additional Java skill for its event handlers that what you already may have.

For user input, you should have a wide TextField at the top of the GUI console.

This is where the user enters the numbers that they want to perform functions on.
Below the TextField, you would have an array of function buttons doing basic (i.e. add/subtract/multiply/divide and memory/recall/clear) functions.
Once the GUI is lain out, you can then add the 'controller' references that link each button function to its Java implementation, e.g a call to method in your project's controller class.

This video is a bit old but still shows how easy Scene Builder is to use.

剩余の解释 2024-10-29 02:29:34

获取用户输入的最简单方法是使用 Scanner。下面是一个如何使用它的示例:

import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();

代码行 import java.util.Scanner; 告诉程序程序员将在其代码中使用用户输入。正如它所说,它导入了扫描仪实用程序。 Scanner sc=new Scanner(System.in); 告诉程序启动用户输入。完成此操作后,您必须创建一个没有值的字符串或整数,然后将它们放入 a=sc.nextInt();a=sc.nextLine();< 行中/代码>。这为变量提供了用户输入的值。然后您可以在您的代码中使用它。希望这有帮助。

The most simple way to get user input would be to use Scanner. Here's an example of how it's supposed to be used:

import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();

The line of code import java.util.Scanner; tells the program that the programmer will be using user inputs in their code. Like it says, it imports the scanner utility. Scanner sc=new Scanner(System.in); tells the program to start the user inputs. After you do that, you must make a string or integer without a value, then put those in the line a=sc.nextInt(); or a=sc.nextLine();. This gives the variables the value of the user inputs. Then you can use it in your code. Hope this helps.

小梨窩很甜 2024-10-29 02:29:34

使用 JOptionPane 你可以实现它。

Int a =JOptionPane.showInputDialog(null,"Enter number:");

Using JOptionPane you can achieve it.

Int a =JOptionPane.showInputDialog(null,"Enter number:");
小糖芽 2024-10-29 02:29:34
import java.util.Scanner;

public class userinput {
    public static void main(String[] args) {        
        Scanner input = new Scanner(System.in);

        System.out.print("Name : ");
        String name = input.next();
        System.out.print("Last Name : ");
        String lname = input.next();
        System.out.print("Age : ");
        byte age = input.nextByte();

        System.out.println(" " );
        System.out.println(" " );

        System.out.println("Firt Name: " + name);
        System.out.println("Last Name: " + lname);
        System.out.println("      Age: " + age);
    }
}
import java.util.Scanner;

public class userinput {
    public static void main(String[] args) {        
        Scanner input = new Scanner(System.in);

        System.out.print("Name : ");
        String name = input.next();
        System.out.print("Last Name : ");
        String lname = input.next();
        System.out.print("Age : ");
        byte age = input.nextByte();

        System.out.println(" " );
        System.out.println(" " );

        System.out.println("Firt Name: " + name);
        System.out.println("Last Name: " + lname);
        System.out.println("      Age: " + age);
    }
}
双手揣兜 2024-10-29 02:29:34
class ex1 {    
    public static void main(String args[]){
        int a, b, c;
        a = Integer.parseInt(args[0]);
        b = Integer.parseInt(args[1]);
        c = a + b;
        System.out.println("c = " + c);
    }
}
// Output  
javac ex1.java
java ex1 10 20 
c = 30
class ex1 {    
    public static void main(String args[]){
        int a, b, c;
        a = Integer.parseInt(args[0]);
        b = Integer.parseInt(args[1]);
        c = a + b;
        System.out.println("c = " + c);
    }
}
// Output  
javac ex1.java
java ex1 10 20 
c = 30
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文