can't catch Exception - java

When I start my tests I want to see an Exception, but programm just stay on the one line "mobileTelephony.driver" and don't throught exception. I don't understand why?
#Test(groups = {"non-basic"})
#Parameters({"idCategory"})
public void checkSearchForm(int idCategory) throws InterruptedException {
String categoryName;
int location = 1;
StackOfCategories sub1Stack = TestSuiteMobileTelephony.sub1Stack;
boolean isItSubCategory;
basePage.getBasePage();
basePage.clickCategoryName(idCategory);
MobileTelephonyPage mobileTelephony = PageFactory.initElements(basePage.driver, MobileTelephonyPage.class);
while (location <= 3) {
mobileTelephony.clickChangeLocation(location);
for(int i = 1; i <= sub1Stack.size(); i++) {
if (location == 1) {
categoryName = sub1Stack.getCategory(i).getNameEn();
} else if (location == 2) {
categoryName = sub1Stack.getCategory(i).getNameRu();
} else {
categoryName = sub1Stack.getCategory(i).getNameUk();
}
mobileTelephony.writeInSearchFormAndClick(categoryName);
try {
mobileTelephony.driver.findElement(By.xpath(".//div[#id='breadcrumbs']/span1"));
} catch(Exception e){
e.printStackTrace();
mobileTelephony.back();
}
isItSubCategory = true;
AssertMessage.assertTrueNavigateSubCategory(categoryName, isItSubCategory);
mobileTelephony.back();
}
location++;
}
}
Mobail Telefony code
public class MobileTelephonyPage extends BasePage {
public void clickAndWriteNumber(String number) throws AWTException {
String[] numsArray = number.split("");
number1.clear();
number1.click();
Robot robot = new Robot();
// Constryction
for(int i = 0; i < numsArray.length; i++) {
switch(Integer.parseInt(numsArray[i])) {
case 0 :
robot.keyPress(KeyEvent.VK_0);
break;
case 1 :
robot.keyPress(KeyEvent.VK_1);
break;
case 2 :
robot.keyPress(KeyEvent.VK_2);
break;
case 3 :
robot.keyPress(KeyEvent.VK_3);
break;
case 4 :
robot.keyPress(KeyEvent.VK_4);
break;
case 5 :
robot.keyPress(KeyEvent.VK_5);
break;
case 6 :
robot.keyPress(KeyEvent.VK_6);
break;
case 7 :
robot.keyPress(KeyEvent.VK_7);
break;
case 8 :
robot.keyPress(KeyEvent.VK_8);
break;
case 9 :
robot.keyPress(KeyEvent.VK_9);
break;
}
}
}
public MobileTelephonyPage(WebDriver driver) {
super(driver);
}
public int getHeightImg(int number) {
int height = driver.findElement(By.xpath("(.//div[#class='icon']/img)[" + number + "]")).getSize().getHeight();
return height;
}
public int getWidthImg(int number) {
int width = driver.findElement(By.xpath("(.//div[#class='icon']/img)[" + number + "]")).getSize().getWidth();
return width;
}
public MobileTelephonyPage back() {
driver.navigate().back();
return this;
}
public String getCurrentURL() {
return driver.getCurrentUrl();
}
public void clickOperator(String linkText) {
driver.findElement(By.linkText(linkText)).click();
}
}
in debug program stop in the next snipet of code(class HttpCommandExecutor)
this.log("profiler", new HttpProfilerLogEntry(command.getName(), true));
HttpResponse e = this.client.execute(httpRequest, true);
this.log("profiler", new HttpProfilerLogEntry(command.getName(), false));

No Exception is thrown.
Probably the code needs a long time to be executed or it is in a livelock.
A livelock is a situation when a function is executed but never ends. For example because in a for loop you loose to update a variable so the test is always true
Edited after new informations
From the javadoc of WebDriver:
This method is affected by the 'implicit wait' times in force at the
time of execution. The findElement(..) invocation will return a
matching row, or try again repeatedly until the configured timeout is
reached. findElement should not be used to look for non-present
elements, use findElements(By) and assert zero length response
instead.
As you can see the the function could not returns exactly as mentioned on the first two lines of my post.

Related

Method that doesn't allow more participants than the maximum and same number of registration

I have a issue here. I need to create this method:
Method: registraParticipante (Aluno alu) that will receive by parameter one
student(Aluno) and add to the participant(participante) array. The method should also implement the following rules:
control not to allow more participants to register which was defined in the attribute: Maximum number of participants(qtMaxParticipantes);
not allow registration of a participant who has the same number of registration(int matricula) of an already registered participant.
I have the superclass Usuario (means User) with the int matricula in it
and the subclass Aluno (means student)
PROBLEM SOLVED - Thanks Andre.
public void registraParticipante(Aluno alu) {
if (!matriculaJaExistente(alu))
{
for (int i = 0; i < listaDeParticipantes.length; i++)
{
if (listaDeParticipantes[i] == null)
{
listaDeParticipantes[i] = alu;
break;
} else {
System.out.println("Número maximo de participante atingido.");
}
}
} else {
System.out.println("Aluno já matriculado.");
}
}
public boolean matriculaJaExistente(Aluno a)
{
boolean resultado = false;
for (int i = 0; i < listaDeParticipantes.length; i++)
{if (listaDeParticipantes[i].getMatricula() == a.getMatricula())
{
resultado = true;
}
else
{
resultado = false;
}
}
return resultado ;
}
I don't know if you necessarily have to use an array, so I guess that using a List would be the best solution, than, your code would look like this:
List<Aluno> alunosList = new ArrayList();
private int maxParticipantes = 5; // arbitrary number
public void registraParticipante(Aluno a) {
if (alunosList.size() > maxParticipantes || alunoJaRegistrado(a)) {
System.out.println("Can't add this aluno");
} else {
alunosList.add(a);
}
}
public boolean alunoJaRegistrado(Aluno aluno) {
boolean result;
for (Aluno a : alunosList) { // this goes through each aluno on the list
if (a.getMatricula() == aluno.getMatricula) {
result = true;
break;
} else result = false;
}
return result;
}

How to process large DefaultStyledDocument and catch a cancel event?

I have a JTextPane with an extended DefaultStyledDocument. Updating the document takes about 2 minutes. Currently I am breaking it up into steps and updating on the swing thread with InvokeAndWait for each step. I have a progress bar and a cancel button. The cancel button only triggers when there is a break between steps. Each step takes about 10 seconds so I need to wait up to 10 seconds to stop the processing of the document. Is there anyway to make this more responsive? I am displaying a JFrame with the JTextPane in a JScrollPane when it is done. When it is finally rendered the scroll is very responsive and I can view the whole document. I do not want to display the JFrame until the document is updated yet I want to continue to show the progress of the update. Any ideas on how to update the document and have Swing and/or the cancel button more responsive?
====== Edit in response to comments ======
In styled document using the append(text) method - setting styles for each line before appending.
public void append(String text)
{
append(text, textStyle, paragraphStyle);
}
public void append(String text, Style ts, Style ps)
{
try
{
int start = this.getLength();
int end = this.getLength()+text.length();
this.insertString(start, text, ts);
this.setParagraphAttributes(start, end, ps, true);
}
catch (BadLocationException e)
{
LOG.log(Level.SEVERE, "Bad location in append", e);
}
}
======== Edit ========
This is what my document update method looks like.
public void writeTextOutsideOfSwing(StatusDialog status, float statusPercentage)
{
final StringBuilder letter = new StringBuilder();
final ArrayList<IndexTextEntry>list = new ArrayList<>();
LOG.log(Level.INFO, "Updating document: {0}", entries.length);
setText("");
int step = (int)((status.getMaximum() * statusPercentage) / (double)entries.length);
for(int j = 0; j < entries.length; j++)
{
if(status.cancel) break;
final int index = j;
list.add(entries[j]);
if(list.size() == 100 || index == entries.length -1)
{
int first = index - list.size() + 2;
int last = index + 1;
status.setStatusBarText("Writing Concordance: Processing " + first + " - " + last + " of " + entries.length);
try
{
SwingUtilities.invokeAndWait(()->
{
for(int k = 0; k < list.size(); k++)
{
int i = index-list.size() + k;
if(!letter.toString().equals(list.get(k).getSortLetter()))
{
letter.setLength(0);
letter.append(list.get(k).getSortLetter());
String title = list.get(k).getSortLetterTitle(letter.toString());
appendLetter(title, i == 0);
}
else if(i > 0)
{
if(cf.getLineBetweenEntries())
{
clearTextAreaStyles();
setFontSize(cf.getLineBetweenEntriesFontSize());
append(" \n");
}
}
float indent = appendEntry(0, list.get(k));
appendSubEntries(indent, list.get(k));
}
});
}
catch(InterruptedException | InvocationTargetException ex)
{ LOG.log(Level.SEVERE, "Writing Concorder Interrupted", ex); }
list.clear();
}
status.increment(step);
}
LOG.info("Done updating docuemnt");
}
And these methods go with the write method:
private void appendSubEntries(float indent, IndexTextEntry entry)
{
for (IndexTextEntry subEntry : entry.getSubEntries())
{
float ind = appendEntry(indent, subEntry);
appendSubEntries(ind, subEntry);
}
}
private float appendEntry(float indent, IndexTextEntry entry)
{
setFontFamily(cf.getWordFormat().getFontFamily());
setFontSize(cf.getWordFormat().getFontSize());
setFontBold(cf.getWordFormat().getBold());
setFontItalic(cf.getWordFormat().getItalic());
switch (cf.getWordFormat().getAlignment())
{
case TextFormat.ALIGN_CENTER:
setFontAlignment(EnhancedTextArea.ALIGN_CENTER);
break;
case TextFormat.ALIGN_RIGHT:
setFontAlignment(EnhancedTextArea.ALIGN_RIGHT);
break;
default:
setFontAlignment(EnhancedTextArea.ALIGN_LEFT);
break;
}
float wi = indent + cf.getWordFormat().getIndentJAVA();
setLeftIndent(wi);
setFontColor(cf.getWordFormat().getColor());
append(entry.getConcordance().getTitle());
append("\n");
float li = 0;
for(ConcordanceLine line : entry.getConcordance().getLines())
li = appendLine(wi, line);
return li;
}
private float appendLine(float indent, ConcordanceLine line)
{
setFontFamily(cf.getLineFormat().getFontFamily());
setFontSize(cf.getLineFormat().getFontSize());
switch (cf.getLineFormat().getAlignment())
{
case TextFormat.ALIGN_CENTER:
setFontAlignment(EnhancedTextArea.ALIGN_CENTER);
break;
case TextFormat.ALIGN_RIGHT:
setFontAlignment(EnhancedTextArea.ALIGN_RIGHT);
break;
default:
setFontAlignment(EnhancedTextArea.ALIGN_LEFT);
break;
}
float li = indent + cf.getLineFormat().getIndentJAVA();
setLeftIndent(li);
setFontColor(cf.getLineFormat().getColor());
setFontBold(cf.getPageBold());
setFontItalic(cf.getPageItalic());
append(line.page + " ");
setFontBold(cf.getLineBold());
setFontItalic(cf.getLineItalic());
append(line.lead);
setFontBold(cf.getWordBold());
setFontItalic(cf.getWordItalic());
append(line.word);
setFontBold(cf.getLineBold());
setFontItalic(cf.getLineItalic());
append(line.trail);
append("\n");
return li;
}
ALL VARIABLES are resolved before get methods

Java: Using created string as loop parameter?

In short, the user will input a number (say 1 through 3). This will decide which range of numbers the loop should search through.
switch(input){
case 1:
searchTerm = "i<10 && i>5";
case 2:
searchTerm = "i>=10 && i<19";
case 3:
searchTerm = "i>19 && i<24";
}
while(searchTerm){
//some function
}
Is this possible? I I've not been able to find a way to use a string as search parameters.
EDIT: I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters? For example:
case 1:
searchTerm = "i<5"
case 2:
searchTerm = "i>25 && i<29"
case 3:
searchTerm = "(i<50 && i>25) && (i>55 && i<75)"
case 4:
searchTerm = "(i<20 && i>15) && (i>300 && i<325) && (i>360 && i<380)
Then how does one do it? Multiple loops that call the same function?
The correct way to do this is to not use a string at all:
int min, max;
switch(input){
case 1: // i<10 && i>5
min = 6;
max = 10;
break; // to avoid follow-through to the next case
case 2: // i>=10 && i<19
min = 10;
max = 20;
break;
case 3: // i>19 && i<24
min = 20;
max = 25;
break;
default:
// You need something here in case the value entered wasn't 1-3
}
for (int i = min; i < max; ++i) {
// ...
}
Re your edit:
I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters?
In that case, you'll have to use an expression evaluator (or write one, which is a non-trivial task). There's one in Spring, for instance (not recommending, just happened to hear about it). A search for "Java expression evaluator" should turn up some options.
Another alternative, which is somewhat amusing given that some folks mistook your question for a JavaScript question, is to use the JavaScript evaluator built into Java (either Rhino or Nashorn). E.g.: Live Example
import javax.script.*;
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
String searchTerm = "i >= 19 && i <= 24";
int i;
try {
i = 19;
engine.put("i", i);
while ((boolean)engine.eval(searchTerm)) {
System.out.println("i = " + i);
++i;
engine.put("i", i);
}
System.out.println("Done");
} catch (ScriptException scriptException) {
System.out.println("Failed with script error");
}
}
}
...but you'll still have the problem of determining what initial value to use for i, which I've hardcoded above.
In Java 8 you can select a lambda instead of String:
Predicate<Integer> searchTerm = (Integer v) -> false;
switch (input) {
case 1:
searchTerm = (Integer v) -> v < 10 && v > 5;
break;
case 2:
searchTerm = (Integer v) -> v >= 10 && v < 19;
break;
case 3:
searchTerm = (Integer v) -> v > 19 && v < 24;
break;
}
while (searchTerm.test(i)) {
...
}
You can create an enumeration as below.
public enum SearchTerms {
None(""),
Between6And9("i<10 && i>5"),
Between10And18("i>=10 && i<19"),
Between20And23("i>19 && i<24");
private final String stringValue;
SearchTerms(String stringValue) {
this.stringValue = stringValue;
}
public String getStringValue() {
return stringValue;
}
public static SearchTerms fromStringValue(String stringValue) {
for (SearchTerms searchTerm : values()) {
if (searchTerm.getStringValue().equalsIgnoreCase(stringValue)) {
return searchTerm;
}
}
return SearchTerms.None;
}
}
Usage:
SearchTerms searchTerm = SearchTerms.fromStringValue("i<10 && i>5");
switch(searchTerm) {
case Between6And9:
//dosomething
break;
}
You can use .eval() of JavaScript.
Also don't forget break; at the end of each case:
Check out this fiddle.
Here is the snippet.
function test(input, i) {
switch (input) { //input=1
case 1:
searchTerm = "i<10 && i>5"; //this will be 'searchTerm'
break;
case 2:
searchTerm = "i>=10 && i<19";
break;
case 3:
searchTerm = "i>19 && i<24";
break;
}
while (eval(searchTerm)) { //'searchTerm' converted to boolean expression
alert(i); // alert for i=7,8,9
i++;
}
}
test(1, 7); //pass input=1 and i=7

" character is not getting typed in my auto-typer program

