如何使用Scanner
类读取包含空格的字符串,例如"Bolt Penguin"
?我需要删除空格吗?
但我不能,我必须保持两个角色之间的空格。这是我创建的程序:
import java.util.Scanner;
public class Shop {
public static void main(String args[]){
Scanner You = new Scanner(System.in);
//Your Money
int money;
String name;
//Your Cards
String Cards;
//Shop (M) Cards
int Bolt_Penguin = 100;
int Eldeen = 95;
int Jinn = 1020;
//Shop (S) Cards
int Dark_Energy = 500;
int Horn_Unicorn = 640;
int Sparks = 90;
//Shop (T) Cards
int Hidden_S = 800;
... //You don't have to see the whole program
name = You.next();
if(name.equals("Bolt Penguin")){ //Here it is Bolt (space) Penguin
System.out.println("Seller: That'll cost " + Bolt_Penguin);
}else if(name.equals("Eldeen")){
System.out.println("Seller: That'll cost " + Eldeen);
}else if(name.equals("Jinn the Mystical Genie of the Lamp")){
System.out.println("Seller: That'll cost " + Jinn);
}else{
System.out.println("Seller: We don't have that Card yet! ");
}
...
我需要做些不同的事吗?
答案 0 :(得分:2)
使用:
name = You.nextLine();
用空格读取整行。
您可能还想使用equals
更改equalsIgnoreCase
,但这取决于您的要求:
name = You.nextLine();
if(name.equalsIgnoreCase("Bolt Penguin")) {
System.out.println("Seller: That'll cost " + Bolt_Penguin);
}
答案 1 :(得分:2)
替换
name = You.next();
通过
name = You.nextLine();
我用输入Bolt Penguin
我的输出是= Seller: That'll cost 100
答案 2 :(得分:1)
替换
name = You.next();
与
name = You.nextLine();