How to make a displaybox application that prompts user for length and width and then displays a box of asterisks

I want to make a box of asterisks that utilizes the user’s length and width, using methods, parameters and loops (no arrays if possible since I haven’t learned it yet.) What I have so far just displays one line of the asterisks, I have no idea what to do past this point. Please help!

    public static void drawBar(int length, String mark) {

    for (int i = 1; i < length; i++) {
        System.out.print(mark);
    }
}

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Enter a height: ");
    int length1 = input.nextInt();
    System.out.println("Enter a width: ");
    int length2 = input.nextInt();

    for (int j = 1; j < length1; j ++) {
        drawBar(j, "*");
    }

}

}

Remove() method for a doubly linked list

 /**
 * The remove() method removes the current node from the list. If the next node exists,
 * it becomes the current node. Otherwise the previous node becomes the current node. 
 * If neither node exists, the list becomes empty.
 * 
 * @throws Exception    If the list is empty.
 */

public void remove() throws Exception
{
    if (isEmpty())
    {
        throw exListEmpty;
    }
    Node target = current;      
    Node prevNode = target.prev;
    Node nextNode = target.next;

    // current node is at head
    if (prevNode == null)
    {
        nextNode.prev = null;
        head = nextNode;
    }
    else
    {
        prevNode.next = nextNode;
        current = prevNode;
    }

    // current node is at tail
    if (nextNode == null)
    {
        prevNode.next = null;
        tail = prevNode;
    }
    else
    {
        nextNode.prev = prevNode;
        current = nextNode;
    }
    if (prevNode == null && nextNode == null)
    {
        isEmpty();
    }
    else if (prevNode != null && nextNode != null)
    {
        prevNode.next = nextNode;
        nextNode.prev = prevNode;
        current = nextNode;
    }
    size--; 
}

The test code is:

    public void testContains() throws Exception
    {
        PDLinkedList first = new PDLinkedList();
        first.append(5);
        first.insert(7);
        first.add(8);

        System.out.println("Before first remove: " + first.toString());
        first.remove(); 
        System.out.println("After first remove: " + first.toString());
        first.remove(5);
        System.out.println("After second remove: " + first.toString());
        first.remove();
        System.out.println("After third remove: " + first.toString());
    }

Which then prints out as:

Before first remove: 7 8 5
After first remove: 7 8 5
After second remove: 7 8
After third remove: 7 8

It should remove the 8 after the first remove(), then the 7 after the third remove(). My add(item) method is set as the current pointer, and my remove() method should then remove the node at the current pointer. But it seems to do nothing. I wonder if it is pointing at the wrong node? The code compiles, but I receive an Assertion Error that states the 7 and 8 are still in the list.

Testing SOAP client with MockWebServer

I am not sure if I will be able to articulate this question well, but I shall try.
So I have this project where I have generated java pojos from a wsdl and xjb file through apache cxf wsdl2java plugin. This generates java pojos and also a Services java file which has a method that gets the ServicesSoap file which has the methods defined in wsdl. I am trying to write tests for this but have been unable to find anything online for it. I am using okhttp3 MockWebServer for testing.

For example, Test File:

@ClassRule
public static MockWebServer server       = new MockWebServer();

@Test
public void testHealthCheck() throws Exception {
    client = new XYZClient(SomeClientConfigurationObject);
    server.enqueue(new MockResponse().setBody("<DummyResponse xmlns='https://www.dummywebsite.com'><DummyResult>OK</DummyResult></DummyResponse>"));
    assertEquals(ResponseType.OK, client.healthCheck());
}

Client File:

//initialization of service.
//qname has www.dummyWebsite.com and WSDL points to WSDL for the service.
service = new ServicesFile(WSDL_URL, qName).getDummySoapServices();
public HealthResponse healthCheck() {
    service.isAlive();
    return ResponseType.OK;
}

DummySoapService File:

