我为主程序创建了一个类,为矩形创建了一个类本身,假设从用户输入创建2个矩形,打印矩形的信息并打印矩形的形状* ,但是当我创建第二个矩形时出现此错误:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Rectangle.input(Rectangle.java:74)
at Program.main(Program.java:20)
这是矩形的类:
import java.util.Scanner;
public class Rectangle {
// Data Members for rectangle.
private int width;
private int height;
public String color;
public int xPos;
public int yPos;
// Initialization..
public void init(int width, int height, String color, int xPos, int yPos) {
this.width = width;
this.height = height;
this.color = color;
this.xPos = xPos;
this.yPos = yPos;
}
// Print all Data Members.
public void printInfo() {
System.out.println("Width: " + width + ",Height: " + height
+ ",Color: " + color + ",X position: " + xPos + ",Y position: "
+ yPos);
}
// Setter (width)
public void setWidth(int width){
if(width >= 0 ){
this.width = width;
}
}
// Getter (width)
public int getWidth(){
return width;
}
// Setter (height)
public void setHeight(int height){
if(height >= 0){
this.height = height;
}
}
// Getter (height)
public int getHeight(){
return height;
}
public void starsRectangle(){
for(int i=0; i<getHeight(); i++){
for(int j=0; j<getWidth(); j++){
System.out.print("*");
}
System.out.println();
}
}
public void input(){
Scanner s = new Scanner(System.in);
System.out.println("Enter color");
String inputC = s.nextLine();
System.out.println("Enter width");
int inputW = s.nextInt();
System.out.println("Enter height");
int inputH = s.nextInt();
System.out.println("Enter x position");
int inputXPos = s.nextInt();
System.out.println("Enter y position");
int inputYpos = s.nextInt();
setWidth(inputW);
setHeight(inputH);
color = inputC;
xPos = inputXPos;
yPos = inputYpos;
s.close();
}
}
这是主程序的类:
public class Program {
public static void main(String[] args) {
Rectangle rec1 = new Rectangle(); // Reference1 + object
rec1.init(5, 3, "BLUE", 90, 50);
rec1.printInfo();
rec1.starsRectangle();
System.out.println("--------");
rec1.input();
rec1.starsRectangle();
System.out.println("--------");
Rectangle rec2 = new Rectangle(); // Reference2 + object
rec2.input();
rec2.printInfo();
rec2.starsRectangle();
}
}
答案 0 :(得分:1)
您可以使用
while(s.hasNextLine()){..}
以避免此错误。
答案 1 :(得分:0)
Scanner s = new Scanner(System.in);
作为实例变量或类变量。你可以在那个班级的任何地方使用它。编写一个close()方法,在退出应用程序之前关闭扫描程序流。
每次调用和关闭方法时都不要创建扫描仪对象。而是创建一次并关闭一次流。