java – System.out.print同时打印两行/题.我究竟做错了什么?
作者:互联网
所以我正在为类分配工作,在我完成并修复了编译器发现的所有错误后,我在运行程序时得到了这个:
J:\Java Class>java AddressDemo
What is your Street's name? Unknown RD
What is your zip code? 1234565
What is your State?
What is your house number?
它同时询问这两个问题并等待输入.
这是我的代码:
import java.util.Scanner;
public class AddressDemo
{
public static void main(String[] args)
{
Address address = new Address();
Scanner input = new Scanner(System.in);
String Street;
int Zip;
String State;
String City;
int house;
// Get the student's input
System.out.println();
System.out.print("What is your Street's name?\t");
Street = input.nextLine();
System.out.println();
System.out.print("What is your zip code?\t");
Zip = input.nextInt();
System.out.println();
System.out.print("What is your State?\t");
State = input.nextLine();
System.out.println();
System.out.print("What is your house number?\t");
house = input.nextInt();
System.out.println();
System.out.print(" What is your city?\t");
City = input.nextLine();
// Processing
address.setStName(Street);
address.setZNum(Zip);
address.setSName(State);
address.setCName(City);
address.setHNum(house);
//Output isn't finished
System.out.println("\nYour address is:" + address.getHNum() + address.getStName() + address.getCName() +address.getSName()
+ address.getZNum() + " !");
}
}
这是我需要的其他文件的代码:
public class Address
{
private int HNum;
private String StName;
private String CName;
private String SName;
private int ZNum;
private String LNum;
public boolean setHNum (int hn)
{
HNum = hn;
return true;
}
public String getHNum()
{
return String.format("%08d", HNum);
}
public boolean setStName(String str)
{
StName = str;
return true;
}
public String getStName()
{
return StName;
}
public boolean setCName(String City)
{
CName = City;
return true;
}
public String getCName()
{
return CName;
}
public boolean setSName(String st)
{
SName = st;
return true;
}
public String getSName()
{
return SName;
}
public boolean setZNum ( int zip)
{
ZNum = zip;
return true;
}
public String getZNum()
{
return String.format("%08d", ZNum);
}
public boolean setLNum (String l2)
{
LNum = l2;
return true;
}
public String getLNum()
{
return String.format("%08d", LNum);
}
}
解决方法:
使用input.nextInt()时,它不会使用结束输入的换行符.结果是当您提示下一个输入(状态)时,它会立即读取剩余的换行符,将空字符串分配给State,并提示输入门牌号.您应该使用input.nextLine()来读取邮政编码(以及稍后的门牌号)并将该行解析为int.或者,在调用nextInt()之后调用nextLine()并忽略返回值.
我想建议邮政编码应该只是一个字符串,以便你保留前导零并可以处理zip 4地址.同样,门牌号码应该是一个字符串来处理像贝克街221b这样的地址.当然,这将需要更改您的Address类定义以及更改读取输入的方式.
标签:java-util-scanner,java,system-out 来源: https://codeday.me/bug/20190824/1713251.html