当我尝试运行for循环(Java)时,系统挂起
我正在尝试设置一个扫描器,它使用循环请求项目信息。当我试图创建一个item对象时,系统一直挂起,我不知道为什么。有什么想法吗?这是我的密码:当我尝试运行for循环(Java)时,系统挂起,java,loops,java.util.scanner,freeze,Java,Loops,Java.util.scanner,Freeze,我正在尝试设置一个扫描器,它使用循环请求项目信息。当我试图创建一个item对象时,系统一直挂起,我不知道为什么。有什么想法吗?这是我的密码: public class ItemAdd { // instance variables - replace the example below with your own // private String itemName; // private int cost; // private String taxable; /** * Construc
public class ItemAdd
{
// instance variables - replace the example below with your own
// private String itemName;
// private int cost;
// private String taxable;
/**
* Constructor for objects of class Item
*/
public ItemAdd()
{
System.out.println ("How many items do you have on your list?");
Scanner scan=new Scanner(System.in);
int count = scan.nextInt();
if (count>0)
for(;count>0; count--){
System.out.println("What is the item name?");
String itemName = scan.nextLine();
System.out.println("How much does this item cost?");
int cost = scan.nextInt();
System.out.println("Is this item taxable?");
String taxable = scan.nextLine();
}
}
}
你把nextLine和下一个方法混在一起,这是行不通的。使用
next()
而不是nextLine()
。如果希望空格成为项目名称中的有效部分,请在使用scanner.useDelimiter(“\r?\n”)创建扫描程序后立即更新扫描程序的分隔符
,然后next()
的操作与nextLine()
一样,只是没有中断。看起来您正在学习面向对象编程
您有一个类来描述一个项目。每个项目将有三个字段或属性-名称、成本和是否应纳税
Main类包括Main方法,Java从该方法开始执行程序。main方法调用程序中的其他代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println ("How many items do you have on your list?");
int count = scan.nextInt();
while (count>0){
// Create a new Item object and instantiate it
// This variable will be reused, meaning if you create 5
// objects, after the loop terminates there will only be
// one item variable.
Item item = new Item();
// Display the item value (this calls the toString method)
System.out.println(item);
count--;
}
}
}
// This is the class which describes Item objects
class Item {
// The properties of each item
private String itemName;
private int cost;
private String taxable;
// The constructor method which instantiates the object
public Item() {
// Get the values from the user and set the properties of the object
Scanner scan=new Scanner(System.in);
System.out.print("What is the item name? ");
itemName = scan.next();
System.out.print("How much does this item cost? ");
cost = scan.nextInt();
System.out.print("Is this item taxable? ");
taxable = scan.next();
}
// Returns a string representation of the object
public String toString() {
return String.format("Name: %s%nCost: %d%nTaxable: %s%n", itemName, cost, taxable);
}
}