Java:从控制台读取

时间:2014-01-15 18:11:25

标签: java console

我不知道如何从Java中读取控制台。 如果有可能我想用扫描仪来做。 这是我在学习Java时尝试过的。

package Scanners;

import java.util.Scanner;

public class ConsoleScanner {


    static Scanner input = new Scanner(System.in);

    public static void main(String[] args){

        if(input.equals("Hello"))
            System.out.println("You typed in: Hello ");
        if(input.equals("Good Bye"))
            System.out.println("You typed in: Good Bye");
        else{
            System.out.println("You typed in: " + input);
        }


    }

}

它给了我这个错误:

  

您输入的内容:   java.util.Scanner中[定界符= \ p {javaWhitespace} +] [位置= 0] [匹配   valid = false] [need input = false] [来源   closed = false] [skipped = false] [group separator =。] [decimal   separator = \,] [positive prefix =] [negative prefix = \ Q- \ E] [positive   suffix =] [negative suffix =] [NaN string = \ Q?\ E] [infinity string = \ Q?\ E]

如果有更好的方法从控制台读取,请发布。 - 谢谢

4 个答案:

答案 0 :(得分:0)

您不想打印扫描仪本身。您想调用各种扫描仪功能来获取输入。有关详细信息,请查看Scanner APIScanner tutorial(这是google搜索“Java Scanner”的第一个和第二个结果)。

答案 1 :(得分:0)

试试这个:

  

包装扫描仪;

     

import java.util.Scanner;

     

public class ConsoleScanner {

static Scanner scanner = new Scanner(System.in); //Creates the scanner

public static void main(String[] args){

    String input = scanner.NextLine();  //Sets the string input equal to whatever the user types next

    if(input.equals("Hello"))
        System.out.println("You typed in: Hello ");
    if(input.equals("Good Bye"))
        System.out.println("You typed in: Good Bye");
    else{
        System.out.println("You typed in: " + input);
    }


}
     

}

答案 2 :(得分:0)

我的朋友你必须使用

Scanner scanner= new Scanner(System.in);
    input = scanner.next();

此方法查找并返回此扫描程序中的下一个完整标记。在完成令牌之前和之后是与分隔符模式匹配的输入。

答案 3 :(得分:-1)

import java.util.Scanner;  
class ScannerDemo{  
 public static void main(String args[]){  

   Scanner sc=new Scanner(System.in);  

   System.out.println("Enter your age");  
   int age=sc.nextInt();  

   System.out.println("age:"+age);  

 }  
}