This program reads from a file and types its contents out line by line or at the ends of sentences depending on config settings. It uses Java.awt.Robot to do this, and all the keyboard characters can be typed except the apostrophe and quotation characters. The key is function on my keyboard and other scripts can type it. I can't figure out why this program cannot type it correctly.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class SmartRobot extends Robot {
public int count70=0;
public SmartRobot() throws AWTException {
super();
}
public void keyType(int keyCode) {
if(keyCode == -1)
return;
keyPress(keyCode);
delay(2);
keyRelease(keyCode);
}
public void keyType(int keyCode, int keyCodeModifier) {
keyPress(keyCodeModifier);
keyPress(keyCode);
delay(2);
keyRelease(keyCode);
keyRelease(keyCodeModifier);
}
public void type(String text) {
if(text.length()>1 && text.substring(0, 1).equals("\\")){
Driver.codeTimeEnd = System.nanoTime();
delay(Integer.parseInt(text.substring(2, text.length()))-(int) (Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
String textUpper = text.toUpperCase();
for (int i=0; i<text.length(); ++i) {
typeChar(textUpper.charAt(i));
}
if(!Driver.enterAtPeriods || !Driver.enterUnder60)keyPress(KeyEvent.VK_ENTER);
Driver.codeTimeEnd = System.nanoTime();
if(!Driver.enterUnder60)
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd- Driver.codeTimeStart)/1000000000);
else
delay(2);
}
public void typeChar(char c) {
boolean shift = true;
int keyCode;
switch (c) {
case '~':keyCode = (int)'`';break;
case '!':keyCode = (int)'1';break;
case '#':keyCode = (int)'2';break;
case '#':keyCode = (int)'3';break;
case '$':keyCode = (int)'4';break;
case '%':keyCode = (int)'5';break;
case '^':keyCode = (int)'6';break;
case '&':keyCode = (int)'7';break;
case '*':keyCode = (int)'8';break;
case '(':keyCode = (int)'9';break;
case ')':keyCode = (int)'0';break;
case ':':keyCode = (int)';';break;
case '_':keyCode = (int)'-';break;
case '+':keyCode = (int)'=';break;
case '|':keyCode = (int)'\\';break;
case '"':keyCode = (int)'\'';break;
case '?':keyCode = (int)'/';break;
case '{':keyCode = (int)'[';break;
case '}':keyCode = (int)']'; break;
case '<':keyCode = (int)',';break;
case '>':keyCode = (int)'.';break;
case '“':keyCode = (int)'\'';break;
case '”':keyCode = (int)'\'';break;
case '…':keyCode = (int)' ';break;
case '‘':keyCode = (int)'\'';break;
case '’':keyCode = (int)'\'';break;
default:
// System.out.println(c);
keyCode = (int)c;
// System.out.println(keyCode);
shift = false;
}
if(Driver.enterUnder60){
count70++;
if(count70>70)
if(c == ' '){
count70 = 0;
keyType(KeyEvent.VK_ENTER);
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
}
if(Driver.enterAtPeriods){
if(c == '.'){
count70 = 0;
keyType(KeyEvent.VK_ENTER);
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
}
if (shift){
keyType(keyCode, KeyEvent.VK_SHIFT);
System.out.println("works");
}
else
keyType(keyCode);
}
private int charToKeyCode(char c) {
switch (c) {
case ':':
return ';';
}
return (int)c;
}
}
The infile can be whatever you want it to be, and all characters will be shown, but the " will not be typed. I don't know if the type() method is ever accessed in its case.
Here is an example input:
"Hi, my name is koikoi."
The output comes out like this:
Hi, my name is koikoi.
When it should have the quotations on it. The typer does not recognize/read them. I can't find any flaws in my code and would like some advice. I can add the main method if requested.

match and delete elements in arraylists

I am making a robot maze where the robot reaches a target automatically without crashing into walls. I want the robot to do the maze once, learn the correct route and then the second time be able to get there straight away without going to any deadends. I thought I could do this by making three arraylists.
One for all the squares the robot visits.
Two for all the squares that lead to a deadend.
Three for all the directions the robot goes.
If the squares that lead to a dead end are found in the first arraylist then i can delete the same indexes in the third arraylist. That way, the second time, i can just iterate the third Arraylist.
My full code is below:
import java.util.ArrayList;
import java.util.*;
import java.util.Iterator;
import java.util.stream.IntStream;
public class Explorer {
private int pollRun = 0; // Incremented after each pass.
private RobotData robotData; // Data store for junctions.
private ArrayList<Integer> nonWallDirections;
private ArrayList<Integer> passageDirections;
private ArrayList<Integer> beenbeforeDirections;
private Random random = new Random();
int [] directions = {IRobot.AHEAD, IRobot.LEFT, IRobot.RIGHT, IRobot.BEHIND};
private ArrayList<Square> correctSquares;
private ArrayList<Square> wrongSquares;
private ArrayList<Integer> correctDirections;
public void controlRobot (IRobot robot) {
// On the first move of the first run of a new maze.
if ((robot.getRuns() == 0) && (pollRun ==0))
robotData = new RobotData();
pollRun++; /* Increment poll run so that the data is not reset
each time the robot moves. */
int exits = nonwallExits(robot);
int direction;
if ((robot.getRuns() != 0))
direction = grandfinale(robot);
nonWallDirections = new ArrayList<Integer>();
passageDirections = new ArrayList<Integer>();
beenbeforeDirections = new ArrayList<Integer>();
correctSquares = new ArrayList<Square>();
correctDirections = new ArrayList<Integer>();
// Adding each direction to the appropriate state ArrayList.
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonWallDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.BEENBEFORE) {
beenbeforeDirections.add(item);
}
}
// Calling the appropriate method depending on the number of exits.
if (exits < 2) {
direction = deadEnd(robot);
} else if (exits == 2) {
direction = corridor(robot);
} else {
direction = junction(robot);
robotData.addJunction(robot);
robotData.printJunction(robot);
}
robot.face(direction);
addcorrectSquares(robot);
correctDirections.add(direction);
}
/* The specification advised to have to seperate controls: Explorer and Backtrack
and a variable explorerMode to switch between them.
Instead, whenever needed I shall call this backtrack method.
If at a junction, the robot will head back the junction as to when it first approached it.
When at a deadend or corridor, it will follow the beenbefore squares until it
reaches an unexplored path. */
public int backtrack (IRobot robot) {
if (nonwallExits(robot) > 2) {
addwrongSquares(robot);
return robotData.reverseHeading(robot);
} else {
do {
addwrongSquares(robot);
return nonWallDirections.get(0);
} while (nonwallExits(robot) == 1);
}
}
// Deadend method makes the robot follow the only nonwall exit.
public int deadEnd (IRobot robot) {
return backtrack(robot);
}
/* Corridor method will make the robot follow the one and only passage.
The exception is at the start. Sometimes, the robot will start with
two passages available to it in which case it will choose one randomly.
If there is no passage, it will follow the beenbefore squares
until it reaches an unexplored path.*/
public int corridor (IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) == 2) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
/* Junction method states if there is more than one passage, it will randomly select one.
This applies to crossroads as well as essentially they are the same.
If there is no passage, it will follow the beenbefore squares until it reaches an unexplored
path. */
public int junction(IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) > 1) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
// Calculates number of exits.
private int nonwallExits (IRobot robot) {
int nonwallExits = 0;
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonwallExits++;
}
}
return nonwallExits;
}
// Calculates number of passages.
private int passageExits (IRobot robot) {
int passageExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageExits++;
}
}
return passageExits;
}
// Calculates number of beenbefores.
private int beenbeforeExits (IRobot robot) {
int beenbeforeExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
beenbeforeExits++;
}
}
return beenbeforeExits;
}
// Resets Junction Counter in RobotData class.
public int reset() {
return robotData.resetJunctionCounter();
}
public void addcorrectSquares(IRobot robot) {
Square newSquare = new Square(robot.getLocation().x, robot.getLocation().y);
correctSquares.add(newSquare);
}
public void addwrongSquares(IRobot robot) {
Square badSquare = new Square(robot.getLocation().x, robot.getLocation().y);
wrongSquares.add(badSquare);
}
public int grandfinale (IRobot robot) {
IntStream.range(0, correctSquares.size())
.map(index -> correctSquares.size() - index - 1)
.filter(index -> (((wrongSquares.x).contains(correctSquares.x)) && ((wrongSquares.y).contains(correctSquares.y))).get(index))
.forEach(index -> correctDirections.remove(index));
Iterator<Integer> routeIterator = correctDirections.iterator();
while (routeIterator.hasNext()) {
break;
}
return (routeIterator.next());
}
}
class RobotData {
/* It was advised in the specification to include the variable:
private static int maxJunctions = 10000;
However, as I am not using arrays, but ArrayLists, I do not
need this. */
private static int junctionCounter = 0;
private ArrayList<Junction> junctionList = new ArrayList<Junction>();
// Resets the Junction counter.
public int resetJunctionCounter() {
return junctionCounter = 0;
}
// Adds the current junction to the list of arrays.
public void addJunction(IRobot robot) {
Junction newJunction = new Junction(robot.getLocation().x, robot.getLocation().y, robot.getHeading());
junctionList.add(newJunction);
junctionCounter++;
}
// Gets the junction counter for Junction info method in Junction class.
public int getJunctionCounter (IRobot robot) {
return junctionCounter;
}
// Prints Junction info.
public void printJunction(IRobot robot) {
String course = "";
switch (robot.getHeading()) {
case IRobot.NORTH:
course = "NORTH";
break;
case IRobot.EAST:
course = "EAST";
break;
case IRobot.SOUTH:
course = "SOUTH";
break;
case IRobot.WEST:
course = "WEST";
break;
}
System.out.println("Junction " + junctionCounter + " (x=" + robot.getLocation().x + ", y=" + robot.getLocation().y +") heading " + course);
}
/* Iterates through the junction arrayList to find the
heading of the robot when it first approached the junction.
It does this by finding the first junction in the ArrayList
that has the same x and y coordinates as the robot.*/
public int searchJunction(IRobot robot) {
Junction currentJunction = null;
Iterator<Junction> junctionIterator = junctionList.iterator();
while (junctionIterator.hasNext()) {
currentJunction = junctionIterator.next();
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y)))
break;
}
return currentJunction.arrived;
}
// Returns the reverse of the heading the robot had when first approaching the junction.
public int reverseHeading(IRobot robot) {
int firstHeading = searchJunction(robot);
int reverseHeading = 1; // Random integer to Iniitalise variable.
switch (firstHeading) {
case IRobot.NORTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.AHEAD;
else
reverseHeading = IRobot.LEFT;
break;
case IRobot.EAST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.RIGHT;
else
reverseHeading = IRobot.AHEAD;
break;
case IRobot.SOUTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.BEHIND;
else
reverseHeading = IRobot.RIGHT;
break;
case IRobot.WEST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.LEFT;
else
reverseHeading = IRobot.BEHIND;
break;
}
return reverseHeading;
}
}
class Junction {
int x;
int y;
int arrived;
public Junction(int xcoord, int ycoord, int course) {
x = xcoord;
y = ycoord;
arrived = course;
}
}
class Square {
int x;
int y;
public Square(int cordx, int cordy){
x = cordx;
y = cordy;
}
}
IntStream.range(0, al1.length)
.filter(index -> al2.contains(al1.get(index)))
.forEach(index -> al3.remove(index));
Slightly more complex than this if removing elements from al3 shifts them left but in that case just reverse the stream before the .filter- then it will delete from the end. The easiest way to do that is:
.map(index -> al1.length - index - 1)
Without Streams the equivalent would be
for (int i = 0; i < al1.length; i++) {
if (al2.contains(al1.get(i))) {
al3.remove(i);
}
}
Similarly, if you need to delete from the right then the for loop would need to count down rather than up.
Without further details on arraylist structure it's hard to give any more hints.

Categories