Save search results into JTable

//I try to make an function for catching all results of search of some string, //but I only catching one element and my for does not continue to all results of //my search.
//There is an error in my loop sequence?
//Do you have any soggestion?

//This is my code.
//Sorry my code it is in spanish.

private void Buscar(String tema){
    String url = "http://www.google.com/search?q="+tema;
    String resultado;
    String[] resultados;
    DefaultTableModel model = (DefaultTableModel) jT_ResultadosBusqueda.getModel();
    int contacampos;
    try{
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
        StringBuffer response = new StringBuffer();
        while ((tema = in.readLine()) != null) {
        response.append(tema);
    }
            in.close();
            resultado = response.toString();
            resultados = resultado.split("<a href="/url?q=");
            contacampos = 1;
            do{
                for (int i = 0; i < resultados.length; i++) {
                    //JOptionPane.showMessageDialog(this,i);
                    //JOptionPane.showMessageDialog(this,resultados.length);
                    int inicio = resultados[i].indexOf(""http");
                    //JOptionPane.showMessageDialog(this,inicio);
                    int fondo = resultados[i].indexOf("">");
                    //JOptionPane.showMessageDialog(this,fondo);
                    String result = resultados[i].substring(inicio + 1, fondo);
                    model.addRow(new Object[]{result,"Ejemplo1","Tema1","Asunto1","www.1.com"});
                }
                                contacampos = contacampos +1;
            }while(contacampos<resultados.length);


    }catch(HeadlessException | IOException e){
        JOptionPane.showMessageDialog(this,e.getMessage (),"¡Aviso!",JOptionPane.ERROR_MESSAGE);
    }

}

Java hangman game – image shows when correct letter guessed and not other way around

I can’t figure this out at all, when a letter is pressed it will light up green if the letter is in the answer, and red if not. This works fine so my program knows what letters exist in the answer. But if I call my setImage() method when an incorrect letter is picked, it doesn’t change the image.

Now the buggy part is the next time the player actually guesses a CORRECT letter, the image will appear showing they have lost a life, and it will make up for the times it was supposed to appear and show the correct number of lives left.

I have output to the console every time a life is lost, which is accurate. I think the problem may lie in my setImage() method but I could be very wrong so I thought I’d ask here if anyone could help. I have posted just what I believe to be relevant methods.

GUI Class

public void createKeyboard() {
    //String keyboardFormat = "QWERTYUIOPASDFGHJKLZXCVBNM";
    String buttonLabel;
    char buttonLabelChar;

    for (char c = 'A'; c <= 'Z'; c ++) {    
        buttonLabelChar = c;
        buttonLabel = "" + buttonLabelChar; // Converts char to a string so it can be used in JButton label.
        JButton button = new JButton(buttonLabel);
        button.setPreferredSize(new Dimension(40, 40));
        pnlKeyboard.add(button);
        button.addActionListener(
            new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {


                    hm.setLetterGuessed(event.getActionCommand().charAt(0));
                    hm.revealLetter();

                    if (hm.revealLetter()) {

                        button.setForeground(Color.GREEN);

                    }
                    else {
                        button.setForeground(Color.RED);
                        hm.loseLife();

                        setImage();
                    }


                    setWord();




                }
            }
        );

    }
}

public void setImage() {

    for (int i = 10; i >= 0; i --) {
        if (hm.getLives() == i) {
            imgPath = "src/images/" + String.valueOf(i) + ".png";
        }
    }
        try {
            File imgFile = new File(imgPath);
            firstImg = ImageIO.read(imgFile);
            icon = new ImageIcon(firstImg);
            lblFirstImg = new JLabel(icon);

        } catch (IOException e) {
            e.printStackTrace();
        }

    pnlMain.add(lblFirstImg, BorderLayout.CENTER);
}

Hangman Class

public boolean revealLetter() {
    boolean boolRevealed = false;

    System.out.println("revealLetter() called");


    for (int i = 0; i < splitWord.length(); i ++) {
        if (letterGuessed == splitWord.charAt(i)) {
            hiddenWordArray.set(i, letterGuessed);
            boolRevealed = true;
        }
    }


    StringBuilder sb = new StringBuilder();
    for (Character s : hiddenWordArray) {
        sb.append(s);

    }
    hiddenWord = sb.toString();

    System.out.println(hiddenWord);

    return boolRevealed;

}

public void loseLife() {
    lives--;
    System.out.println("Lives remaining: " + lives);
}

public int getLives() {

    return lives;
}

Server (java) and client (android) how to

We searched for how to do it, but maybe we miss something. Please give us some information or keywords what to search for.

For our university project, we want to develop a small app:

A client sends the current location data to the server. The server checks in the database for other nearby clients and send a notification (data) to this client. This client now can accept or reject this offer.

Is it possible as:

  • Server in Java
  • Client is Android-App
  • Server is online and not local

How to do it?

What we found might be helpful for us: websockets, firebase cloud messaging, tomcat server. Is this relevant? Please 🙂

[Gradle][Play] where is compilePlayBinaryScala defined?

I’m relatively new to gradle and Play.

I’m working on play project which uses gradle as build system. I’m trying to use build caching for better performance. From build scan, i observe ‘compilePlayBinaryScala’ is not cacheable and most of the other tasks are dependent on ‘compilePlayBinaryScala’. Enabling caching for ‘compilePlayBinaryScala’ will really scale up the build.

Gradle official docs lists .*PlayBinary tasks (https://docs.gradle.org/current/userguide/play_plugin.html)

I could not find explicit task definition for ‘compilePlayBinaryScala’ or any other .*PlayBinaryScala tasks. Where are these tasks defined?

From my research, i could see this file where tasks may be created.But, i’m not sure. https://github.com/gradle/gradle/blob/de399b5015b19c07d94aa2eabec47709fc719a68/subprojects/platform-play/src/main/java/org/gradle/play/plugins/PlayApplicationPlugin.java#L160

Since i’m newbie Detailed explanation of why its done this way will be very helpful.

Java eclipse JButton, how can I recognize what I clicked on?

What I am trying to do is I want to move the icon ( yellow icon in screen shot) to the other JButton area only when I click the first position of that icon. For example, when you see the screen shot, for yellow icon position, row is 7 and column is 0. It has to be moved only in case that I click the first position. I have been stucking in this problem for several hours, please help me.

    package WoolfandSheep;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;

    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;



    public class test extends JFrame{

        private int length = 4;
        private Container contents;
        Sheep Sheep = new Sheep(7, 0);
        Woolf []Woolf = new Woolf[length];


        private JButton[][] squares = new JButton[8][8];
        private Color colorBlack = Color.BLACK;
        private Color colorOrange = Color.ORANGE;

        private ImageIcon sheep = new ImageIcon("sheep.PNG");
        private ImageIcon woolf = new ImageIcon("wolf.PNG");


        public test()
        {
            super("Sheep and wolf game"); 

            Woolf[0] = new Woolf(0,1);
            Woolf[1] = new Woolf(0,3);
            Woolf[2] = new Woolf(0,5);
            Woolf[3] = new Woolf(0,7);

            contents = getContentPane();
            contents.setLayout(new GridLayout(8, 8));

            ButtonHandler buttonhandler = new ButtonHandler();

            for(int i=0;i<8;i++)
            {
                for(int j=0;j<8;j++)
                {


                    squares[i][j] = new JButton();
                    if((i+j)%2!=0) // it allows to show   black blocks
                    {
                        squares[i][j].setBackground(colorBlack);
                    }
                    else
                    {
                        squares[i][j].setBackground(colorOrange);
                    }
                    contents.add(squares[i][j]);
                    squares[i][j].addActionListener(buttonhandler);
                }
            }


            /*System.out.println(SheepClass.getSheeprow());
            System.out.println(SheepClass.getSheepcol());
            System.out.println(Woolf[0].getWoolfcol());*/



            squares[Sheep.getSheeprow()][Sheep.getSheepcol()].setIcon(sheep);
            squares[Woolf[0].getWoolfrow()][Woolf[0].getWoolfcol()].setIcon(woolf);
            squares[Woolf[1].getWoolfrow()][Woolf[1].getWoolfcol()].setIcon(woolf);
            squares[Woolf[2].getWoolfrow()][Woolf[2].getWoolfcol()].setIcon(woolf);
            squares[Woolf[3].getWoolfrow()][Woolf[3].getWoolfcol()].setIcon(woolf);

            setSize(500,500);
            setResizable(false);
            setLocationRelativeTo(null); //centers window
            setVisible(true);

        }


        private boolean isValidMove(int i, int j)
        {

            int rowDelta = Math.abs(i-Sheep.getSheeprow());
            int colDelta = Math.abs(j-Sheep.getSheepcol());

            if((rowDelta==1) && (colDelta==1))
            {
                return true;
            }

            return false;
        }


        private void processClick(int i, int j)
        {


            if(isValidMove(i,j)==false)
            {
                    //JOptionPane.showMessageDialog(null, "You have to move only one box in black board");
                    return;
            }



            squares[Sheep.getSheeprow()][Sheep.getSheepcol()].setIcon(null);
            squares[i][j].setIcon(sheep);
            Sheep.setSheeprow(i);
            Sheep.setSheepcol(j);

        }



        private class ButtonHandler implements ActionListener
        {
            public void actionPerformed(ActionEvent e) 
            {



                Object source = e.getSource();

                for(int i=0;i<8;i++)
                {
                    for(int j=0;j<8;j++)
                    {

                        if(source==squares[i][j])
                        {
                            System.out.println("i = " +i+ "j = " +j);

                            processClick(i,j);

                            return;
                        }

                    }
                }

            }




        }



        public static void main(String[] args) {
            // TODO Auto-generated method stub



            new test(); 
        }
    }

package WoolfandSheep;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;




    public class Woolf {

        private int woolfrow;
        private int woolfcol;

        public Woolf(int woolfrow,int woolfcol)
        {
            this.woolfrow=woolfrow;
            this.woolfcol=woolfcol;
        }
        public void setWoolfrow(int woolfrow)
        {
            this.woolfrow = woolfrow;
        }
        public void setWoolfcol(int woolfcol)
        {
            this.woolfcol = woolfcol;
        }
        public int getWoolfrow()
        {
            return woolfrow;
        }
        public int getWoolfcol()
        {
            return woolfcol;
        }
    }

package WoolfandSheep;


    public class Sheep {

        private int Sheeprow;
        private int Sheepcol;

        public Sheep(int Sheeprow, int Sheepcol)
        {
            this.Sheeprow = Sheeprow;
            this.Sheepcol = Sheepcol;
        }
        public void setSheeprow(int Sheeprow)
        {
            this.Sheeprow = Sheeprow;
        }
        public void setSheepcol(int Sheepcol)
        {
            this.Sheepcol = Sheepcol;
        }
        public int getSheeprow()
        {
            return Sheeprow;
        }
        public int getSheepcol()
        {
            return Sheepcol;
        }
    }

enter image description here

java Giving Chances

I was trying to make a program about shooting a target. I have finished most of the parts and have only one thing left.
In the question, I was told to let the user to input vo,xo,yo,degree and calculate if he can hit the target. He can only have 4 chances. After the 4 chances, he can either type to end the game or start the game again.

The problem I am having now is the way I coded can only make the program run once(which the player can only have 4 chances and the game ends). I am wondering if there is any way I can fix or change.

Here is my main method:

public static void main(String[] args) throws IOException{
    BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
    AngryBirdGame game = new AngryBirdGame();
    System.out.println("This game is the Angry Bird Game. You will be trying to hit the target.");
    System.out.println("One of the targets of the game is (500,0)");
    System.out.println("The other target of the game is (250,0)");
    int vo,degree,xo,yo,theXvalue;
    double radian;
    double a,b,c,time,theMaximumHeight;
    startOrend();
    for (int i = 1;i <= 4 && game!= null;i++, game= startOrend()) {
        System.out.println();
        System.out.println("This is chance # " +i);
        System.out.println("Please enter the initial velocity");
        vo=velocity() ;
        System.out.println("Please enter the angle of elevation(0-90 degrees)");
        degree=degree();
        System.out.println("Please enter the horizontal starting point(50-500)");
        xo=horizontal();
        System.out.println("Please enter the vertical starting point");
        yo=vertical();  
        radian=radian(degree);
        a=a();
        b=b(vo, radian);
        c=c(yo);
        time=time(a,b,c);
        System.out.println("The time used to get to the ground is" +time);
        theXvalue=theXvalue(xo, vo, time, degree);
        System.out.println("The x value is" +theXvalue);
        theMaximumHeight=theMaximumHeight(vo);
        System.out.println("The maximum height is" +theMaximumHeight);
        result(theXvalue);
    }

And the method I have for staring and ending the program:

public static AngryBirdGame startOrend() throws IOException {
    // first check if the user wants to play
    BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Do you want to start again? <Enter 'EXIT' to end the game>");
    String input = br.readLine();
    if (input.toLowerCase().startsWith("e")) {
        return null;
    }
    // if so, create a game object and get all the input
    AngryBirdGame game = new AngryBirdGame();
    return game;
}

I will be very apprieciated to recieve your help!!

One thing more, I just started learning to code, so it would be better to help me using (for, do…while, while) loops.

No enclosing instance is accessible. Must qualify the allocation with an enclosing instance of type (e.g. x.new A() where x is an instance of )

I’m new to programming and I’ll be studying it next year in uni. In my public static void main … I can’t create a new SimpleCircle. This error occurs only on my circle. Thank you very much for the help! 🙂

public class TestSimpleCircle {

class SimpleCircle {
    double radius;

    SimpleCircle(){
        radius = 1;
    }

    SimpleCircle(double newRadius){
        radius = newRadius;
    }

    double getArea() {
        return radius * radius * Math.PI;
    }

    double getPerimeter() {
        return 2 * radius * Math.PI;
    }

    void setRadius(double newRadius) {
        radius = newRadius;
    }
}

public static void main(String [] args) {
    SimpleCircle circle = new SimpleCircle();
    System.out.println("the area of the circle of radius "+circle.radius+" is "+circle.getArea());

    SimpleCircle circle2 = new SimpleCircle(25);
    System.out.println("the area of the circle of radius "+circle2.radius+" is "+circle2.getArea());

    SimpleCircle circle3 = new SimpleCircle(125);
    System.out.println("the area of the circle of radius "+circle3.radius+" is "+circle3.getArea());

    circle.radius = 100;
    System.out.println("The area of the circle of radius "+circle.radius+" is "+circle.getArea());

}
}

Read a line and push into a line-stack until the end of file

I have to do a program and unfortunately I have no idea where to start. It’s like we were doing very basic coding and then my teacher went on maternity leave and our substitute thinks we are further along then we actually are. I know how to ready from a file, but I do not know how to put the line into a stack from there.
These are the instructions
1) Read a line and push into a line-stack until the end of file 2) While line_stack is not empty a. Pop one element out and process the following i. Split elements in this line (i.e. numbers) using StringTokenzier ii. Push all numbers into number-stack iii. While number_stack is not empty 1. Pop a number 2. Print a character using that ascii number

Faster face detection code using OpenCV Java

For my university project work, I have written a code to detect faces from the image and crop the faces into a differnt folder using OpenCV Java. In the code I have used “CascadeClassifier”. Using this code I have detected the faces. However, is it possible improve the code, so that it is possible to detect the code faster. For example, it took 1.1520934 second to detect 5 faces from 5.jpg (resolution 1280*720). My pc has intel core i-5 @ 2.20 GHz. Is it possible to detect the face faster?
Opencv code

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class DetectFaceDemo 
{

    public void run() 
    {
        // TODO Auto-generated method stub
        System.out.println("nRunning DetectFaceDemo");

        // Create a face detector from the cascade file in the resources
        // directory.
        long startTime = System.nanoTime();
    //    CascadeClassifier faceDetector = new CascadeClassifier("D:\opencv\sources\data\lbpcascades\lbpcascade_frontalface.xml");
        CascadeClassifier faceDetector = new CascadeClassifier("D:\opencv\sources\data\haarcascades\haarcascade_frontalface_alt.xml");
//       CascadeClassifier faceDetector = new CascadeClassifier("D:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml");


//      Mat image = Highgui.imread("d:\face image\aaa05.jpg");
        Mat image = Highgui.imread("D:\photo test gallery_HD_2\5.jpg");
       float size = Math.round(image.height() * 0.1f);
       //System.out.println("####= "+ size); 
        Rect rectCrop = null;
        // Detect faces in the image.
        // MatOfRect is a special container class for Rect.
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);
//      faceDetector.detectMultiScale(image, faceDetections, 1.1, 3, 0, new Size(90, 90),new Size(400, 400));


        System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

        // Draw a bounding box around each face.
        for (Rect rect : faceDetections.toArray())
        {
            Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 0, 255));

            rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);  

            Core.putText(image, "Edited by me", new Point(rect.x,rect.y),
                    Core.FONT_HERSHEY_PLAIN, 1.0 ,new  Scalar(0,255,255));
        }


        // crop individual image
        int counter=0;
        for (Rect rect : faceDetections.toArray())
        {
            Mat faceImage = image.submat(rect);
            Mat resizeimage = new Mat();
            Size sz = new Size(64, 128);
            Imgproc.resize(faceImage, resizeimage, sz);
            System.out.println(counter);
            Highgui.imwrite("D:\image\appface\"+ counter+ ".jpg", resizeimage);
            counter++;
            System.out.println(";)");

        }

        //long stopTime = System.nanoTime();
        //float time_diff = stopTime - startTime;
        //System.out.println("timefacedetect-s:"+ time_diff/1000000000);

        // Save the visualized detection.
        String filename = "d:\faceDetection.jpg";
        System.out.println(String.format("Writing %s", filename));
        Highgui.imwrite(filename, image);

    }

}

Sample image file:
https://drive.google.com/open?id=1kQHyF3E-pYMy1IESn8yzRs_6J4fZq_zi