P
P
PRAIT2019-02-13 02:49:26
Java
PRAIT, 2019-02-13 02:49:26

Conciseness and correctness of code in Java. When should you declare variables in your code?

Hello guys, it's a simple easy task. You need to write Java code that will display Name, patronymic, year, birth = First name, age in the console.
But I asked myself this question, there are two options that I know by which I can implement the idea.
1. This is to write all the values ​​\u200b\u200bat once, as in this option, then write them again.

package test;
import java.util.Scanner;
public class Test {
  public static void main(String[] args) {
    Scanner tu = new Scanner(System.in);
    String name;
    String surName;
    int yearBorn;
    int yearNow;
    System.out.println("Ваше имя:");
    name = tu.nextLine();
    System.out.println("Вашe отчество:");
    surName = tu.nextLine();
    System.out.println("Какой сейчас год?");
    yearBorn = tu.nextInt();
    System.out.println("В каком году вы родились?");
    yearNow = tu.nextInt();
    System.out.println("Здравствуйте "+name+" "+surName+"!");
    System.out.println("Ваш возраст "+(yearBorn-yearNow)+"");
  }
}

Or in this version.
package test;
import java.util.Scanner;
public class Test1 {
  public static void main(String[] args) {
    System.out.println("Ваше имя:");
    String name = new Scanner(System.in).nextLine();
    System.out.println("Ваше отчество");
    String surName = new Scanner(System.in).nextLine();
    System.out.println("Какой сейчас год?");
    int yearBorn = new Scanner(System.in).nextInt();
    System.out.println("В каком году вы родились?");
    int yearNow = new Scanner(System.in).nextInt();
    System.out.println("Здравствуйте "+name+""+surName+"!");
    System.out.println("Ваш возраст "+(yearBorn-yearNow)+"");
  }
}

I understand that the question is slightly stupid and you can implement it this way and that, but still I would like to know how best to write, according to the first or second option? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Iloveski, 2019-02-13
@PRAIT

Not like that, not like that. You create the scanner at the beginning 1 time. And it is better to declare variables closer to the place of use and immediately assign values ​​to them using 1 and the same scanner.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question