简体   繁体   English

Java - 转换用户的输入,其中包含整数和双精度数组

[英]Java - Casting user's input, which contains both integers and doubles into an array

I'm brand new to Java. 我是Java的新手。 At the moment I have been given the problem of casting a 3-by-4 array using a user's input of specific numbers as follows: 2.6 5.1 6 8 5.4 4.4 7 1 9.5 7.9 2 3 目前我已经遇到了使用用户输入的特定数字投射3乘4阵列的问题,如下所示:2.6 5.1 6 8 5.4 4.4 7 1 9.5 7.9 2 3

Right now, I have got it to work solely for integers, and structured it as such, as I cannot wrap my head around multiple inputs from the user. 现在,我已经让它只为整数工作,并将其结构化,因为我无法绕过用户的多个输入。

What I have if I just use integers (Such as 5 instead of 5.1, and 2, instead of 2.6 etc.) is as follows: 如果我只使用整数(例如5而不是5.1,而不是2.6等),我有以下内容:

    int row, col;
    int i, j;
    int data[][] = new int[4][3];


    col = 3;
    row = 4;

    Scanner scan = new Scanner(System.in);
    // enter array elements.
    System.out.println("Enter the provided Array Elements : ");
    //Works with integers as input only at the moment.

    for(i=0; i<row; i++)
    {
        for(j=0; j<col; j++)
        {
            data[i][j] = scan.nextInt();
        }
    }

What I would like is to convert all of the user's input to read as a double data type, and cast the double data types into the array. 我想要的是将所有用户的输入转换为双数据类型,并将双数据类型转换为数组。

Any insight on how to cast them would be greatly appreciated. 任何关于如何投射他们的见解将不胜感激。 Thanks! 谢谢!

You can't cast arrays in java like you'd probbaly expect. 您不能像在probbaly期望的那样在java中强制转换数组。 For example, you aren't allowed to do the following operations: 例如,您不允许执行以下操作:

int[] i = new int[0];
double[] d = (double[]) i;

This means, you need to declare your array simply as double[] and replace scan.nextInt() with scan.nextDouble() and that's it. 这意味着,您需要将数组声明为double []并将scan.nextInt()替换为scan.nextDouble() ,就是这样。

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

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