簡體   English   中英

為什么我要創建一個新的掃描儀? 在創建驅動程序時

[英]Why do I have to create a new Scanner? when creating a driver

正如您所看到的,這是我正在處理的代碼片段。 我的問題是為什么我必須創建一個新的掃描儀才能輸入? 為什么我不能只使用stdIn.nextLine(); 代替? 如果你能包含一些參考文獻,我將非常感激。

import java.util.Scanner;

public class Week6{

    public static void main(String[]args){
    Horse horse1;
    Horse horse2;
    Horse horse3;
    String name;
    int age;
    double height;
    String color;
    boolean pureBlood;
    Scanner in = new Scanner(System.in);

    horse1 = new Horse(); // creation of Horse1
    horse2 = new Horse(); // creation of horse2
    horse3 = new Horse(); // creation of horse3

    System.out.print("Enter the name of Horse1: ");
    name = in.nextLine();

    horse1.setName(name); //setting name for horse1

    System.out.println(horse1.getName());



    } // end main
} // end class

檢查javadoc以獲取java.lang.Systemjava.io.InputStreamjava.io.Scanner

System.in是一個InputStream 因此,您可以使用InputStream方法從中訪問數據,這是非常基本的。

當您創建新的Scanner ,您將InputStream包裝在另一個類中,該類提供更高級/舒適的方法,如readLinenextLine ,這些方法在InputStream的定義中不可用。

如果它有助於可視化我的意思,請認為您的Scanner變量可能有任何不同的名稱,因此沒有直接的關系。 簡而言之,您不是在創建“另一個” Scanner因為在您的代碼中只有一個Scanner實例(您創建的實例)。

你不能使用stdIn,因為java既沒有那個對象,也沒有你創建過。 當你編寫myString.nextline()你正在調用對象myString(所有字符串都是對象,例如:String myString = new String(“Hello World!”)),但如果你調用stdIn,它將顯示錯誤。

我沒有找到任何你可以使用stdIn的java庫,但stdIn適用於PHP,Python和C,所以也許你因此而感到困惑。

我們使用Scanner類從user獲取輸入。我們首先創建一個Scanner類的對象,然后我們使用Scanner的方法class.Scanner類存在於java.util包中,所以我們在我們的程序中導入這個包為ex:

掃描儀a =新掃描儀(System.in);

使用以下Scanner類方法

1)nextInt輸入一個整數

2)nextFloat輸入一個浮點數

3)nextLine輸入一個字符串

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

希望! 這有助於你......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM