简体   繁体   English

线程“main”中的异常 java.lang.NumberFormatException:对于输入字符串:“38”

[英]Exception in thread "main" java.lang.NumberFormatException: For input string: " 38"

For an assignment I have almost ready but can't seem to get past the error .. the file items.txt data对于我几乎准备好的作业,但似乎无法克服错误..文件 items.txt 数据

12345,Ballpeen Hammer,25,18.75 12345,Ballpeen Hammer,25,18.75

56789,Phillips Screwdriver,120,10.95 56789,十字螺丝刀,120,10.95

24680,Claw Hammer,35,15.98 24680,爪锤,35,15.98

13579,Box Wrench,48,20.35 13579,套筒扳手,48,20.35

28967,Hex Wrench,70,19.98 28967,六角扳手,70,19.98

the file activity.txt data文件activity.txt数据

D,12345,0 D,12345,0

R,12345,100 R,12345,100

S,12345,45 S,12345,45

The error i am getting again and again it tells me the error我一次又一次收到的错误告诉我错误

                       Exception in thread "main" java.lang.NumberFormatException: For input string: " 38"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at InventoryItemTest.main(InventoryItemTest.java:21)

C:\\Users\\Noah\\AppData\\Local\\NetBeans\\Cache\\8.2\\executor-snippets\\run.xml:53: Java returned: 1 BUILD FAILED (total time: 0 seconds) C:\\Users\\Noah\\AppData\\Local\\NetBeans\\Cache\\8.2\\executor-snippets\\run.xml:53:Java 返回:1 BUILD FAILED(总时间:0 秒)

The code that is not working不工作的代码

    import java.io.*;
    import java.text.NumberFormat;
    import java.time.format.DateTimeFormatter;
    import java.util.Calendar;
    import java.util.Scanner;

     public class InventoryItemTest {
     private static final int INVENTORY_SIZE=100;
     public static void main(String[] args)
            {
               InventoryItem[] inventoryItems= new 
               InventoryItem[INVENTORY_SIZE];
                        int i= 0;
                 //Process the file
                 try {
                                                                                          Scanner scanfile = new Scanner(new File("items.txt"));

        while (scanfile.hasNextLine())
        {
            String[] lines = scanfile.nextLine().split(",");
            if(Integer.parseInt(lines[0])>=20000 && Integer.parseInt(lines[0])<=79999) { 
                inventoryItems[i] = new InventoryItem(Integer.parseInt(lines[0]), lines[1], Integer.parseInt(lines[2]), Double.parseDouble(lines[3]));
                i++;
           }
        }
        System.out.println(i+" items has been created.");
        scanfile.close();
    }
    catch (FileNotFoundException ex)
    {
        System.err.println("FILE NOT FOUND!!!!");
    }

    try
    {
        int processedCount=0,skippedCount=0;
        Scanner scanFile = new Scanner(new File("activity.txt"));

        while (scanFile.hasNextLine())
        {
            String[] tokens = scanFile.nextLine().split(",");
            int id = Integer.parseInt(tokens[1]);
            System.out.println(id);
            int q = Integer.parseInt(tokens[2]);
            for (int j = 0; j <i ; j++) {
                if(id==inventoryItems[j].getItemNumber())
                {
                    processedCount++;
                    switch (tokens[0])
                    {
                        case "D":
                            inventoryItems[j].setQuantity(q);
                            break;
                        case "R":
                            inventoryItems[j].receiveItems(q);
                            break;
                        case "S":
                            inventoryItems[j].shipItems(q);
                            break;
                    }
                }
                skippedCount++;
            }
        }
        System.out.println("Total Number of received Process: "+processedCount);
        System.out.println("Number of records skipped: "+skippedCount);
        scanFile.close();
        PrintWriter writer = new PrintWriter(new FileWriter("report.txt"));
        //Preparing Report
        double grandTotal=0;
        double value =0;

        writer.println("Joe E. Bagadonuts for the Albatross Company, Ltd.\nPrepared On: "+ Calendar.getInstance().getTime());
        writer.println("\t\tI N V E N T O R Y  R E P O R T\nInventory Item");
        writer.println(String.format("%5s %19s %10s %10s %10s","Number","Description","Quantity","Unit Price","Value"));
        writer.println(String.format("%5s %19s %10s %10s %10s","------","-----------","--------","----------","------"));
        for (int j = 0; j <i ; j++) {
            value = inventoryItems[j].getQuantity()*inventoryItems[j].getUnitCost();
            grandTotal+=value;
            writer.println(String.format("%5s %19s %10s %11s %11s",inventoryItems[j].getItemNumber(),inventoryItems[j].getDescription(),inventoryItems[j].getQuantity(),NumberFormat.getCurrencyInstance().format(inventoryItems[j].getUnitCost()),NumberFormat.getCurrencyInstance().format(value)));

        }
        writer.println(String.format("%5s %19s %10s %10s %10s"," "," "," ","","==================="));
        writer.println(String.format("%5s %19s %10s %11s %11s"," "," "," ","Total ", NumberFormat.getCurrencyInstance().format(grandTotal)));

        writer.close();
    }
    catch (FileNotFoundException ex)
    {
        System.err.println("File not found...");
    } catch (IOException e) {
        System.err.println("Error in creating report");
    }
}

} }

