Results 1 to 19 of 19

Thread: Programming Challenge: Chatroom/

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    kshcshbash's Avatar My Good Sir CNSW
    Civitate

    Join Date
    Nov 2005
    Location
    Ontario, Canada
    Posts
    736

    Default Programming Challenge: Chatroom/

    I think we shall start doing the Programming Challenges in two categories:
    Advanced and Regular.

    Advanced is really anything that you wouldn't learn in _LANGUAGE_ For Dummies. Don't put too much weight on it, this is really just to give people a chance.

    Regular Challenge
    Mr. Arial Black coaches an association football (American "soccer") team. He stores all of his player statistics in a file called stats.txt. This file has the name, total goals and appearances of each of his players.

    The format is:
    Name <newline>
    Goals <newline>
    Appearances <newline>
    Code:
    John Smith
    5
    20
    Johnny Cash
    200
    5
    Mr. Black now needs a program that will figure out which player gets the highest number of goals per appearance. Help him out!
    Example output:
    Johnny Cash @ 40/match


    Advanced Challenge
    Write a simple chatroom in a programming/scripting language of your choice.
    It should be able to have a whole two users via some kind of a network (LAN, Internet, Bluetooth etc) at the same time, exchanging messages.
    Very slim specification. Very slim code is all that's required. Get my logic? Anyways, this is highly open ended.
    Enjoy.

    I hope I haven't made them overly difficult!
    And to code an entry for each one, now...
    Last edited by kshcshbash; April 12, 2007 at 09:51 PM.
    Simetrical's homeboy, yo.
    You take the blue pill and the story ends. You wake in your bed and you believe whatever you want to believe. You take the red pill and you stay in Wonderland and I show you how deep the rabbit-hole goes. Remember -- all I am offering is the truth, nothing more.

    Sign up to learn Java!

  2. #2

    Default Re: Programming Challenge: Chatroom/

    Are those two users on the same computer? Two terminals of the same computer? Two computers using the same file-system? The internet?

  3. #3
    kshcshbash's Avatar My Good Sir CNSW
    Civitate

    Join Date
    Nov 2005
    Location
    Ontario, Canada
    Posts
    736

    Default Re: Programming Challenge: Chatroom/

    Fun Java hint because I have to reformat my laptop NOW, and I won't have time to finish the code.
    Code:
    //player.java
    
    import java.text.DecimalFormat;
    
    class player {
    	private String name;
    	private double ratio;
    	private int matches;
    	private int goals;
    
    	public player(String name, int matches, int goals){
    		this.name = name;
    		this.matches = matches;
    		this.goals = goals;
    		this.ratio = goals/matches;
    	}
    
    	public String retName(){
    		return name;
    	}
    
    	public double retRatio(){
    		DecimalFormat decFrm =
    			new DecimalFormat("	.00"); // Two decimal places. DecimalFormat has it's own formatting; 0 represents ANY digit.
    		return decFrm.format(this.ratio);		
    	}
    }

    Lee: If you can code two users on the same FS in a chatroom, go for it. I was more thinking along the lines of the same network (LAN or Internet). I think almost everyone will just write a server @ localhost and client, and open two client windows and talk to ...themselves. I'll update it.
    Simetrical's homeboy, yo.
    You take the blue pill and the story ends. You wake in your bed and you believe whatever you want to believe. You take the red pill and you stay in Wonderland and I show you how deep the rabbit-hole goes. Remember -- all I am offering is the truth, nothing more.

    Sign up to learn Java!

  4. #4
    chris_uk_83's Avatar Physicist
    Join Date
    Feb 2007
    Location
    Lancaster, England
    Posts
    818

    Default Re: Programming Challenge: Chatroom/

    You've already beaten me to most of the Java solution , and I only know Java for Dummies so there's no way I could do the chatroom problem. Nevertheless I may have a go today, maybe put it in an applet or something.

  5. #5

    Default Re: Programming Challenge: Chatroom/

    Well, I have no clue how to actually write anything regarding networks.

    As for the file system solution, I will code it up tormmow

  6. #6
    chris_uk_83's Avatar Physicist
    Join Date
    Feb 2007
    Location
    Lancaster, England
    Posts
    818

    Default Re: Programming Challenge: Chatroom/

    CNSW, I've been experimenting with that DecimalFormat object, which looks quite cool, but I'm having problems with it. Even when I hand it a double (even resorting to copy pasting your code to make sure my syntax was correct) it tells me it's found a String and will only take a double, wtf!?

  7. #7
    kshcshbash's Avatar My Good Sir CNSW
    Civitate

    Join Date
    Nov 2005
    Location
    Ontario, Canada
    Posts
    736

    Default Re: Programming Challenge: Chatroom/

    Might I see your code?
    Simetrical's homeboy, yo.
    You take the blue pill and the story ends. You wake in your bed and you believe whatever you want to believe. You take the red pill and you stay in Wonderland and I show you how deep the rabbit-hole goes. Remember -- all I am offering is the truth, nothing more.

    Sign up to learn Java!

  8. #8
    chris_uk_83's Avatar Physicist
    Join Date
    Feb 2007
    Location
    Lancaster, England
    Posts
    818

    Default Re: Programming Challenge: Chatroom/

    Code:
    import java.text.*;
    
    class player {
    	private String name;
    	public double ratio;
    	private double matches;
    	private double goals;
            
    	public player(String name, double matches, double goals){
    		this.name = name;
    		this.matches = matches;
    		this.goals = goals;
    		this.ratio = goals/matches;
    	}
    
    	public String retName(){
    		return name;
    	}
    
    	public String retRatio(){
    		DecimalFormat decFrm =
    			new DecimalFormat(".00"); // Two decimal places. DecimalFormat has it's own formatting; 0 represents ANY digit.
    		return decFrm.format(this.ratio);               
    	}
    }
    There you go, that's your player class fixed so it compiles and gives the right answer. DecimalFormat needed to import java.text, it also returns a String, not a double. It also seems that if you divide an int by and int, you can only get an int as an answer, even if a double is allocated to the answer; so I changed all the ints used in finding the ratio to doubles, now it seems to work.

    Took me ages staring at documentation to work this out though coz I'm such a noob

  9. #9
    kshcshbash's Avatar My Good Sir CNSW
    Civitate

    Join Date
    Nov 2005
    Location
    Ontario, Canada
    Posts
    736

    Default Re: Programming Challenge: Chatroom/

    Excellent

    Yeah, I didn't ever even get around to compiling that code. I wrote it in Notepad.

    Nice job +rep for problem solving skillz
    Simetrical's homeboy, yo.
    You take the blue pill and the story ends. You wake in your bed and you believe whatever you want to believe. You take the red pill and you stay in Wonderland and I show you how deep the rabbit-hole goes. Remember -- all I am offering is the truth, nothing more.

    Sign up to learn Java!

  10. #10
    chris_uk_83's Avatar Physicist
    Join Date
    Feb 2007
    Location
    Lancaster, England
    Posts
    818

    Default

    Thanks!

    I'm now working on a way to get the info into a file. Getting it back out again may prove problematic for me though, as I'm no expert on java.io. I can just about manage a FileWriter with some help from the doc and my magic textbook, but reading patterns in order to retrieve the right bits of text is a little beyond my 1337 skillz at the moment. I'll try though. Ooh, maybe a map could be useful......more reading needed.

    Any chance you could take a quick look at this code for me? It's my addition to your Java program that takes inputs from the console and turns them into an array of Players.

    I keep getting a null pointer exception when I try to add a player to the array. This is understandable if the array has no length to it, but I thought that the way I've initialized it means it changes its length to fit its contents.

    I also think I've overused static

    Code:
    import java.text.*;
    import java.io.*;
    
    class Player {
    	private String name;
    	public double ratio;
    	private double matches;
    	private double goals;
            
    	public Player(String name, double matches, double goals){
    		this.name = name;
    		this.matches = matches;
    		this.goals = goals;
    		this.ratio = goals/matches;
    	}
    
    	public String retName(){
    		return name;
    	}
    
    	public String retRatio(){
    		DecimalFormat decFrm =
    			new DecimalFormat(".00"); // Two decimal places. 
                    //DecimalFormat has it's own formatting; 0 represents ANY digit.
    		return decFrm.format(this.ratio);               
    	}   
            public String toString() {
                return "Name: " + name + "\nmatches played: " + matches
                        + "\ngoals scored: " + goals + "\ngoals per match: "
                        + retRatio();
            }        
    }
    
    public class Football {
        static Player[] player;
        static int count = 0;
        static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        static boolean cont = true;
        
        
        public static void playerInput() throws IOException {
            String name;
            double goals = 0;
            double matches = 0;        
            System.out.println("Enter name: ");
            name = in.readLine();
            System.out.println("Enter matches played: ");        
            matches = Double.parseDouble(in.readLine());
            System.out.println("Enter goals scored: ");
            goals = Double.parseDouble(in.readLine());
            player[count] = new Player(name, matches, goals);
            count++;        
        }
        
        public static void playerOutput() {
            for(int j = 0; j <= count; j++)
                System.out.println(player[j] + "\n");
        }
        
        public static void main(String[] args) throws IOException{
            String s = "y";
            String st = "y";
            while(s.equals(st)) {   
                System.out.println(s);
                System.out.println(st);
                playerInput();
                System.out.println("Enter another player? y/n");  
                st = in.readLine();            
            }
            playerOutput();
        }
    }
    Last edited by Nihil; April 13, 2007 at 09:53 AM. Reason: double post merged

  11. #11
    Nihil's Avatar Annihilationist
    Join Date
    Feb 2005
    Location
    Dublin, Ireland
    Posts
    2,221

    Default Re: Programming Challenge: Chatroom/

    Ha! This is fun, I think I can get the chat program to work. I'm writing it in java. Needs some work still, but I'll post it soon.

    And here it is:

    Code:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    
    public class Chat{
        public static void main(String[] args) throws IOException {
    
    	DatagramSocket socketin = null;
        	boolean more = true;
    	int port = 5050;
    
        	try {
    	            socketin = new DatagramSocket(port);
    		    System.out.println("\nUDP socket (port " + port + "):");
    		}
    		catch( SocketException se ) {
    		    se.printStackTrace();
    		    System.exit( 1 );
    		}
    
    
    		// Set IP address
    	 	String connectIP = "192.168.1.100";   // default IP address
    		if (args.length == 1) {
    	   		connectIP = new String( args[0]);
    		}
    		else{
    			connectIP = JOptionPane.showInputDialog("Enter Connection IP address\nDefault: " + connectIP );
    		}
    
        	if( connectIP.equals("") )
                connectIP = "192.168.1.100";      // default IP address
    
           	InetAddress addr= InetAddress.getByName( connectIP );
    
    	System.out.println(	"\nConnected to: " + addr );
    
    	while (true) {
    
                     String msg = "";
    	 	msg = JOptionPane.showInputDialog("Send Message: " );
    
     		byte[] outBuf = new byte[256];
     		outBuf = msg.getBytes();
    
    		DatagramPacket outPacket = new DatagramPacket(outBuf, outBuf.length, addr, port);
    
    		DatagramSocket socketout = new DatagramSocket();
    
                     socketout.send(outPacket);
    
      	         try {
       			byte[] receiveData = new byte[50000];
                             DatagramPacket inPacket = new DatagramPacket(receiveData, receiveData.length);
    			socketin.receive(inPacket);
    		        String message = new String( inPacket.getData(), 0, inPacket.getLength() );
                             System.out.println( "\nMessage received: " + message );
    
    	        } catch (IOException e) {
                e.printStackTrace();
                more = false;
    		}
    	}
        }
    }
    Gah, my formatting is arsed.

    It needs to be opened on both computers.The only problem is that the first message is always lost, because the program only listens after sending a message. So, to await a message, just send a blank message and then wait to receive.

    I have crude database program I wrote in C that I could probably use to do the other one. It only ever worked with Borland Turbo C, though.
    Last edited by Nihil; April 13, 2007 at 11:23 AM.
    Ex Nihilo, Nihil Fit.
    Acting Paterfamilias of House Rububula
    Former Patron of the retired Atheist Peace
    Current Lineup: Jesus The Inane, PacSubCom, Last Roman, Evariste, I Have a Clever Name, Gabriella26, Markas and Katrina

  12. #12
    Civitate
    Join Date
    Jul 2005
    Location
    Scotland
    Posts
    13,565

    Default Re: Programming Challenge: Chatroom/

    I wish I could program . . .
    Under the patronage of Rhah and brother of eventhorizen.

  13. #13

    Default Re: Programming Challenge: Chatroom/

    Code:
    import java.io.*
    
    public class ShaunCanProgram {
    public static void main(String[] args) throws IOException {
    
    System.out.println("Shaun Can Program" );
    
    }
    }
    I would write the chat program if I could be bothered...but unless a university mark is hinging on it my motivation lacks conviction.

    Also, Nihil, in your program, couldn't you just type:
    !more;

    instead of

    more = false;

    ???

    Edit: Or does that only work for conditional statements? eg If(!more) (Too long out the java loop for me).

  14. #14
    Nihil's Avatar Annihilationist
    Join Date
    Feb 2005
    Location
    Dublin, Ireland
    Posts
    2,221

    Default Re: Programming Challenge: Chatroom/

    Quote Originally Posted by Aristocrat View Post

    Also, Nihil, in your program, couldn't you just type:
    !more;

    instead of

    more = false;

    ???

    Edit: Or does that only work for conditional statements? eg If(!more) (Too long out the java loop for me).
    Probably. There's always a million ways to do things. I usually just stick with the first thing that works, particularly if it's just for fun.
    Ex Nihilo, Nihil Fit.
    Acting Paterfamilias of House Rububula
    Former Patron of the retired Atheist Peace
    Current Lineup: Jesus The Inane, PacSubCom, Last Roman, Evariste, I Have a Clever Name, Gabriella26, Markas and Katrina

  15. #15
    Erik's Avatar Dux Limitis
    Join Date
    Aug 2004
    Location
    Amsterdam
    Posts
    15,653

    Default Re: Programming Challenge: Chatroom/

    Quote Originally Posted by Aristocrat View Post
    Also, Nihil, in your program, couldn't you just type:
    !more;

    instead of

    more = false;

    ???

    Edit: Or does that only work for conditional statements? eg If(!more) (Too long out the java loop for me).
    It only works for conditional statements.
    !more; and more=false; are two completely different things:
    more = false; assigns a new value to more, and returns the same value. ("false" in this case)
    !more; returns either false or true depending on the value of more, it doesn't change the value of more.

    more == false; is the same as !more;

    To prevent confusion you can use more:=false; instead of more=false; to indicate that it's an assignment and not a conditional statement.
    := and = is the same in C/C++/Java and many other languages, but not in every computer language.

    Quote Originally Posted by Nihil View Post
    Probably. There's always a million ways to do things. I usually just stick with the first thing that works, particularly if it's just for fun.
    Not me, I like to re-think my code to make it as aesthetic as possible.
    I can really appreciate beautiful code, and really hate ugly code.
    Last edited by Erik; April 14, 2007 at 09:49 AM.



  16. #16
    Simetrical's Avatar Former Chief Technician
    Patrician

    Join Date
    Nov 2004
    Location
    θ = π/0.6293, φ = π/1.293, ρ = 6,360 km
    Posts
    20,154

    Default Re: Programming Challenge: Chatroom/

    I was writing a one-line shell script to do the "regular" challenge, but gave up when expr seemed to be too ornery to work without a for statement.
    Quote Originally Posted by Erik View Post
    To prevent confusion you can use more:=false; instead of more=false; to indicate that it's an assignment and not a conditional statement.
    := and = is the same in C/C++/Java and many other languages, but not in every computer language.
    := does not work in C(++). It's a syntax error, as you can see from the BNF. Java BNF also appears not to include it. Have you tried compiling it, or do you have a reference to appropriate standards? := isn't used in any mainstream modern language, to my knowledge.
    MediaWiki developer, TWC Chief Technician
    NetHack player (nao info)


    Risen from Prey

  17. #17
    Erik's Avatar Dux Limitis
    Join Date
    Aug 2004
    Location
    Amsterdam
    Posts
    15,653

    Default Re: Programming Challenge: Chatroom/

    Quote Originally Posted by Simetrical View Post
    := does not work in C(++). It's a syntax error, as you can see from the BNF.
    You are right, I was mistaken

    Have you tried compiling it, or do you have a reference to appropriate standards? := isn't used in any mainstream modern language, to my knowledge.
    I have never actually used := at all, but I thought my professor said that it was possible.
    I've learned many programming and other formal languages at university.

    On second thought I think := stands for assignment in logics, but apparently not in programming.



  18. #18
    kshcshbash's Avatar My Good Sir CNSW
    Civitate

    Join Date
    Nov 2005
    Location
    Ontario, Canada
    Posts
    736

    Default Re: Programming Challenge: Chatroom/

    Pascal!

    It's as modern as they come. Only, not.
    Simetrical's homeboy, yo.
    You take the blue pill and the story ends. You wake in your bed and you believe whatever you want to believe. You take the red pill and you stay in Wonderland and I show you how deep the rabbit-hole goes. Remember -- all I am offering is the truth, nothing more.

    Sign up to learn Java!

  19. #19
    chris_uk_83's Avatar Physicist
    Join Date
    Feb 2007
    Location
    Lancaster, England
    Posts
    818

    Default Re: Programming Challenge: Chatroom/

    Can somebody (possible CNSW) help me out here?

    I'm having trouble getting my java program to format the text properly in a file. I can either make it format nicely and remove all data every time the program is run (using println()), or I can make it add data with terrible formatting (with append()). EDIT: No, actually data is removed whatever I do.

    Here's the method:

    Code:
    public void playerFileOutput() throws IOException {
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("stats.txt")));
            for(int j = 0; j <= count; j++) {
                out.write(player[j] + "\n");
                out.write("========================" + "\n");            
            }
            out.close();
        }
    and here's the Player class' toString() method:

    Code:
    public String toString() {
                return "Name: " + name + "\nmatches played: " + matches
                        + "\ngoals scored: " + goals + "\ngoals per match: "
                        + retRatio();
            }
    It's pretty easy to work out what all the variables are becasue they have nice names :p

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •