我正在尝试在班级Address
中创建扫描仪方法,因此我不必在每个需要用户输入的方法中重复扫描器代码。我遇到的问题是,当我在Address
类的实例的测试程序中运行这两个set方法时,此方法似乎只返回我的实例变量值而不是用户的扫描程序输入。
我该怎么做?我不想在每一种方法中重复scr.nextInt()
等。
//Scanner method for integer inputs from user.
public int scanInt(){
int userInt = scr.nextInt();
scr.nextLine();
return userInt;
}
//Scanner method for string inputs from user
public String scanLine(){
String userString = scr.nextLine();
return userString;
}
//in these methods below (and others) I want to use the above scanner methods so I don't have to repeat the code for scanner inputs in every single method.
public void setStreet(){
System.out.println("Skriv in gata: ");
scanLine();
}
public void setStreetNr(){
System.out.println("Skriv in gatunummer: ");
scanInt();
}
答案 0 :(得分:1)
public void setStreet(){
System.out.println("Skriv in gata: ");
street = scanLine();
}
答案 1 :(得分:0)
听起来您正在使用BlueJ或其他程序测试您的课程。如果是这种情况,请尝试这个课程。
import java.util.Scanner;
public class Address
{
String street;
int streetNr;
Scanner scr = new Scanner(System.in);
//Scanner method for integer inputs from user.
public int scanInt()
{
int userInt = scr.nextInt();
scr.nextLine();
return userInt;
}
//Scanner method for string inputs from user
public String scanLine()
{
String userString = scr.nextLine();
return userString;
}
public void setStreet()
{
System.out.println("Skriv in gata: ");
street = scanLine();
}
public void setStreetNr()
{
System.out.println("Skriv in gatunummer: ");
streetNr = scanInt();
}
}
这应该像你描述的那样工作。创建类的实例,调用这两个方法并检查对象的参数。此代码将输入分配给每个方法的变量。