Java: How do I store a vector in another vector and using Math library

Asked

Viewed 940 times

-2

my doubt is the following, I have to read 20 integer numbers in one vector and then I have to compute the square of that vector and store in another and then display the two.

But when it comes to square I use a java library that is Math the code is like this at the time of calculating:

import java.util.Scanner;

public class Exercicio01Lista { 
   public static void main(String[] args) { 
      int [] num = new int[5]; 
      int [] num2 = new int[5]; 
      Scanner entrada = new Scanner(System.in); 
      for (int c = 0; c<num.length; c++) { 
         System.out.println("Numero: "); 
         num[c] = entrada.nextInt(); 
      } 
      for (int i = 0; i<num2.length; i++) { 
         num2[i] = Math.sqrt(num[c]); 
      } 
   } 
}

only that it is giving error.

  • Would this variable c be a counter? matrices one and num2 have the same size? Post more lines of code! What error happens?

  • The variable c is the counter of the first vector, they have the same size. the code: import java.util.Scanner; public class Exercicio01list { public Static void main(String[] args) { int [] num = new int[5]; int [] num2 = new int[5]; Input scanner = new Scanner(System.in); for (int c = 0; c<num.length; c++){ System.out.println("Number: "); num[c] = input.nextInt(); } for (int i = 0; i<num2.length; i++){ num2[i] = Math.sqrt(num[c]); } } }

  • Then take out this counter that is not needed. Put a[i] in place.

  • put i in place of num[i] and it hasn’t worked yet, the error is this one: Exception in thread "main" java.util.Inputmismatchexception at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at exercicio01lista.Exercicio01lista.main(Exercicio01lista.java:15) C: Users Bruno Appdata Local Netbeans Cache 8.2 executor-snippets run.xml:53: Java returned: 1 BUILD FAILURE (total time: 9 seconds)

  • Without knowing what the numbers are, what the size of each vector is and what error is occurring, we have no way of guessing. I suggest you read the [Ask] page, how to mount a [mcve] and the Manual on how not to ask questions. Then click on [Edit] and add the missing information, because only with this code and without knowing what the error is, we have no way to help. Something else, the sqrt returns the square root. If you want the square, use Math.pow(valor, 2) (or just multiply the value by itself)

  • Use the link [Edit] to put this information in the question, is more readable than in the comments

  • The error message mentions Scanner.nextInt, and if he made a mistake it is because he expected a number but was provided something else. Please put the code that has the Scanner and the data he’s reading

Show 2 more comments

4 answers

0

You can do a for that traverses your array and stores n² in the new array like this:

for (int i = 0; i<arrayValores.length, i++){
   int arrayQuadrado[i] = pow(arrayValores[i],2);
}
  • Missed the Math. before the pow. Moreover, Math.pow returns double.

0

The variable c is only visible in the first for, but since arrays have the same size you can use the variable i for the two arrays.

    public static void main(String[] args) {
        int[] num = new int[5];
        int[] num2 = new int[5];

        Scanner entrada = new Scanner(System.in);

        for (int c = 0; c < num.length; c++) {
            System.out.println("Numero: ");
            num[c] = entrada.nextInt();
        }

        for (int i = 0; i < num2.length; i++) {
            num2[i] = (int) Math.pow(num[i], 2);
        }

        entrada.close();
    }
  • Now I understood, I was putting the int before the num2[i] and not after. thank you very much! , by the way I leave here my thanks to everyone

  • 1

    entrada.close();

  • Any questions about that line?

  • 1

    https://stackoverflow.com/q/14142853/540552

  • Test the code. This way it doesn’t matter if the stream is closed. It’s being closed at the end of the application.

  • 1

    Explain to me the purpose of closing the System.in? For that is what will happen when the Scanner.

  • If it closes this flow input anywhere else, whether in another method or class, it will have an Exception, java.util.Nosuchelementexception, when trying to use the input variable in the main method, because System.in will be closed. But that’s not the case.

Show 2 more comments

0

Using Java 8+, you can generate the array with the squares in a single row. Assuming your array is the variable numeros, then you can do it:

int[] quadrados = IntStream.of(numeros).map(x -> x * x).toArray();

To read the 20 numbers, you can also do it with two lines:

Scanner entrada = new Scanner(System.in);
int[] numeros = IntStream.generate(entrada::nextInt).limit(20).toArray();

To display the array, you can do it in a row as well:

System.out.println(Arrays.toString(quadrados));

Here is the resulting complete code. Note that it is very simple, only needs 5 lines between the { and the } of the method main:

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

class Teste {
    public static void main(String[] args) {
        Scanner entrada = new Scanner(System.in);
        int[] numeros = IntStream.generate(entrada::nextInt).limit(20).toArray();
        int[] quadrados = IntStream.of(numeros).map(x -> x * x).toArray();
        System.out.println(Arrays.toString(numeros));
        System.out.println(Arrays.toString(quadrados));
    }
}

Given this input:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

This output is produced:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]

See here working on ideone.

Ah, Math.sqrt(...) is to compute the square root. To compute the square, the simplest way is to multiply each element by itself as in the code above. Note that the code to create the array with the squares works regardless of the size of the original array.

If you want a message to appear to ask for the number, you can do something like this:

int[] numeros = IntStream.generate(() -> {
    System.out.println("Digite um número: ");
    return entrada.nextInt();
}).limit(20).toArray();
  • It is important to close the reading scan. Or you can use java.close() or Try with Resources input. And to be more intuitive you need to ask the user to enter something. A message like System.out.println("Enter a number: ");

  • 1

    @Antoniosantos On the Scanner, no: https://stackoverflow.com/q/14142853/540552 - About the message, the questioner did not put any of this in his question.

  • The author of the message does not use Stream API. The question is whether to use for. He needs to understand the use of for before going to something like Stream API. It is good to know the forms but if the previous step is understood and the next step is explained.

  • 1

    @Antoniosantos From what I see in the first paragraph of the question, he asked how to create a vector based on another vector, he didn’t say it had to be with for. He just tried to do it with a for using the Math.sqrt.

  • And he needs to know where the bug is, based on the code he’s using, even though it’s important to know about using the Stream API.

-3

int exchange for double.

int [] num = new int[5]; double [] num2 = new double[5];

     Scanner entrada = new Scanner(System.in); 
     
      for (int i = 0; i < num.length; i++) { 
         System.out.println("Numero: "); 
         num[i] = entrada.nextInt(); 
      } 
      for (int i = 0; i<num2.length; i++) { 
         num2[i] = Math.sqrt(num[i]); 
      } 
      
      for (int i = 0; i<num2.length; i++) { 
          System.out.println("A raiz quadrada do número "+num[i]+" é "+num2[i]);
      } 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.