@WebService(targetNamespace = "https://www.dummywebsite.com", name = "DummySoap")
@XmlSeeAlso({ObjectFactory.class})
public interface DummySoap {

@WebMethod(operationName = "IsAlive", action = "https://www.dummyWebsite.com/IsAlive")
@RequestWrapper(localName = "IsAlive", targetNamespace = "https://www.dummyWebsite.com", className = "package.IsAlive")
@ResponseWrapper(localName = "DummyResponse", targetNamespace = "https://www.dummyWebsite.com", className = "package.DummyResponse")
@WebResult(name = "DummyResult", targetNamespace = "https://www.dummyWebsite.com")
public java.lang.String isAlive();
}

Services File:

@WebServiceClient(name = "ServicesFile", wsdlLocation = "classpath:somewhere/something.wsdl", targetNamespace = "https://www.dummyWebsite.com") 
public class ServicesFile extends Service {
    @WebEndpoint(name = "dummySoapService")
        public DummySoapService getDummySoapService() {
            return super.getPort(DummySoapService, DummySoapService.class);
        }
    }

The issue is that since the services and the servicesSoap file get generated randomly from the wsdl which has www.dummyWebsite.com as the targetNamespace, while performing tests I want it to mock and hit something like www.abcd.com, but I am not sure how to go about it.

If this seems to vague, please let me know what other details you need! Thanks!

How to display array elements?

So I am trying to write a method that populate a board in a game. I am just beginning to learn about programming so I do not know much about special methods.

public static void Board(char[][] array){

  for(int i=0; i<2*array.length+1; i++) {
  if(i %2 ==0){
    for(int j=0; j<2*array.length+1;j++){
      if(j%2==0){
        System.out.print("+");
      }
      else{
        System.out.print("-");
      }
    }
  }
  else {
      for(int j=0; j<2*array.length+1;j++){
        if(j%2==0){
          System.out.print("|");
        }
        else{
          System.out.print(" "); // Maybe should use this spot to insert the x and o from the array.
        }
  }
    }
  System.out.println();

But in the board, where I currently have empty spaces, I want to actually be able to accept input.

For example , if

char [][] b={{'',' x',' ',},{' ','s','t '},{'o','o',' '}};
 Board(a);

Then instead of only having the empty spaces, I would like the element corresponding to the array to go there. I marked on my code where I think this might be done. I don’t know of any special methods, but possibly DeepArray to string or such.
I understand how to import using Arrays.ToString, the issue is with the index.

Markov Text java List.clear() issue

Trying to create a Markov learnFromText program with the following constraints where for each sequence of three adjacent words

  • there’s a sublist of the first two words that will be the key for the map

  • Take the value for that key, and add the third word to the end of the list.

Basically a string like "<START> <START> I am not a number. I am a free man! <END>"

should print out as {[<START>, <START>]=[I], [<START>, I]=[am], [I, am]=[not, a], [am, not]=[a], [not, a]=[number.], [a, number.]=[I], [number., I]=[am], [am, a]=[free], [a, free]=[man!], [free, man!]=[<END>]}

What I have so far is

static void learnFromText(Map<List<String>, List<String>> whatComesNext, List<String> text) {
    List<String> temp = new ArrayList<String>();
    List<String> temp1 = new ArrayList<String>();
    for(int i = 0; i < text.size()-2; i++) {
        temp.add(text.get(i));
        temp.add(text.get(i+1));
        temp1.add(text.get(i+2));
        whatComesNext.put(temp, temp1);
        temp.clear();
        temp1.clear();
    }
    System.out.println(whatComesNext);
  }

But it prints
{[]=[], []=[], []=[], []=[], []=[], []=[], []=[], []=[], []=[], []=[]} which are empty so something is wrong with my .clear() but it’s called after the map stores the values.

How to test if @PreAuthorize with custom bean-spel is valid?

I have a many @RestControllers with methods like:

@PreAuthorize("@myBean.myMethod(#param1, #param2)")
public void foo(String param1, Long param2) {}

And somewhere

@Component
public class MyBean {
    public boolean myMethod(String param1, Long param2) {

        return importantSecurityCheck();
    }
}

It works very well, but I want to avoid possible stupid bugs after refactoring (because afaik spring doesn’t detect error until method is invoked), so my idea was to write test which will check if expression is valid (e.g. parameters have same type and names are valid).

I tried to do something like this:

@Test
public void checkSecurityExpressions() {
 Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RestController.class);

    beansWithAnnotation.forEach((name, bean) -> {
        Method[] methods = AopUtils.getTargetClass(bean).getMethods();

        for (Method method : methods) {
            PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);

            if (annotation != null) {

                String securityExpression = annotation.value();

                System.out.println(securityExpression);
            }

        }
    });
}

