There is a robot at the origin(0,0). The robot can move in left, right, up and down. You can enter two entries as either "l" or "r" or "u" or "d", these are steps of the robot. Now, you have to make sure that after two entries, the robot is at the origin or not. For example, if you enter "u"+"d" or "l"+"r" , it will be in origin. But if you enter "u"+"u" or "l"+"l", it will not be in the origin.
package abc;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class RobotMove1 {
public static ArrayList<Integer> robotMove(String move1, String move2) {
int x = 0;
int y = 0;
String defaultValue = null;
ArrayList<String> alist = new ArrayList<>();
alist.add(move1);
alist.add(move2);
Iterator<String> itr = alist.iterator();
while(itr.hasNext()){
switch(itr.next()) {
case "u" : y=y+1;
break;
case "d" : y=y-1;
break;
case "r" : x=x+1;
break;
case "l" : x=x-1;
break;
default : defaultValue = "Enter Valid Value";
break;
}
}
//return x, y; //Return does not work this way, to return the two values using arraylist as below
System.out.println("the value of x after case : "+x);
System.out.println("the value of y after case : "+y);
ArrayList<Integer> alist1 = new ArrayList<>();
alist1.add(x);
alist1.add(y);
System.out.println("Checking before calling the method : "+alist1);//[0, 0]
return alist1;
}
//////////// Calling above method here //////////////////////////
public static void main(String[] args) {
Scanner snr1 = new Scanner(System.in);
System.out.println("Enter 1st move");
String move1 = snr1.nextLine();
System.out.println("Enter 2nd move");
String move2 = snr1.nextLine();
//Calling the Method
System.out.println("The output after calling the method : "+RobotMove.robotMove(move1,move2));//The output after calling the method : [0, 0]
//OR
//Calling method in a different way
ArrayList<Integer> finalList = RobotMove.robotMove(move1,move2);/////This
//OR
ArrayList<Integer> finalList1 = new ArrayList<>();
finalList1 = RobotMove.robotMove(move1,move2); ////////This
int xCoordinate = finalList.get(0);
int yCoordinate = finalList.get(1);
int xCoordinate1 = finalList1.get(0);
int yCoordinate1 = finalList1.get(1);
System.out.println("Just to check if above calling working or not : "+xCoordinate+" "+yCoordinate+" "+xCoordinate1+" "+yCoordinate1);//Just to check if above calling working or not : 0 0 0 0
if((xCoordinate==0)&&(yCoordinate==0)){
System.out.println("The object is at the origin");
} else {
System.out.println("The object is NOT at the origin");
}
}
}
Output:
Enter 1st move
u
Enter 2nd move
d
Checking before calling the method : [0, 0]
Just to check if above calling working or not0 0 0 0
The object is at the origin
No comments:
Post a Comment