D
D
Dmitry Stoyanov2016-02-25 22:22:53
Java
Dmitry Stoyanov, 2016-02-25 22:22:53

Java. Why does the class variable change?

I can not understand why the class variable changes, although it does not participate in sorting at all.
An explanation is needed on this example, because. rewrite so that I can work.

package cesar;

import java.io.PrintStream;
import java.util.Scanner;

public class Cesar {

  private static Scanner sc = new Scanner(System.in);
  private static PrintStream pr = new PrintStream(System.out);
  private static char[] alphabet;
  private static char[] revAlphabet;

  static
  {
    alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ".toLowerCase().toCharArray();
    revAlphabet = getReverseAlphabet();
  }

  public static void main(String[] args) {
    
  }

  private static char[] getReverseAlphabet() {
    int step = 3;
    char[] rev = alphabet;

    for (char c : alphabet)             //test 1
    {
      pr.print(c);
    }
    pr.println();

    for (int i = 0; i < step; i++)
    {
      for (int k = 0; k < rev.length-1; k++)
      {
        char temp = rev[k];
        rev[k] = rev[k+1];
        rev[k+1] = temp;
      }
    }

    for (char c : alphabet)             //test 2
    {
      pr.print(c);
    }
    return rev;
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Timur Sergeevich, 2016-02-25
@stoyanovdmitry

private static char[] alphabet ?? she is?

char[] rev = alphabet; // копируете ссылку на массив. 

//

        char temp = rev[k];
        rev[k] = rev[k+1]; // тут rev[k] то же самое что и alphabet[k] 
        rev[k+1] = temp;

char[] x = {'a','b','c'}; //создаете массив и присваеваете ссылку на массив.
char[] y;
char[] z;

z = y = x;

Sistem.out.prinln(z[0]); // a
System.out.prinln(y[1]); // b
z[2] = 'm';
System.out.println(y[2]); // m
System.out.println(x[2]); // m

See more here

S
Sergey, 2016-02-25
@bogdanov-s

char[] rev = Arrays.copyOf(alphabet, alphabet.length);

A
alexfacepalm, 2016-02-26
@alexfacepalm

If you need to decide the caesar encoding, then increment each element by 1 (or your step=3)
for (int k = 0; k < rev.length1; k++) {
rev[k] += 1;//rev[k] += 3;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question