简体   繁体   English

如何存储具有用户输入值的数组

[英]How to store an array with user input values

I'm taking a java course in school and was given this question: "Write a program that stores an array of the five int values 1, 2, 3, 4, and 5, a Date object for current time, and the double value 5.5 in the file named Exercise17_05.dat."我正在学校学习 java 课程,并被问到这个问题:“编写一个程序,存储五个 int 值 1、2、3、4 和 5 的数组,一个 Date object 用于当前时间,以及 double 值5.5 在名为exercise17_05.dat 的文件中。”

My professor wanted to modify this by saying, "We will change things up a little on this in that you need to let the user enter in their name and enter the five (5) integer values along with the other two items mentioned."我的教授想通过说“我们将对此进行一些修改,因为您需要让用户输入他们的姓名并输入五 (5) 个 integer 值以及提到的其他两项。”

I figured out how to do the original problem thanks to the amazing people on here.感谢这里的了不起的人,我想出了如何解决最初的问题。 I tried to modify the program with what I know but keep getting "Exception in Thread" errors.我试图用我所知道的修改程序,但不断收到“线程中的异常”错误。

Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readFully(DataInputStream.java:197)
    at java.io.DataInputStream.readLong(DataInputStream.java:416)
    at java.io.DataInputStream.readDouble(DataInputStream.java:468)
    at java.io.ObjectInputStream$BlockDataInputStream.readDouble(ObjectInputStream.java:3208)
    at java.io.ObjectInputStream.readDouble(ObjectInputStream.java:1061)
    at cosc_hw17.COSC_HW17.main(COSC_HW17.java:75)
Java Result: 1

I know it has something to do with creating an array and the original reading from the file part.我知道这与创建数组和从文件部分读取的原始数据有关。 Any help would be greatly appreciated.任何帮助将不胜感激。

What I have is attached below.我所拥有的附在下面。 I updated the code and am still having issues.我更新了代码,但仍然有问题。 Error is reading that it cannot find symbol for the numbers' "readObject"错误是读取它找不到数字“readObject”的符号

 import java.io.*; import java.util.Scanner; import java.util.Arrays; import java.util.Date; public class COSC_HW17 { // main method public static void main(String[] args) throws ClassNotFoundException, IOException { // create scanner Scanner input = new Scanner (System.in); // stores integers in array double [] numbers = new double [5]; // stores the returned array from method double[] ret; //Create an output stream for file ObjectOutputStream output = new ObjectOutputStream( new FileOutputStream("Exercise17_05.dat", true)); // Ask user for name System.out.println("Please Enter Name:"); String name = input.next(); // Ask user for numbers System.out.println("Input Five Integer Values:"); for (int i = 0; i < 5; i++) { numbers[i] = input.nextInt(); } //Write to file // 1. Write name output.writeUTF(name); // 2. Write int array object output.writeObject(numbers); // 3. Write double output.writeDouble(5.5); // 4. Write date object output.writeObject(new java.util.Date()); // 5. Write utf string output.writeUTF("Exercise17_05.dat"); // Close the stream output.close(); //Create an input stream for file ObjectInputStream report = new ObjectInputStream (new FileInputStream("Exercise17_05.dat")); // Read from file // 1. Read name System.out.println("Name: " + name); // 2. Read int array object int[] newNumbers = (int[]) (input.readObject()); System.out.println("Integers: " + Arrays.toString(newNumbers)); // 3. Read double double doubleValue = report.readDouble(); System.out.println("Double value: " + doubleValue); // 4. Read date object Date date = (java.util.Date) (report.readObject()); System.out.println("DateTime: " + date); // 5. Read utf string String fileName = report.readUTF(); System.out.println("File name: " + fileName); // Close the stream input.close(); }

You have to read exactly what you wrote.您必须准确阅读您所写的内容。 When you don't, the types don't match up.如果您不这样做,则类型不匹配。 So for example originally when you did ReadDouble, it encountered the persons name, which led to the error with which you started the question.因此,例如,最初当您执行 ReadDouble 时,它遇到了人员姓名,这导致了您开始问题时出现的错误。 The most recent piece was more subtle, because an array of doubles was written, but you were attempting to read (cast) it as an array of integers.最近的一段更微妙,因为编写了一个双精度数组,但您试图将其读取(转换)为一个整数数组。

So we just follow what happened in the writing:所以我们只是按照写作中发生的事情:

// Read from file
        // 1. Read name
        String newName = report.readUTF(); 
        System.out.println("Name: " + newName);
        // 2. Read double array object
        ret = (double[])report.readObject();
        System.out.println("Integers: "+ Arrays.toString(ret));
        // 3. Read double
        double doubleValue = report.readDouble();
        System.out.println("Double value: " + doubleValue); 
        // 4. Read date object
        Date date = (java.util.Date) (report.readObject());
        System.out.println("DateTime: " + date);
        // 5. Read utf string
        String fileName = report.readUTF();
        System.out.println("File name: " + fileName);

Actually,there is a casual problem with the code.实际上,代码有一个偶然的问题。

 int[] newNumbers = (int[]) (input.readObject());

readObject() is a method of class ObjectInputStream in the java.io.ObjectInputStream.ObjectInputStream readObject()是 java.io.ObjectInputStream.ObjectInputStream 中java.io.ObjectInputStream.ObjectInputStream ObjectInputStream的方法

input according to the code is object of Scanner class from the java.util.Scanner package.根据代码input是 object 来自java.util.Scanner

your statement input.readObject() is invalid as it seems to me and should raise:您的声明input.readObject()在我看来是无效的,应该提出:

The method readObject() is undefined for the type Scanner未为 Scanner 类型定义方法 readObject()

And the Solution to the Question is:-问题的解决方案是:-

public class InputFile {



    public File data() throws IOException {
        Scanner scan= new Scanner(System.in);
        String Name="";
        int arr[]=new int[5];
        LocalDateTime mydate=LocalDateTime.now();
        double dou=5.5;
        System.out.println("please enter name");
        Name=scan.next();

         File file = new File("Exercise17_05.dat");
            if(file.createNewFile()){
                System.out.println("file.txt File Created in Project root directory");
            }else 
                System.out.println("File file.txt already exists in the project root directory");

            FileOutputStream fos=new FileOutputStream("Exercise17_05.dat");
            fos.write(Name.getBytes());
            for(int i=0;i<arr.length;i++) {
                System.out.println("please enter an integer numeral for the index:" +i);
                arr[i]=scan.nextInt();
                fos.write(arr[i]);
                }
System.out.println("the array is:::: " +Arrays.toStrings(arr));
            fos.write(mydate.toString().getBytes());
            fos.write(String.valueOf(dou).getBytes());

            return file;

    }
    public static void main(String[] args) throws IOException {
        InputFile data=new InputFile();
        data.data();


    }
}

I'd be glad to hear from you我很高兴收到你的来信

Thank You.谢谢你。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM