generated from hummel/Bank-System
116 lines
2.5 KiB
Java
116 lines
2.5 KiB
Java
package tpe.exceptions.roboter;
|
|
|
|
import java.util.*;
|
|
|
|
import tpe.exceptions.RobotException;
|
|
import tpe.exceptions.RobotIllegalStateException;
|
|
import tpe.exceptions.RobotMagicValueException;
|
|
|
|
public class R2D2 implements Robot {
|
|
private RobotException lastException;
|
|
private String name;
|
|
private boolean powerSwitch;
|
|
private int id;
|
|
StringBuilder sb = new StringBuilder();
|
|
|
|
public R2D2(String name, boolean powerSwitch) {
|
|
super();
|
|
id = createId();
|
|
this.name = name;
|
|
this.powerSwitch = powerSwitch;
|
|
}
|
|
private int createId() {
|
|
Random randomID = new Random();
|
|
return randomID.nextInt(10000);
|
|
}
|
|
@Override
|
|
public int getId() {
|
|
|
|
return id;
|
|
}
|
|
|
|
@Override
|
|
public String getName() {
|
|
return name;
|
|
}
|
|
|
|
@Override
|
|
public void triggerPowerSwitch() {
|
|
if(powerSwitch=false)
|
|
powerSwitch=true;
|
|
else
|
|
powerSwitch=false;
|
|
}
|
|
|
|
@Override
|
|
public boolean isPowerOn() {
|
|
return powerSwitch;
|
|
}
|
|
|
|
public void setLastException(RobotException lastException) {
|
|
this.lastException = lastException;
|
|
}
|
|
|
|
@Override
|
|
public RobotException getLastException() {
|
|
return lastException;
|
|
}
|
|
|
|
@Override
|
|
public String speak(int[] zahlen) throws RobotException {
|
|
|
|
for (int i = 0; i < zahlen.length; i++) {
|
|
sb.append(zahlen[i]);
|
|
if (i < zahlen.length - 1) {
|
|
sb.append(", ");
|
|
}
|
|
}
|
|
|
|
String output = sb.toString();
|
|
return output;
|
|
|
|
}
|
|
|
|
public boolean checkRobotMagicValueException(int[] zahlen) {
|
|
boolean error=false;
|
|
for(int i = 0; i < zahlen.length; i++) {
|
|
if(zahlen[i]==42) {
|
|
error=true;
|
|
}
|
|
}
|
|
return error;
|
|
}
|
|
|
|
@Override
|
|
public int[] think(int[] zahlen) throws RobotException {
|
|
if(!isPowerOn())
|
|
{
|
|
throw new RobotIllegalStateException("Der Roboter ist ausgeschaltet!", this.getName());
|
|
}
|
|
else if(checkRobotMagicValueException(zahlen)==true)
|
|
{
|
|
throw new RobotMagicValueException("Zahl 42 kann nicht verarbeitet werden!",this.getName());
|
|
}
|
|
else {
|
|
// Iterate through zahlen from left to right
|
|
for (int i = 0; i < zahlen.length - 1; i++) {
|
|
// Set the index of the current smallest element to i
|
|
int minIndex = i;
|
|
// Search the smallest element in zahlen
|
|
for (int j = i + 1; j < zahlen.length; j++) {
|
|
if (zahlen[j] < zahlen[minIndex]) {
|
|
minIndex = j;
|
|
}
|
|
}
|
|
// Switch the smallest with the current element
|
|
int temp = zahlen[i];
|
|
zahlen[i] = zahlen[minIndex];
|
|
zahlen[minIndex] = temp;
|
|
}
|
|
return zahlen;
|
|
}
|
|
|
|
}
|
|
|
|
}
|