简体   繁体   English

如何获得用户输入中给出的位数

[英]How to get number of digits given in the user input

if user is asked to enter the coefficients of variables for an equation and the number of variables is unknown for example 例如,如果要求用户输入方程式的变量系数,并且变量数未知

enter coefficients of equation 1 : 3 4 9 6
enter coefficients of equation 2 : 3 7 8 1 2

so how to know number of coefficients entered so we can use them in loop to create matrix and how to extract each digit into double in order to create a matrix like this form 所以如何知道输入的系数的数量,以便我们可以在循环中使用它们来创建矩阵,以及如何将每个数字提取为双精度以创建像这种形式的矩阵

3.0 4.0 9.0 6.0
3.0 7.0 8.0 1.0 2.0

ie if I want to create matrix with these coefficients how i can know the number of variables ie times of iterations. 即,如果我想用这些系数创建矩阵,我如何知道变量的数量,即迭代次数。

for(int i=0; i<? ; i++)
{
  for(int j=0; j<? ; j++)
  //create the matrix

}

Use String.split and iterate over its elements: 使用String.split并遍历其元素:

Example: 例:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("enter coefficients of equation 1 :");
    String l1 = scan.nextLine();
    String[] elementL1 = l1.split(" ");
    System.out.println(elementL1.length);
    for (int i = 0; i < elementL1.length; i++) {
        System.out.println("Element "+ elementL1[i]);

    }
}

and do the same for the equation 2 对方程式2做同样的事情

Split input coefficients by space char, then create matrix 用空格字符分割输入系数,然后创建矩阵

something like that 这样的东西

String[] numbers1 = line1.split("\s")
String[] numbers2 = line2.split("\s")

double [][] arr = new double[numbers1.length][numbers2.length]

then fill with values: 然后填充值:

for (int i; i < numbers1.length; i++) {
    for (int j; j < numbers2.length; j++) {
        // do something
    }
}

how to know number of coefficients entered? 如何知道输入的系数数量? you can put the "3 4 9 6" into an array ,them split it by blank" ".you will get int[] coefficients.Then the number you want is coefficients.length 您可以将“ 3 4 9 6”放入一个数组中,然后用空格“”将其分割。您将获得int []系数。那么您想要的数字就是系数。

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

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