Which finds expressions nicely, but all ExpressionParser examples which I found work with simpler expressions (without security context, even without @ at the beginning).

How to check it’s correctness? Or maybe there are better solutions for this problem?

Remove all entries where value is an empty Optional from map

I want to remove all entries where value is an empty Optional from the map. It would seem that nothing complicated, but I am trying to find a better solution that I have.


Input:

I have the following Map:

Map<String, Function<String, Optional<String>>> attributesToCalculate = new HashMap<>();

Where key – just a String and value – reference to method which returns Optional < String >


Output:

As a result, I want to get

Map<String, String> calculatedAttributes

(excluding entries where value was an empty Optional)


Here is my solution

      return attributesToCalculate.entrySet()
        .stream()
        .map(entry -> Pair.of(entry.getKey(), entry.getValue().apply(someString)))
        .filter(entry -> entry.getValue().isPresent())
        .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get()));

But I don’t like the .filter part because then I have to invoke .get() on Optional in collect part.

Is there а better way (maybe without .get invocation) to solve this problem? Thanks.

How many vertices is to many for a polygon

Would it be considered bad to have to many vertices to define a single polygon. What I mean is if a lot of the coordinates are touching is that bad? I am worried about what will happened when I come to triangulate my polygons as well as performance issues (technically this is not a problem for the size of the game, but I want to take it into consideration for my own personal development).

[note] – this is a libgdx project. I am making risk the board game. The polygons are for mapping territories that are (obviously) complex and irregular shapes.

Generating a new reversed LinkedList without altering the caller

I am trying to create a new LinkStrand, without altering the strand on which it’s called. In addition to reversing the linked list, I want to reverse each string in each node of the linked list using StringBuilder. For reversing the LinkedList, I would like to use the approach of adding a new node to the front of the reversed list being constructed. Below is the code I have so far, for reversing a LinkStrand. Please let me know what I am missing and how to make it work, as the original strand in the call strand.reverse() my Unit test is changing after this call. Thanks a lot for your help.

E.g. if my Unit test has:

private static String[] s = "aggtccg";
IDnaStrand strand = getNewStrand(s);
IDnaStrand rev = strand.reverse();

LinkStand.java:
public IDnaStrand reverse() {

        // Copy this node to temp
        LinkStrand copiedStrand = this; 

        // Reverse the string in the first node  
        LinkStrand newStrand = new LinkStrand(new StringBuilder(myFirst.info).reverse().toString());

        //Move the first node in temp to the next position
        copiedStrand.myFirst = copiedStrand.myFirst.next; 

        while(newStrand.size() < mySize){

            // Save current node from the copy into tmp before over-writing temp with next node
            Node tmp = copiedStrand.myFirst;

            // Set current Node to the next node
            copiedStrand.myFirst = copiedStrand.myFirst.next; 

            // Make the node next to tmp as the last node.
            //tmp.next = null; 

            newStrand.append(new StringBuilder(tmp.info).reverse().toString()); 
        }
        return newStrand;   
}

public IDnaStrand getInstance(String source) {
    return new LinkStrand(source);
}