0

I apologize if this is a very basic question, but this is my first week in java (mostly python backround).

I want to assign a value "something" to to variables: x and y.

Within the console I want to be able to explicitly say x = some number and y = some number so that the order does not matter in which I am inputting the numbers.

So it could be:

x = some number 
y = some number 

or

y = some number 
x = some number 

I need to be able to assign a value to a variable when running the code.

How would I accomplish this?

MAO3J1m0Op
  • 423
  • 3
  • 14
John
  • 29
  • 5

3 Answers3

0

In Java, variables must have a type declared with them, and the variable is only allowed to store values of a specific type. You can declare variables like so:

String x;
String y;

And then assign the values to them:

x = "something";
y = "some other value";

However, you can only assign Strings to x and y. Assigning any other type (an int for example) will generate a compiler error.

MAO3J1m0Op
  • 423
  • 3
  • 14
  • Ok, so I cannot put " x = 3 and y = 2 " and the variables x and y will now have the values x = 3 and y = 2? – John Sep 11 '19 at 01:05
  • 1
    Yes. You cannot. But it is possibleto put x= "3" and y = "2". To use the integer values, you need to use Integer.parseInt(x); or Integer.parseInt(y); – Kavitha Karunakaran Sep 11 '19 at 04:44
0

I think you do something like this,as long as the first character is always the variable name,try this.

Scanner scan = new Scanner(System.in);
String in = scan.nextLine();
int x;
int y;
if(in.charAt(0)=='x'){
   x = Integer.parseInt(in.substring(5));
   in = scan.nextLine();
   y = Integer.parseInt(in.substring(5));
else{
   y = Integer.parseInt(in.substring(5));
   in = Integer.parseInt(scan.nextLine());
   x = Integer.parseInt(in.substring(5));
}
0

You can define a variable as an Object.

    Object x = "some string";
    x = 3;

But you should learn more about java type system. Because you can not using mathematical operators without a type cast. And the misunderstood can cause a memory leak.

    Object x = "some string";
    x = 3;
    x = x + 1; // error 
    x = (Integer)3 +1; //Can cause memory leak

    //bellow code is Ok. But it is complex. (Hard to read and a bit slower than usual).
    x = new Integer(3);
    x = new Integer((Integer)3 +1);

So the better solution for your case is to use 2 difference variables.

Esc Điệp
  • 346
  • 2
  • 8