【发布时间】:2020-03-18 09:03:01
【问题描述】:
我需要一些关于我作为示例编写的代码的帮助。 我目前正在使用 Atom 记事本作为我的代码。
问题陈述:
获取用户输入的平面详细信息。
预期输出:
打印用户输入的数据。
问题:
我能够成功地从用户那里获取输入,但是在打印时,所有值都显示为NULL。
代码:
import java.util.*;
class Planes{
String Name;
int Number_of_Pylons;
String Type;
void EnterValues()
{
Scanner s=new Scanner(System.in);
System.out.println("NAME: ");
String Name=s.nextLine();
System.out.println("PYLONS: ");
int Number_of_Pylons=s.nextInt();
s.nextLine();
System.out.print("TYPE OF CRAFT: ");
String Type=s.nextLine();
}
};
class Base{
public static void main(String args[]){
Planes air[]=new Planes[2];//DID NOT CREATE OBJECTS, REFERENCE ARRAY!!!!!!!!!
for(int j=0;j<2;j++){
air[j]=new Planes();
}// CREATED OBJECTS OF CLASS PLANE!!!!!!!!!
int i=0;
for(i=0;i<2;i++)
{
System.out.println("Enter values for the planes:");
air[i].EnterValues();
}
System.out.println(air[0].Name);//Test for Print, prints NULL idk why :(
for(i=0;i<2;i++)//Display the Entered Details
{
System.out.println("Name: "+air[i].Name+"Number of Pylons: "+air[i].Number_of_Pylons+"Type: "+air[i].Type);
}
}
};
这是一个相当简单的代码,但我似乎无法让它工作。 我也为我的英语道歉。它不是我的母语。
【问题讨论】:
-
我“认为”您的问题的原因是:stackoverflow.com/q/13102045/592355(当使用
nextInt()和nextLine()时出现意外值) -
解决方案:OR(1.) 通过
int Number_of_Pylons=Integer.valueOf(s.nextLine()); //possible runtime exception!获取您的 int ...OR(2.) 通过s.next()获取(全部)您的“字符串”(2 的问题。-它只读取到“空白”) -
但是
s.next只会取第一个标记值而不是整个句子,对吗? -
选项 3(如引用和接受的答案中所述):在
nextInt()之后调用nextLine();)