我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。

如何在Java中获得用户输入?


当前回答

使用JOptionPane就可以实现。

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

其他回答

你可以像这样使用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());

希望这能有所帮助!

最简单的方法之一是使用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();

获取用户输入的最简单方法是使用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();

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

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

    }
}

这是一个使用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;
            }
        }
    }   
}