java sorting algorithms – find comparisons and motions

    package faculdade;

import java.util.Random;

public class Ordenacao {

    public static long comparacao;

    public static long movimentacao;

    public static void main(String() args) {
        int() vetor = new int(1000);
        fill(vetor);
        System.out.println("Vetor criado:");
        // show(vetor);
        // tempo inicial
        long tempoInicial = System.currentTimeMillis();
        //selectionSort(vetor);
        bubbleSort(vetor);
        //insertionSort(vetor);
        //quickSort(vetor, 0, vetor.length - 1);
        // tempo final
        long tempoFinal = System.currentTimeMillis();

        System.out.println("Executado em = " + (tempoFinal - tempoInicial) + " ms");
        System.out.println("n Comparações: " + comparacao + " Movimentaçoes: " + movimentacao);
        System.out.println("Finalizado.");


    }

    public static void selectionSort(int() vetor) {
        comparacao = 0;
        movimentacao = 0;
        for (int i = 0; i < vetor.length - 1; i++) {
            int menor = i;
            for (int j = i + 1; j < vetor.length; j++) {
                comparacao++;
                if (vetor(j) < vetor(menor)) {
                    comparacao++;
                    menor = j;
                }

            }
            swap(vetor, i, menor);
            // show(vetor);
            movimentacao++;
        }
    }

    public static void bubbleSort(int() vetor) {
        movimentacao = 0;
        comparacao = 0;
        for (int i = vetor.length; i >= 1; i--) {
            for (int j = 1; j < i; j++) {
                if (vetor(j - 1) > vetor(j)) {
                    swap(vetor, j, j-1);
                    comparacao++;
                }
            }
            show(vetor);
        }
    }

    public static void insertionSort(int() vetor) {
        comparacao = 0;
        movimentacao = 0;
        for (int i = 1; i < vetor.length; i++) {
            int current = vetor(i);
            int j = i - 1;
            while (j >= 0 && current < vetor(j)) {
                vetor(j + 1) = vetor(j);
                j--;
                comparacao++;
            }
            // at this point we've exited, so j is either -1
            // or it's at the first element where current >= a(j)
            vetor(j + 1) = current;
        }

            show(vetor);
            movimentacao++;
    }

    public static void quickSort(int vetor(), int esquerda, int direita) {

        int esq = esquerda;
        int dir = direita;
        int pivo = vetor((esq + dir) / 2);
        int troca;

        while (esq <= dir) {
            while (vetor(esq) < pivo) {
                esq = esq + 1;

            }
            while (vetor(dir) > pivo) {
                dir = dir - 1;

            }
            if (esq <= dir) {
                troca = vetor(esq);
                vetor(esq) = vetor(dir);
                vetor(dir) = troca;
                esq = esq + 1;
                dir = dir - 1;
                movimentacao++;

            }
            comparacao++;
        }
        if (dir > esquerda) {
            quickSort(vetor, esquerda, dir);

        }

        if (esq < direita) {
            quickSort(vetor, esq, direita);

        }


    }

    public static void fill(int() vetor) {
        Random r = new Random();
        for (int i = 0; i < vetor.length; i++) {
            vetor(i) = r.nextInt(100);
        }
    }

    public static void show(int() vetor) {
        for (int i = 0; i < vetor.length; i++) {
            System.out.print(vetor(i) + " ");
        }
        System.out.println("");
    }

    public static void swap(int() vetor, int a, int b) {
        int aux = vetor(a);
        vetor(a) = vetor(b);
        vetor(b) = aux;
        movimentacao++;

    }

}

At runtime, the comparison number corresponds to the train number. I think that's wrong

webservice – Error setting up web service with Java and Eclipse

There has been a Haciendo Facturación Electrónica y ToDo Functionaba Correctiona y No podia Conectarse con El Servicio Web y El séjiente Error

(Exception in the thread "main" javax.xml.ws.WebServiceException: Error accessing the WSDL at: https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl. Error at: https: //celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl. at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex (RuntimeWSDLParser.java:250) at com.sun. xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse (RuntimeWSDLParser.java:231) at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse (RuntimeWSDLParser.java:194) at com.sun. sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse (RuntimeWSDLParser.java:163) under com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL (WSServiceDelegate.java:348) under com.sun. x. internal.ws.client.WSServiceDelegate. (WSServiceDelegate.java:306) at com.sun.xml.internal.ws.client.WSServiceDelegate. (WSServiceDelegate.java:215) at com.sun.xml.internal.ws. client. WSServiceDelegate. (WSServiceDelegate.java:196 ) at com.sun.xml.internal. ws.client.WSServiceDelegate. (WSServiceDelegate.java:192) at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate (ProviderImpl.java:104) at javax.xml.ws.Service. (Service.java: 77) at ec.gob.sri.comprobanteselectronicos.ws.recepcioncomprobantes.desarrollo.RecepcionComprobantesService. (RecepcionComprobantesService.java:47) under commons.prrue.validarComprobante (prrue.java:10) under commons.prrue.java:10 20) Trigger: java.io.FileNotFoundException: https://celcer.sri.gob.ec/ comprobantes-electronicos-ws / RecepcionComprobantes? wsdl at sun.net.www.protocol.http.HttpURLConnection.getInputStream0 (HttpURLConnection.java: 1890) at sun.net.www.protocol.http.HttpURLConnection.getInputStream (HttpURLConnection.java:1492 ) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream (HttpsURLConnectionImpl.java:263) at java.net. URL.openStream (URL.java:1045) under com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.createReader (RuntimeWSDLParser.java:984) under com.sun.xml.internal.ws.wsdl.p arser .RuntimeWSDLParser.resolveWSDL (RuntimeWSDLParser.java:385) under com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse (RuntimeWSDLParser.java:216) … 12 more)
No entiendo porque puede ser ya que el sistema funcionaba correctamente. You can play with MITY versions 1.1.7

java – Use status patterns to remove if else statements

I have to get rid of if, else statements from my code because it's a smell. I know that you can implement the status pattern to remove it. However, in my code, I check that the string input is a specific operator, and then execute the steps on a stack. How would I do that? Should I create different states that also perform the math and stack operations? My main problem is that I do not understand how to implement it without using an if statement. For example, if I encounter an operator, I want to do something, but since there are a number of different operators, I need to check that the input is a "+" to do the code necessary for that section.

Here is my code:

package src;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class RPNCalculator {

    public int solveEquation(final String input) {
        final Stack operands = new Stack();

        List tokenizedInput = Arrays.asList(input.split(" "));

        for (String currentToken : tokenizedInput) {
            try {
                int inputAsInt = Integer.parseInt(currentToken);
                operands.push(inputAsInt);
                continue; //
            } catch (NumberFormatException exception) {
                // do nothing, just continue
            }

            if (currentToken.contains("+")) {
                int total = operands.pop() + operands.pop();
                operands.push(total);

            } else if (currentToken.contains("-")) {
                int secondNum = operands.pop();
                int total = operands.pop() - secondNum;
                operands.push(total);

            } else if (currentToken.contains("*")) {
                int total = operands.pop() * operands.pop();
                operands.push(total);

            } else if (currentToken.contains("/")) {
                int secondNum = operands.pop();
                int total = operands.pop() / secondNum;
                operands.push(total);

            }


Visual Studio Code – Prevents VSCode from using Java streaming methods one after the other

The Java plug-in for Visual Studio Code has some annoying formatting when multiple methods are placed one behind the other. My code will be formatted like that.

Item item = items.stream().filter(m -> m.getItemName() == itemName).findFirst().orElse(Item.DEFAULT);

How can I format the plugin like this:

Item item = items.stream()
    .filter(m -> m.getItemName() == itemName)
    .findFirst()
    .orElse(Item.DEFAULT);

or so:

Item item = items.stream()
                 .filter(m -> m.getItemName() == itemName)
                 .findFirst()
                 .orElse(Item.DEFAULT);

I can not find the setting on the GitHub wiki page with the Formatter settings and templates provided.

This will give you the desired Java output

This java file should execute and retrieve the information from legoSets.XML and show me the output. At the moment, the issue I receive is just a totals number. There is no information about the other 3 that I need to see. (name, year, num-parts) I've commented out set-num to see if I can get the name to output the results, but it still only displays set-num.

---Desired Output---
    00-1
    WEETABIX CASTLE
    1970
    471>

But my edition shows only the set number

---real output---
    1: 00-1
    2: 0011-2
    3: 0011-3
    4: 0012-1
    5: 0013-1

---MAIN.Java---
package assign6;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 *
 * @author assign
 */
public class Assign6 {

    /**
     * @param args the command line arguments
     */
    public static void main(String() args) {
        System.out.print("Welcome to Brad Pitt's Lego Sorter");
        try {
            XMLReader reader = XMLReaderFactory.createXMLReader();
            MyHandler handler = new MyHandler();
            reader.setContentHandler(handler);
            reader.setErrorHandler(handler);

            InputSource inputSource = new InputSource("legoSets.xml");
            reader.parse(inputSource);

            ArrayList data = handler.getsetnums();

            System.out.println("set-num List");
            System.out.println("----------");
            for (int i = 0; i < data.size(); i++) {
                String setnum = data.get(i);
                setnum = setnum.toUpperCase();
                System.out.println((i + 1) + ": " + setnum);
            }

            ArrayList names = handler.getnames();

            System.out.println("name List");
            System.out.println("----------");
            for (int i = 0; i < data.size(); i++) {
                String name = data.get(i);
                name = name.toUpperCase();
                System.out.println((i + 1) + ": " + name);
            }

            ArrayList years = handler.getyears();

            System.out.println("year List");
            System.out.println("----------");
            for (int i = 0; i < data.size(); i++) {
                String year = data.get(i);
                year = year.toUpperCase();
                System.out.println((i + 1) + ": " + year);
            }

            ArrayList numparts = handler.getnumparts();

            System.out.println("num-part List");
            System.out.println("----------");
            for (int i = 0; i < data.size(); i++) {
                String numpart = data.get(i);
                numpart = numpart.toUpperCase();
                System.out.println((i + 1) + ": " + numpart);
            }

        } catch (SAXException ex) {
            Logger.getLogger(Assign6.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Assign6.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }

}

---MyHandler.Java---
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assign6;

import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author assign
 */
public class MyHandler extends DefaultHandler {

    private boolean inset;
    private boolean insetnum;
    private boolean inname;
    private boolean inyear;
    private boolean innumpart;
    private String setnumBuffer;
    private String nameBuffer;
    private String yearBuffer;
    private String numpartBuffer;

     private ArrayList setnums, names, years, numparts;

    public ArrayList getsetnums() {
        return setnums;

    }

    public ArrayList getnames() {
        return names;
    }

    public ArrayList getyears() {
        return years;
    }
    public ArrayList getnumparts() {
        return numparts;
    }

    @Override
    public void startDocument() throws SAXException {
        // System.out.println("Start Document")
        inset = false;
        insetnum = false;
        inname = false;
        inyear = false;
        innumpart = false;
        setnumBuffer = "";
        setnums = new ArrayList<>();
        nameBuffer = "";
        names = new ArrayList<>();
        yearBuffer = "";
        years = new ArrayList<>();
        numpartBuffer = "";
        numparts = new ArrayList<>();
    }

    @Override
    public void startElement(String uri, String localName,
            String qName, Attributes attributes) throws SAXException {
        if (localName.equals("lego-sets")) {
            inset = true;
        } else if (inset && localName.equals("set-num")) {
            // System.out.println("Start element : " + localName);
            insetnum = true;
            setnumBuffer = "";

        } else if (inset && localName.equals("name")) {
            // System.out.println("Start element : " + localName);
            inname = true;
            nameBuffer = "";

        } else if (inset && localName.equals("year")) {
            // System.out.println("Start element : " + localName);
            inyear = true;
            yearBuffer = "";
        } else if (inset && localName.equals("num-parts")) {
            // System.out.println("Start element : " + localName);
            innumpart = true;
            numpartBuffer = "";
        }
    }

    @Override
    public void characters(char() ch, int start, int length) throws SAXException {
        String data = new String(ch, start, length);
        if (inset && insetnum) {
            // System.out.println("Characters : " + data);
            setnumBuffer = setnumBuffer + data;
        } else if (inset && inname) {
            // System.out.println("Characters : " + data);
            nameBuffer = nameBuffer + data;
        } else if (inset && inyear) {
            // System.out.println("Characters : " + data);
            yearBuffer = yearBuffer + data;
        } else if (inset && innumpart) {
            // System.out.println("Characters : " + data);
            numpartBuffer = numpartBuffer + data;
    }
    }     
    @Override
    public void endElement(String uri, String localName,
            String qName) throws SAXException {
        if (localName.equals("inset")) {
            inset = false;
        } else if (inset && localName.equals("set-num")) {
            // System.out.println("Title: " + titleBuffer);
            // System.out.println("End element   : " + localName);
            // System.out.println();            
            setnums.add(setnumBuffer);
            insetnum = false;
        } else if (inset && localName.equals("name")) {
            // System.out.println("Title: " + titleBuffer);
            // System.out.println("End element   : " + localName);
            // System.out.println();            
            names.add(nameBuffer);
            inname = false;
        } else if (inset && localName.equals("year")) {
            // System.out.println("Title: " + titleBuffer);
            // System.out.println("End element   : " + localName);
            // System.out.println();            
            years.add(yearBuffer);
            inyear = false;
        } else if (inset && localName.equals("num-parts")) {
            // System.out.println("Title: " + titleBuffer);
            // System.out.println("End element   : " + localName);
            // System.out.println();            
            numparts.add(numpartBuffer);
            innumpart = false;
        }
    }

    @Override
    public void endDocument() throws SAXException {
        // System.out.println("End Document");
    }

    @Override
    public void error(SAXParseException e) throws SAXException {
        System.out.println("ERROR: Line number " + e.getLineNumber());
        System.out.println("ERROR:             " + e.getMessage());
    }

    @Override
    public void fatalError(SAXParseException e) throws SAXException {
        System.out.println("FATAL ERROR: Line number " + e.getLineNumber());
        System.out.println("FATAL ERROR:             " + e.getMessage());
    }

}

---legoSets.xml---

    
        00-1
        WEETABIX CASTLE
        1970
        471
    
    
        0011-2
        TOWN MINI-FIGURES
        1978
        12
    
    
        0011-3
        CASTLE 2 FOR 1 BONUS OFFER
        1987
        2
    
    
        0012-1
        SPACE MINI-FIGURES
        1979
        12
    

Beginner – "Rock Paper Scissors Game" Java

  • What can improve this code?
  • And how could I improve this code?
  • Oh and I would love if someone has a project that is not that
    challenging, but I could learn a lot from it 🙂
import java.util.Scanner;

public class RockPaperScissors {
    final static int ROCK = 1;
    final static int PAPER = 2;
    final static int SCISSORS = 3;

    public static void main(String() args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Start By Entering A number");
        int human = input.nextInt();
        System.out.println("ROCK IS 1 :: PAPER IS 2 :: SCISSORS 3");
        int computerScore = 0, humanScore = 0, computer;
        while (human != -1) {
            human = input.nextInt();
            computer = (int) (Math.random() * 3 + 1);
            String h = human == 1 ? "ROCK" : human == 2 ? "PAPER" : "SCISSORS";
            String c = computer == 1 ? "ROCK" : computer == 2 ? "PAPER" : "SCISSORS";
            if ((human == ROCK && computer == SCISSORS) || (human == PAPER && computer == ROCK) || (human == SCISSORS && computer == PAPER)) {
                humanScore++;
                System.out.println("Human Won : " + humanScore);
                System.out.println("Human Chose " + h + " and Computer Chose " + c);
            } else if ((computer == ROCK && human == SCISSORS) || (computer == PAPER && human == ROCK) || (computer == SCISSORS && human == PAPER)) {
                computerScore++;
                System.out.println("Computer Won : " + computerScore);
                System.out.println("Human Chose " + h + " and Computer Chose " + c);
            } else if (human == computer) {
                System.out.println("HAH YOU BOTH THINK THE SAME! ");
                System.out.println("DRAW!");
            } else {
                System.out.println("Something Went Wrong Try Again:( ");
            }
        }
        System.out.println("nnThe Scores Are *DRUM NOISES* ");
        for (int i = 0; i < 4; i++) {
            System.out.println("------------------------------");
        }
        System.out.println("Human score : " + humanScore);
        System.out.println("Computer score : " + computerScore);
        if (humanScore > computerScore) {
            System.out.println("Human Race Is saved! We Won!");
        } else if (computerScore > humanScore) {
            System.out.println("Sadly We Lost. Better Luck Next Time:)");
        } else {
            System.out.println("Scores are Tied");
        }
    }
}

50% off Java Hosting – JSP, Java, J2EE, Tomcat, Servlets and dedicated JVM

JavaProvider.net has offered budget-friendly Java hosting since 2008.
We are a UptimeSafe certified provider. Contact us through our website or by contacting javaprovider.net

Private JVM Java Hosting Package includes:

  • Pure SSD hosting
  • Dedicated JVM – no sharing of JVM
  • Monthly / weekly backup service
  • Multiple WAR applications and multiple domains
  • Ant and maven
  • Apache Tomcat every version
  • SSH access
  • JDK any version
  • Java Control Panel to restart Tomcat, change the Tomcat / JDK version, monitor memory usage, etc.
  • Servlets, JSP, JSF, Spring, Hibernate, JSTL, Struts, Grails, EJB 3.0 and more
  • Update the heap size at any time by 5 USD / month for 128 MB. 30% discount for 256MB addon
  • Databases: MYSQL 5.6 PostgreSQL 9.3, MongoDB, CouchDB
  • CVS / Subversion (SVN) / GIT / Mercurial Repository
  • PHP 7, Python 3, Perl, Ruby
  • Free JavaProvider.net subdomain / alias
  • All typical cPanel functions

Private hangover

  • Hard disk space (SSD): 10 GB
  • Heap size: 160 MB
  • Perm Size: 160 MB
  • Traffic: 500 GB
  • Monthly: $ 9.99

Private Tomcat Pro

  • All features of Private Tomcat
  • HeapSize: 320 MB
  • Perm Size: 320MB
  • Monthly: 19.99 USD
  • Recommended for Grails, Cyclos and other complex frameworks or webapps

We offer a custom Java Control Panel. You will have the ability:

  • Change the Tomcat version
  • Start / Stop Tomcat
  • Change the JDK version and several JVM startup parameters
  • Search Tomcat logs
  • Access Tomcat Manager
  • Monitor JVM memory usage
  • Managing JMX / RMI access for remote JConsole, JVISUALVM, and more.
  • Quickly check JDBC connections to MySQL and PostgreSQL
  • List port usage and more

50% recurring discount coupon for Tomcat and Tomcat Pro packages ordered in December 2019: WHT50P14 (for new customers only)

For those of you who need more heap memory (320 MB +), we offer VPS packages with SolusVM Control Panel. Each VPS comes with a base operating system or preinstalled open source software.
Dedicated servers are also available.

The most commonly requested setups for VPS packages include JDK, Database Server, SVN and Jira, Jenkins, Magnolia, Liferay, OpenCMS, Confluence, Alfresco, JPublish, Glassfish, Cyclos, Openfire and OpenBravo. WHM / cPanel, Webmin / Virtualmin, DirectAdmin or ISPConfig3 can also be preinstalled. Dedicated servers are also available.

Check JavaProvider.net for more.