You are getting that exception because the number that you are trying to parse has space with it.您收到该异常是因为您尝试解析的数字有空格。 trim() is a function in java which is used to remove space before and after a string. trim()是java中的一个函数,用于去除字符串前后的空格。 Read this to know more about trim.阅读 本文以了解有关修剪的更多信息。

import java.io.*;
import java.text.NumberFormat;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Scanner;

public class InventoryItemTest {
    private static final int INVENTORY_SIZE=100;
    public static void main(String[] args)
    {
        InventoryItem[] inventoryItems= new
                InventoryItem[INVENTORY_SIZE];
        int i= 0;
        //Process the file
        try {
            Scanner scanfile = new Scanner(new File("items.txt"));

            while (scanfile.hasNextLine())
            {
                String[] lines = scanfile.nextLine().split(",");
                int i1 = Integer.parseInt(lines[0].trim());
                if(i1>=20000 && i1<=79999) {
                    inventoryItems[i] = new InventoryItem(i1, lines[1], Integer.parseInt(lines[2].trim()), Double.parseDouble(lines[3].trim()));
                    i++;
                }
            }
            System.out.println(i+" items has been created.");
            scanfile.close();
        }
        catch (FileNotFoundException ex)
        {
            System.err.println("FILE NOT FOUND!!!!");
        }

        try
        {
            int processedCount=0,skippedCount=0;
            Scanner scanFile = new Scanner(new File("activity.txt"));

            while (scanFile.hasNextLine())
            {
                String[] tokens = scanFile.nextLine().split(",");
                int id = Integer.parseInt(tokens[1].trim());
                System.out.println(id);
                int q = Integer.parseInt(tokens[2].trim());
                for (int j = 0; j <i ; j++) {
                    if(id==inventoryItems[j].getItemNumber())
                    {
                        processedCount++;
                        switch (tokens[0])
                        {
                            case "D":
                                inventoryItems[j].setQuantity(q);
                                break;
                            case "R":
                                inventoryItems[j].receiveItems(q);
                                break;
                            case "S":
                                inventoryItems[j].shipItems(q);
                                break;
                        }
                    }
                    skippedCount++;
                }
            }
            System.out.println("Total Number of received Process: "+processedCount);
            System.out.println("Number of records skipped: "+skippedCount);
            scanFile.close();
            PrintWriter writer = new PrintWriter(new FileWriter("report.txt"));
            //Preparing Report
            double grandTotal=0;
            double value =0;

            writer.println("Joe E. Bagadonuts for the Albatross Company, Ltd.\nPrepared On: "+ Calendar.getInstance().getTime());
            writer.println("\t\tI N V E N T O R Y  R E P O R T\nInventory Item");
            writer.println(String.format("%5s %19s %10s %10s %10s","Number","Description","Quantity","Unit Price","Value"));
            writer.println(String.format("%5s %19s %10s %10s %10s","------","-----------","--------","----------","------"));
            for (int j = 0; j <i ; j++) {
                value = inventoryItems[j].getQuantity()*inventoryItems[j].getUnitCost();
                grandTotal+=value;
                writer.println(String.format("%5s %19s %10s %11s %11s",inventoryItems[j].getItemNumber(),inventoryItems[j].getDescription(),inventoryItems[j].getQuantity(),NumberFormat.getCurrencyInstance().format(inventoryItems[j].getUnitCost()),NumberFormat.getCurrencyInstance().format(value)));

            }
            writer.println(String.format("%5s %19s %10s %10s %10s"," "," "," ","","==================="));
            writer.println(String.format("%5s %19s %10s %11s %11s"," "," "," ","Total ", NumberFormat.getCurrencyInstance().format(grandTotal)));

            writer.close();
        }
        catch (FileNotFoundException ex)
        {
            System.err.println("File not found...");
        } catch (IOException e) {
            System.err.println("Error in creating report");
        }
    }

Try using below method while calling parseInt in InventoryItemTest while reading items.txt.在读取 items.txt 时,在 InventoryItemTest 中调用 parseInt 时尝试使用以下方法。

Integer getIntVal(String val){
 return val!=null ? Integer.parseInt(val.trim()) : null;
}

Eg:例如:

if(getIntVal(lines[0])>=20000 && getIntVal(lines[0])<=79999) { 
                inventoryItems[i] = new InventoryItem(getIntVal(lines[0]), lines[1], getIntVal(lines[2]), Double.parseDouble(lines[3]));
                i++;
           } 

Use trim() wherever you are accessing your lines[] array.在您访问 lines[] 数组的任何地方使用 trim()。

