在java中从用户获取字符串输入

时间:2015-03-27 19:25:47

标签: java arrays string java.util.scanner

我是java新手并练习java程序。我的代码如下:

String i;
    String[] people={"Ronald","Donald"};

System.out.println("Whose information do you want?"+Arrays.toString(people));
Scanner s =new Scanner(System.in);
**i=s.nextLine();**

          if(i=="Ronald")
     {
         System.out.println("Ronald is CEO and is in Room No 20"); 
     }
          if(i=="Donald")
     {
         System.out.println("Donald is postman and is in Room No 10"); 
     }

     }
    }

这实际上是一个简单的程序。我想知道的是每当用户输入Ronald时,其打印声明应该在控制台中打印。但应该询问用户想要查看哪些信息。我想知道如何从用户那里获取字符串值。

提前谢谢你:)

2 个答案:

答案 0 :(得分:1)

比较java中的字符串时使用equals方法

if ( i.equals("Ronald") ){

}

答案 1 :(得分:0)

以这种方式检查字符串相等

  if(i.equals("Ronald"))

不使用==

输出

Whose information do you want?[Ronald, Donald]
Ronald
Ronald is CEO and is in Room No 20

使用此课程它完全有效:

    import java.util.Arrays;
import java.util.Scanner;
class ronald {
    public static void main(String[] args) {
     String i;
     String[] people={"Ronald","Donald"};
     System.out.println("Whose information do you want?"+Arrays.toString(people));
     Scanner s =new Scanner(System.in);
     i=s.nextLine();
         if(i.equals("Ronald")) {
         System.out.println("Ronald is CEO and is in Room No 20"); 
         }
         if(i.equals("Donald")) {
         System.out.println("Donald is postman and is in Room No 10"); 
         }
     }
    }

唐纳德的输出

Whose information do you want?[Ronald, Donald]
Donald
Donald is postman and is in Room No 10