简体   繁体   中英

How to take inputs in different variables in one line of code in Java?

Suppose in a Java code,

{        
double a, b, c;      
Scanner sc = new Scanner(System.in);    
a = sc.nextDouble();      
b = sc.nextDouble();      
c = sc.nextDouble();   
}

Since sc.nextDouble(); is common to all the variables, what can I do to reduce the lines of code (without using array)?

When people say "reduce the number of lines", the fatuous answer is just to remove all the line breaks, because newlines have no semantic meaning anyway.

But what I think you might mean is "reduce the number of statements ".

You can express the body of this block in just two statements, by declaring the variables and assigning them in a single statement:

Scanner sc = new Scanner(System.in);    
double a = sc.nextDouble(),
       b = sc.nextDouble(),
       c = sc.nextDouble();

But there's no real advantage in doing this, as it doesn't actually reduce the duplication substantially; and style guides such as Google's Java style guide actively forbid declaring multiple variables in a single statement.

If you don't actually need them in separate variables, you could use an array:

double[] ds = new double[3];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; ++i) ds[i] = sc.nextDouble();

but whilst this stops you repeating the sc.nextDouble() s, you have to introduce the loop gubbins instead.

What you had already was fine. The only thing I would change would be to declare and initialize the variables at the same time.

Scanner sc = new Scanner(System.in);    
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();

If you are really bent on only writing sc.nextDouble() once, you could use an enum with an instance variable of type double set when the enum is initialized.

public enum DoubleExample {
    A, B, C;   
    public final double value;
    private DoubleExample() { value = new Scanner(System.in).nextDouble(); }
}

Of course, if you use this solution, the values of A , B , and C can't be modified after creation. Also, since a separate Scanner is used for each double assignment, each double must be entered on a new line, and some resources are leaked for each variable initialized.

Here's a gist with a full runnable example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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