0

Original Code - Trying to set each inp to name()

import java.util.Scanner;


class U1_L2_Activity_Two {

    public static void main(String[] args) {
        
        String inp1, inp2, inp3 = name()*3;
        
        System.out.println(String.format("%s\n%s\n%s\n\n%s %s %s", inp1, inp2, inp3, inp3, inp2, inp1));
    }
    public static String name() {
        return new Scanner(System.in).nextLine();
    }
    }

Want something similar to this:

String inp1, inp2, inp3 = name()*3;

Instead of:

String inp1 = name(), inp2 = name(), inp3 = name();
1schware
  • 23
  • 3

3 Answers3

0

You can do something like this:

String inp1, inp2, inp3 = inp2 = inp1 = name();

This isn't the case for strings (since they are immutable), but note that all of them have the same reference, so if you change one you change the others. If you don't want that, you'll need to assign them separately (correct me if I'm wrong). For example:

List<Integer> a, b = a = new ArrayList<>();
a.add(5); // 5 will also be added to b
Higigig
  • 1,175
  • 1
  • 13
  • 25
  • You can't multiply a string – prime Sep 15 '20 at 03:03
  • @prime Sorry, I just copied his code which had *3 in it. – Higigig Sep 15 '20 at 03:05
  • `if you change one you change the others` this part is also wrong. Strings are immutable. And each variable holds the same reference to the same value, but if you change a value of inp1 to `test` then it will create a new string in the string pool to hold `test` and assign that to inp1. And it will not change what's being referred by inp2, inp3 (they are still referred to the old value) – prime Sep 15 '20 at 03:08
  • @prime Sorry, I meant in general objects. I edited my answer. – Higigig Sep 15 '20 at 04:29
0

You can't multiply a String in Java like that (name()*3),

If you do,

String inp1 = name(), inp2 = name(), inp3 = name();

It will call the name() method each time and read a different line.

If you need inp1, inp2, inp3 to be the same value (The value read by a single call to name()) the you have to set the variable after you initialize the inp1, inp2, inp3 values.

String inp1, inp2, inp3;
inp1 = inp2 = inp3 = name();
prime
  • 14,464
  • 14
  • 99
  • 131
0

You can do this

String inp1, inp2, inp3= inp2= inp1= name();

But this will all point to the same instance. It won't cause a problem with final variables or primitive types. this way you can do everything in one line.