 if (Integer.parseInt(lines[0].trim().trim()) >= 20000 && Integer.parseInt(lines[0].trim()) <= 79999)
 {
      inventoryItems[i] = new InventoryItem(Integer.parseInt(lines[0].trim()), lines[1].trim(), Integer.parseInt(lines[2].trim()), Double.parseDouble(lines[3].trim()));
      i++;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java-线程“ main”中的异常java.lang.NumberFormatException:对于输入字符串:“”位于 - java - Exception in thread “main” java.lang.NumberFormatException: For input string: “” at 线程“ main”中的异常java.lang.NumberFormatException:对于输入字符串:Java中的“” - Exception in thread “main” java.lang.NumberFormatException: For input string: “” in Java 线程“ main”中的异常java.lang.NumberFormatException:对于输入字符串:“ 0.06” - Exception in thread “main” java.lang.NumberFormatException: For input string: “0.06” 线程“main”中的异常 java.lang.NumberFormatException:对于输入字符串:“8/3/2012” - Exception in thread "main" java.lang.NumberFormatException: For input string: "8/3/2012" 线程“ main”中的异常java.lang.NumberFormatException:对于输入字符串:“” - Exception in thread “main” java.lang.NumberFormatException: For input string: “” 线程“main”中的异常 java.lang.NumberFormatException:对于输入字符串:“0.353” - Exception in thread “main” java.lang.NumberFormatException: For input string: “0.353” 线程“main”中的异常 java.lang.NumberFormatException:对于输入字符串 - Exception in thread “main” java.lang.NumberFormatException: For input string 线程“ main”中的异常java.lang.NumberFormatException:对于输入字符串:“” Array - Exception in thread “main” java.lang.NumberFormatException: For input string: “” Array 线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“3291105000” - Exception in thread “main” java.lang.NumberFormatException: For input string: “3291105000” 线程“ main”中的异常java.lang.NumberFormatException:对于输入字符串:“ a” - Exception in thread “main” java.lang.NumberFormatException: For input string: “a”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM