Slavi 94 Master Poster Featured Poster

Thanks guys for answering :)
@Hiroshe, I am not trying to prevent SQLI/XSS but to simulate it, we have some vulnerable servers but they have some filtering, so using base 10 or Hx would be one of the solutions. I'll try to get some code running on this thanks

Slavi 94 Master Poster Featured Poster

Before I even attempt doing anything in this direction, is it possible to enter a string and get it represented in ascii? I am reading an article about XSS and SQL injections part of a course that I am taking now, and some of the tips are that people in this area should have scripts that do both way translation but I haven't used any scripts at all, so I wonder if it would be possible to do in java as well?

Slavi 94 Master Poster Featured Poster

Your method is missing a return statement, a default one in case it never enters the if statements (Usually, the default return statement doesnt execute in applications that you always have one of the switch inputs, but is needed to satisfy the syntax)

Slavi 94 Master Poster Featured Poster

First, you don't need 2 loops. Create an int i=0, out of the loop and then increment it inside while looping. in your case you don't want to have more than 2 7s and more than 2 8s. Create variables to take care of that(which could happen in the "if"statements such as numbers7<2. Idea for the if statements is
if(number[i]==number[j] && numbers7<2&&number[i] ==7) ,likewise for else if and for else just increment i (That's a case where you have i=7 and j=8).Start from here if you face troubles come back ;)

Slavi 94 Master Poster Featured Poster

It really depends on what exactly your assignment is, but if you have to make an algorithm then the algorithm should find it for you. The way I understand is you have the cities with distance between them. You know the source city and the distance from it and the connecting cities. What your algorithm should do is check which cities you have connection to and how much is the distance to them. Pick the shortest distance and set the city you just travelled to as your new source. Repeat until source is destination, is this what it has to do?

Slavi 94 Master Poster Featured Poster

First I think you need to understand how to make a graph of them and to find how reach from home position to goal position. Take a look at Breadt first search and if you have any experience with recursion take a look at Deep first search. If you understand those, implementing dijkstra for the shortest path would take you no time :)

Slavi 94 Master Poster Featured Poster

What do you want to test? What is the biggest value it can hold?

Slavi 94 Master Poster Featured Poster

I think dijkstra is the way to go, what is your code so far?

Slavi 94 Master Poster Featured Poster

Right, but it is supposed to be an object of a class Scanner right? (Atleast I assume so by the name). I am pointing that in your code you don't define anywhere what scan is

Slavi 94 Master Poster Featured Poster

Try to answer this question?
What is scan from this line bName[i] = scan.next();?

Slavi 94 Master Poster Featured Poster

Show your current code, cant guess where your problem now is without looking into it

Slavi 94 Master Poster Featured Poster

Hey James, thanks for answering!
I took the advice of your post before the edit, and saving Thread instances into an array list, then looping through them and using print to return answer to the clients connected. It does work! Here's my code if anyone wants to take a look/give any suggestions to improve it. Also, thanks James for the edit, now when the console application works versus Computer and versus player/player sending IP packets, I am considering to implement a GUI, where the user can choose whether to play against pc or against another player

EDIT: Here's a picture of it running ;)

import java.net.*;
import java.io.*;
import java.util.*;
public class GameServer extends Thread{
    private ServerSocket serverSocket;
    private enum Action  { Scissors, Rock, Paper;

        public int checkActions(Action action){
            int win = 1;
            int lose = -1;
            int draw = 0;
            if (this == action) return draw;

            switch (this){
                case Scissors:
                if(action == Paper) return win;
                else return lose;

                case Rock:
                if(action == Scissors) return win;
                else return lose;

                case Paper:
                if(action == Rock) return win;
                else return lose;
            }
            return 69; // Default return, will never reach it 
        }
    }
    private String inputFromUser1,inputFromUser2, input;
    private List<String> userInputs = new ArrayList<String>();
    private ArrayList<ClientThread> alThreads = new ArrayList<ClientThread>();
    public GameServer(int port)throws IOException{
        serverSocket = new ServerSocket(port);
    }
    public static void main(String[] args){
        int port = 9001;
        try{
            Thread t = new GameServer(port);
            t.start();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public void run(){
        while(true){
            try{System.out.println("Starting to run");
                Socket server …
Slavi 94 Master Poster Featured Poster

If they are -1 based, then -1 is first, 0 should be second?

Slavi 94 Master Poster Featured Poster

Did you fix what I pointed you to ?

Slavi 94 Master Poster Featured Poster

Scan doesn't seem to be even defined,
charAt is a method in String class, so you have to call it from a string object
choice = charAt(0); choice = STRING.charAt(Int);

Slavi 94 Master Poster Featured Poster

this code that you have works fine for generating 3 numbers, althought I really dont understand why are you using those mathematical expressions for loterryDigits

import java.util.Scanner;
public class LotteryFixed {
    public static void main(String[] args) {
        int lottery = (int)(Math.random() * 1000);
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your lottery pick (three digits): ");
        int guess = input.nextInt();
        int lotteryDigit1 = lottery / 100;
        int lotteryDigit2 = lottery * 1;
        int lotteryDigit3 = lottery % 10;
        int guessDigit1 = guess / 100;
        int guessDigit2 = guess * 1;
        int guessDigit3 = guess % 10;
        System.out.println("The lottery number is " + lottery);
    }
}

One thing you might want to take a look at is Random class and its method nextInt(), then you can get a random number in for example 0-9 to generate each of the 3 lotteryDigits separately

Also the loterry number is from 0 to 1000, so you get number for lottery 500, then in loterryDigit1 you write 500/100 =5 , then in lotteyDigit2 you write 500*1 = 500, Do you see something weird?

Slavi 94 Master Poster Featured Poster

I ran into trouble again. It seems to be working(somehow lol) but it only sends the answer of the game ending to the client that has made the last thread, I tried moving around the PrintWriter to send message with different ways but nothing really worked yet, Here's my server side code:

Note i am pointing to run() method in my inner class ClientThread

import java.net.*;
import java.io.*;
import java.util.*;
public class GameServer extends Thread{
    private ServerSocket serverSocket;
    private enum Action  { Scissors, Rock, Paper;

        public int checkActions(Action action){
            int win = 1;
            int lose = -1;
            int draw = 0;
            if (this == action) return draw;

            switch (this){
                case Scissors:
                if(action == Paper) return win;
                else return lose;

                case Rock:
                if(action == Scissors) return win;
                else return lose;

                case Paper:
                if(action == Rock) return win;
                else return lose;
            }
            return 69; // Default return, will never reach it 
        }
    }
    private String inputFromUser1,inputFromUser2, input;
    private List<String> userInputs = new ArrayList<String>();
    public GameServer(int port)throws IOException{
        serverSocket = new ServerSocket(port);
    }
    public static void main(String[] args){
        int port = 9001;
        try{
            Thread t = new GameServer(port);
            t.start();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public void run(){
        while(true){
            try{System.out.println("Starting to run");
                Socket server = serverSocket.accept();
                new ClientThread(server).start(); 
                //System.out.println(userInputs.size());
                } catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    public String play(Action move1, Action move2) {
        int result;
        String output;
        result = move1.checkActions(move2);
        if(result==0) 
            return output = "User's move " + move1.toString() + "Computer move " 
            + move2.toString() + ", the game is: DRAW";
        else if(result==1)
Slavi 94 Master Poster Featured Poster

um, from what I understand, this is how a new thread for each client would be started? Also, I think i'll write the inputs from users in a list and if the list has 2 answers then reply back to the clients who wins, would that work?

public void run(){
        while(true){
            try{System.out.println("Starting to run");
                Socket server = serverSocket.accept();
                (new Thread().start());
                PrintWriter out = new PrintWriter(server.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
                System.out.println("waiting");
                input = in.readLine();
                System.out.println(inputFromUser1);
                userInputs.add(input);
                //out.print(play(getUser1Move(),getUser2Move()) + "\n");
                //out.flush();      
            } catch(IOException e){
                e.printStackTrace();
            }
        }
    }
Slavi 94 Master Poster Featured Poster

Still can't figure out how to get inputs from both users and then compare those >.>

Slavi 94 Master Poster Featured Poster

Okay! Good news .. the game works BUT ... it only takes inputs from 1 user, so if I send 2 messages from 1 client, I get response back. It's some progress so far but I guess what I was afraid of at first is my problem .. back to the original post of the thread ^

Slavi 94 Master Poster Featured Poster

Nvm found the problem of this for not getting "waiting"

Slavi 94 Master Poster Featured Poster

Okay an update ... I made the client code as well just to see if the server receives/responds to the client .. but I have problem in my run() at the server side .. having it like this

public void run(){
        while(true){
            try{System.out.println("Starting to run");
                Socket server = serverSocket.accept();
                PrintWriter out = new PrintWriter(server.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(server .getInputStream()));
                System.out.println("waiting");
                inputFromUser1 = in.readLine();
                System.out.println(inputFromUser1);
                inputFromUser2 = in.readLine();
                out.print(play(getUser1Move(),getUser2Move()));
                out.flush();        
            } catch(IOException e){
                e.printStackTrace();
            }
        }
    }

It prints out "Starting to run" and I don't hear from it anymore. Any idea why would it get stucked? Basically it doesn't execute the next lives so I never see message "waiting"

Slavi 94 Master Poster Featured Poster

I did point out the thing right after the code ... :p

Slavi 94 Master Poster Featured Poster

@JC, I just wrote this code really quick and it does compile without errors for the server side ... but I am not sure about 1 thing .. here is the code first

import java.net.*;
import java.io.*;

public class GameServer extends Thread{
    private ServerSocket serverSocket;
    private enum Action  { Scissors, Rock, Paper;

        public int checkActions(Action action){
            int win = 1;
            int lose = -1;
            int draw = 0;
            if (this == action) return draw;

            switch (this){
                case Scissors:
                if(action == Paper) return win;
                else return lose;

                case Rock:
                if(action == Scissors) return win;
                else return lose;

                case Paper:
                if(action == Rock) return win;
                else return lose;
            }
            return 69; // Default return, will never reach it 
        }
    }
    private String inputFromUser1,inputFromUser2;

    public GameServer(int port)throws IOException{
        serverSocket = new ServerSocket(port);
    }
    public static void main(String[] args){
        int port = 9001;
        try{
            Thread t = new GameServer(port);
            t.start();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public void run(){
        while(true){
            try{
                Socket server = serverSocket.accept();
                PrintWriter out = new PrintWriter(server.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(server .getInputStream()));
                inputFromUser1 = in.readLine();
                inputFromUser2 = in.readLine();
                out.println(play(getUser1Move(),getUser2Move()));       
            } catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    public String play(Action move1, Action move2) {
        int result;
        String output;
        result = move1.checkActions(move2);
        if(result==0) 
            return output = "User's move " + move1.toString() + "Computer move " 
            + move2.toString() + ", the game is: DRAW";
        else if(result==1) 
            return output = "User's move " + move1.toString() + "Computer move " 
            + move2.toString() + ", You WIN!";
        else 
            return output = "User's move "
Slavi 94 Master Poster Featured Poster

I am not the most experienced person around here but from my experience so far, it really comes to syntax differences, I had to make a banking system in c++ back in the days as a project using multi inheritance and from what I remember the actual differences were:
-creating and deleting objects in c++ by yourself (new, delete) while java has garbige collection
-in c++ you can inherit from multiple classes, in java not exactly, but you can inherit from multiple interfaces which somewhat gets close to the idea behind c++'s multiple inheritance.
As for inheritance its pretty much the same, you need virtual so that the compiler understands it. Also I think there was something with ambigious call error(usage of virtual) but can't remember much about it, if you want you can check the net about it

Slavi 94 Master Poster Featured Poster

Thanks JC, got all I wanted to know

Slavi 94 Master Poster Featured Poster

I made the famous game Scissors, Paper, Rock as console application. The game runs great ... Now I want to make it a bit more advanced and allow 2 clients/users to play against each other from different locations. I checked few tutorials on sockets and networking, and in them they have a field "for multiple client" and when I check that part the pseudo code just shows new thread for each client. For my game with 2 clients, do I need to use that? Also, should I put the game code on the server and only ask the user for an input or proccess everything at the client side and send the server information just to take desicion on who wins and reply back with the winner's name

Slavi 94 Master Poster Featured Poster

Int is a whole number(1,2,3 etc), double is a number with precision and decimal point(23.11). Having this in mind, look at your variables, you might want to switch some around. Also as James said the main method doesn't make sense, it won't compile. If you want an advice, finish your first class first and make sure that it works as expected before starting the next one

Slavi 94 Master Poster Featured Poster

If anyone runs into error like this, the solution is this
private ImageIcon img = new ImageIcon(getClass().getResource("images.jpg"));

changed to this:

URL source = Hangman.class.getResource("images.jpg");
private ImageIcon img = new ImageIcon(source);

worked making jar with eclipse, but doesn't work with cmd

Slavi 94 Master Poster Featured Poster

I made an eclipse project, made a runnable jar from eclipse and I get the same error again >.>

Slavi 94 Master Poster Featured Poster

Um, everything in in the same folder, but not as a package. In order to make jar of multiple files, do they have to be package or just located within the same folder?

Slavi 94 Master Poster Featured Poster

I am trying to create a runnable jar file .. did a few days ago with a single class and worked fine but now it doesn't seem to be working as good with multiple files .. Here is what I did

1) - create manifest.txt the contense of it is Main-class: HangmanLogic
2) - use this command in cmd
C:\Users\User\eclipse\Hangman> jar cvfm Hangman.jar manifest.txt HangmanLogic.class Hangman.class

that returns this in command line:

added manifiest
adding: HangmanLogic.class(in = 3920) (out= 2155)(deflated 45%)
adding: Hangman.class(in = 4700) (out= 2314)(deflated 50%)

3) when I try to run the jar file now using java -jar Hangman.jar I get the following errors

C:\Users\User\eclipse\Hangman>java -jar Hangman.jar
The word is trap and the hint is hint
[ _ ,  _ ,  _ ,  _ ]
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
        at javax.swing.ImageIcon.<init>(Unknown Source)
        at Hangman.<init>(Hangman.java:17)
        at HangmanLogic.<clinit>(HangmanLogic.java:10)

I think it has to do something with the manifest file? Not sure if its supposed to return "Added manifest"

It points to this location in the code in Hangman.java

    private ImageIcon img = new ImageIcon(getClass().getResource("images.jpg"));
    private Icon hanged0 = new ImageIcon( getClass().getResource( "0.png" ));
    private Icon hanged1 = new ImageIcon( getClass().getResource( "11.PNG" ));
    private Icon hanged2 = new ImageIcon( getClass().getResource( "22.PNG" ));
    private Icon hanged3 = new ImageIcon( getClass().getResource( "33.PNG" ));
    private Icon hanged4 = new ImageIcon( getClass().getResource( "44.PNG" ));
    private Icon hanged5 = new ImageIcon( getClass().getResource( "55.PNG" ));

and in HangmanLogic.java
private static Hangman hmGUI = new …

Slavi 94 Master Poster Featured Poster

"Help" you doing it or do it for you? :D

Slavi 94 Master Poster Featured Poster

Array is a fixed size collection, so you have to declear it and cannot change the number of elements in it. Consider using ArrayList instead, it is a collection that can dinamically be allocated, you just add more items in it, look Here

Slavi 94 Master Poster Featured Poster

So static members are needed in main, and not in other methods? Makes sense in a way that using methods you can set/get them but for main if you want to set something you have to have it static, right?

Slavi 94 Master Poster Featured Poster

It's not really a problem that I am facing, more like looking for explanation ... I had this

import java.util.*;
import java.io.*;

public class ReadFile {
    private static int lines=0;
    private static List<String> words=new ArrayList<String>();
    private static String fullLine;
    private static int indexOfSpace;
    private static String getWord;
    private static String getHint;

    public static void main(String[] args) {
    File file = new File("C:\\Users\\User\\eclipse\\readFileAllLines\\words.txt"); //Windows path

        try {

            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line+" "+lines);
                words.add(lines,line);
                lines++;
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        fullLine = words.get(0);
        indexOfSpace = fullLine.indexOf(" ");
        System.out.println(indexOfSpace);
        getWord = fullLine.substring(0,indexOfSpace);
        getHint = fullLine.substring(indexOfSpace+1);
        System.out.println("The word is "+getWord + " and the hint is "+getHint);

    }
}

which works great, but notice that I had to declear my list as static to be able to add elements to it(compiler complained if not static)

Then I wanted to merge the code with the logic of my Hangman Game

import java.util.*;
import java.io.*;

class HangmanLogic{
    private String[] words = {"iwin","iwin","iwin","iwin"}; 
    private static String wordToGuess;
    Random rnd = new Random();
    private static String letter;
    private int wrongGuesses = 0;
    private int guessedLetter;
    private ArrayList<String> al = new ArrayList<String>();
    private static Hangman hmGUI = new Hangman();
    public final String newLine = "\n";


    private static int lines=0;
    private List<String> linesInFile=new ArrayList<String>();
    private static String fullLine;
    private static int indexOfSpace;
    private static String getWord;
    private static String getHint;


    HangmanLogic(Hangman hm){
        this.hmGUI = hm;

        File file = new File("C:\\Users\\User\\eclipse\\readFileAllLines\\words.txt"); //Windows path

        try {
Slavi 94 Master Poster Featured Poster

Here is what you want to do if you want to get the number of occurance

for(int i; i<length<i++)
someLetter = position of the letter at i
check if someLetter equals the letter you are checking for
if it equals, increse index by

indexOf will return the first occurance of "s" in your code, but won't return the total number of occurance

Slavi 94 Master Poster Featured Poster

Nvm, tried it all works ;)

Slavi 94 Master Poster Featured Poster

Hey James, morning

I have the following code that can now read a file, return the number of lines and also return the contense of a line.

public class ReadFile {
    private static int lines=0;
    private static List<String> words=new ArrayList<String>();

    public static void main(String[] args) {
    File file = new File("C:\\Users\\User\\eclipse\\readFileAllLines\\words.txt"); //Windows path

        try {

            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line+" "+lines);
                words.add(lines,line);
                lines++;
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println(words.get(0));
    }
}

Now since I have the file such as
Word1 Hint1
Word2 Hint2
etc ...

I am thinking .. I can use substring to read until the space for the word and also substring after the space until the end of the line for the hint?

EDIT: Since substring is going to return the word and the space afterwards, trim() should remove the black space right?

Slavi 94 Master Poster Featured Poster

Mhm, i had them both up to date ;) is scanner efficient to use for this purpose? I dont see more than 1000 lines in total, from what I found on google scanner is decent for small/middle sized files but noone really pointed out what is middle sized files, I assume with 1000 it should work? Or should I just use windows to finish the program and use BufferedReader?

Slavi 94 Master Poster Featured Poster

Hmm .. I tried using scanner and it magically works :D

File file = new File("/home/slavi/words.txt");

        try {

            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
Slavi 94 Master Poster Featured Poster

Hey James ... I am trying to make any communication at all to my file, currently this is what I have

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("/home/words.txt")))
        {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

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

    }
}

If I run it on my windows laptop it works fine, but it doesn't seem to work on linux, I think it is because of the path? This is the Error list

ReadFile.java:9: '{' expected
        try (BufferedReader br = new BufferedReader(new FileReader("/home/words.txt")))
           ^
ReadFile.java:9: ')' expected
        try (BufferedReader br = new BufferedReader(new FileReader("/home/words.txt")))
                           ^
ReadFile.java:9: ';' expected
        try (BufferedReader br = new BufferedReader(new FileReader("/home/words.txt")))
                                                                                      ^
ReadFile.java:18: 'catch' without 'try'
        } catch (IOException e) {
          ^
ReadFile.java:18: ')' expected
        } catch (IOException e) {
                            ^
ReadFile.java:18: not a statement
        } catch (IOException e) {
                ^
ReadFile.java:18: ';' expected
        } catch (IOException e) {
                              ^
ReadFile.java:9: 'try' without 'catch' or 'finally'
        try (BufferedReader br = new BufferedReader(new FileReader("/home/words.txt")))
        ^
ReadFile.java:23: reached end of file while parsing
}
 ^
9 errors

EDIT: Using pwd found that the path was /home/slavi/textfile but still didnt work

Slavi 94 Master Poster Featured Poster

Thanks :)

Slavi 94 Master Poster Featured Poster

A few days ago, i made a hangman game and I really want to complete it in any aspect. One of my ideas now is to "import" words from a file. Currently what I have is an Array of Strings (just a few words inside for testing) and what I want is a file containing those 2:
Word Hint
word1 Hint1 with spaces
word2 Hint2 with spaces

What I am wondering now is can I import the file and all its context into an array maybe? and then when the game starts use regular expressions such as randomly take a row from the size of the file , then write to the GUI as the word to guess the contense of the row up to the first empty space and then after the space write the contense as Hint area in the GUI. I've had some experience with regular expressions, would they be able to give me the word/hint ? Or any other ways would be appreciated. Also, if this won't work what about 1 file hints, 1 file words, import into ArrayLists and then just get the index of a word and use the same index to get the hint from the other arraylist?

Slavi 94 Master Poster Featured Poster

Actually never mind, i got the game running at the moment seems pretty decent, marking the thread as solved, if I have further questions i ll ask :)

Slavi 94 Master Poster Featured Poster

setResizable(false) should do the trick with the frame, i ll just scale the images to match the panel. Also, I want to add hints for the words. My idea is 2 hashmaps 1 for words and 1 for hints ( hints on same position as the word on the other hashmap), would that work?

Slavi 94 Master Poster Featured Poster

So, for example use GIMP to scale the image to match my Panel and save it as a GIF but why transparent?
Also, how can I set my frame size to be final so it won't be possible for users to resize it?
Would final frame.size(int,int) work?

Slavi 94 Master Poster Featured Poster

Hmm, I have the following now Picture

this is how I get the icon
private Icon hanged1 = new ImageIcon( getClass().getResource( "1.PNG" ));
and then I pass it as parameter for JLabel, which displays the image in JPanel gridLayout(2,1)

Problem - The picture seems a bit small and I really don't like the grey background. How can I extend the size of it? I tried google-ing around but all I found was overriding method paint of JLabel. Is that the only way(looking for something easier/more comfortable)?

Slavi 94 Master Poster Featured Poster

Great advice, thank you

Slavi 94 Master Poster Featured Poster

You are on the right place its just you expect the entire algorithm given at once, if you really want to learn how to do it, start by what you did and ask a specific question about the code where you are stucked, or why does your code not work/what kind of errors you get.