A
A
AlexWD2021-06-04 18:04:49
Java
AlexWD, 2021-06-04 18:04:49

Can't solve the problem?

Please help with the solution of the problem:
Task:
Write a method that executes the
commands encoded in the string. Initial number 0.
Signature: List getResult(final String input)
The input is a string containing only 4 types of characters:
i - increase the number by one;
d - decrease the number by one;
s - square the number;
o - add a number to the output list.
Example:
Input: "iiisdoso"
Output: {8, 64}

In JS, the solution is simple:

function Test(str) {
  let output = [], a = 0;
  for(let i = 0; i < str.length; i++) {
  	if(str[i] === 'i') a += 1;
    if(str[i] === 'd') a -= 1;
    if(str[i] === 's') a = Math.pow(a, 2);
    if(str[i] === 'o') output.push(a);
  }
  return output;
}
console.info(Test('iiisdoso'));

But to turn it into Java, I don't have enough brains for something.
From my attempts here:
package com.company;

public class Main {

    public static int[] main(String[] args) {
        int output[], a = 0, str[];
        for (int i = 0; i < str.length(); i++) {
            if(str[i] == 'i') {
                a += 1;
            };
            if(str[i] == 'd') {
                a -= 1;
            }
            if(str[i] == 's') {
                a += 2;
            }
        }
        return output;

        System.out.println("iiisdoso");
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-06-04
@zagayevskiy

Well, you could at least rewrite the JS into Java directly, and make the signature the way it should be.
Why is your str not a string, but an array?
Why doesn't str come from outside?
Since when does +=2 raise to a power?
Where is the addition to the list?
Where is the list itself, if you declared an array?
Why do you have main returns not the return code, but the result of the calculation?
What for at you after return of value from a method something happens?
Why are you writing your test string to the console?
Almost all questions are not specific to Java.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question