首页 > 解决方案 > 如何解决错误以及如何使用 oops 概念做得更好?

问题描述

我正在学习java程序。我有一个问题要解决。问题是

enter the no . of people:
enter the product_name, price, stock_available:
total amount is price * no. of people

如果可用库存少于人数,则打印值 0

例子:

**input:**
 no . of people : 3
product_name, price, stock_available: book, 100, 3
**output:** 300


public class Product {

public static void main(String args[]) {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the no . of people:");
    int people=sc.nextInt();
    String[] string = new String [3]; 
    System.out.println("Enter the product_name, price, quantity_available:");
    for (int i = 0; i < 3; i++)   
    {  
        string[i] = sc.nextLine();  
    }
    
    int quantity=Integer.parseInt(string[2]); 
    int price=Integer.parseInt(string[1]);
    if(people<=quantity) {
        System.out.println("Total amout is:"+(price*people));
    }
    else
    {
        System.out.println("value is "+0);
    }
    
}
}

控制台错误:

Enter the no . of people:
3
Enter the product_name, price, quantity_available:
book
30
Exception in thread "main" java.lang.NumberFormatException: For input string: "book"

如何解决这个错误以及如何更好地使用 oops 概念?

标签: java

解决方案


您的问题是您正在使用:

for (int i = 0; i < 3; i++)
{
    string[i] = sc.nextLine();
}

sc.nextLine()同时接受输入。现在问题是sc.nextLine()读取一行,直到遇到'\n'或。enter现在,对于 for 循环中的第一个循环,它将 a'\n'放入缓冲区中。因为 nextLine() 在'\n'遇到时停止接受输入。因此,在下一个周期中, 的值string[1] = '\n'。当您尝试将其解析为 Integer 时,会发生错误。因为这不是整数。

尝试这个:

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the no . of people:");

        int people = sc.nextInt();

        String[] string = new String [3];

        System.out.println("Enter the product_name, price, quantity_available:");

        for (int i = 0; i < 3; i++)
        {
            string[i] = sc.next();
        }

        int price = Integer.parseInt(string[1]);
        int quantity = Integer.parseInt(string[2]);

        if(people <= quantity) {
            System.out.println("Total amount is: "+ (price*people));
        }

        else
        {
            System.out.println("value is: "+0);
        }

    }


推荐阅读