Solved

What's wrong with this simple code?

Posted on 2009-04-07
11
243 Views
Last Modified: 2013-11-23
Hi I have this method... whenever I call it with a valid argument... i.e

sinkEnemy("carrier")

it always evaluates to the last else statement.  I always get, "error during sinking enemy ship for all calls that I am making.

Is it supposed to be ship.equals("carrier") etc
public void sinkEnemy(String ship){

		 if(ship=="carrier"){

			 for(int i=0; i<enemyCarrier.size(); i++){

				 int r = enemyCarrier.get(i).getRow();

				 int c = enemyCarrier.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 }		 }

		 if(ship=="battleship"){

			 for(int i=0; i<enemyBattleship.size(); i++){

				 int r = enemyBattleship.get(i).getRow();

				 int c = enemyBattleship.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 } 		 }

		 if(ship=="destroyer"){

			 for(int i=0; i<enemyDestroyer.size(); i++){

				 int r = enemyDestroyer.get(i).getRow();

				 int c = enemyDestroyer.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 }		 }

		 if(ship=="submarine"){

			 for(int i=0; i<enemySubmarine.size(); i++){

				 int r = enemySubmarine.get(i).getRow();

				 int c = enemySubmarine.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 }		 }

		 if(ship=="patrol boat"){

			 for(int i=0; i<enemyPatrolBoat.size(); i++){

				 int r = enemyPatrolBoat.get(i).getRow();

				 int c = enemyPatrolBoat.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 }		 }

		 else{ 	System.out.println("error during sinking enemy ship. the actual name is "+ship );		 }

	 }

Open in new window

0
Comment
Question by:ubuntuguy
  • 3
  • 3
  • 2
  • +2
11 Comments
 
LVL 3

Assisted Solution

by:hottroc
hottroc earned 120 total points
Comment Utility
You can't use default properties. Depending on your ship class you need something like ship.text or ship.value or ship.type.
0
 
LVL 92

Assisted Solution

by:objects
objects earned 120 total points
Comment Utility
>                  if(ship=="carrier"){

should be:

                 if(ship.equals("carrier")){

same for other if's

0
 
LVL 3

Assisted Solution

by:hottroc
hottroc earned 120 total points
Comment Utility
Sorry that's wrong, you're ship isn't an object. Ignore me it's late.
0
 
LVL 3

Assisted Solution

by:hottroc
hottroc earned 120 total points
Comment Utility
doh, posts crossed, mine's wrong, not Savant's.
0
 
LVL 1

Accepted Solution

by:
hadesflames5855 earned 220 total points
Comment Utility
I'm not so sure .equals() would matter but it is recommended for comparing strings. Also you should make it .equalsIgnoreCase() that way it would not matter if it is Carrier or carrier.

Also if changing to .equals does not work could you paste the whole code so that i can analyze the whole program?
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 1

Author Comment

by:ubuntuguy
Comment Utility
Well here is the code for this class... not sure if you want the whole program, but I have 23 classes... it's too much code.

package proj4;
 

import javax.swing.JCheckBoxMenuItem;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JOptionPane;

import javax.swing.SwingUtilities;

import javax.swing.border.TitledBorder;
 

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;
 

import java.net.*;

import java.util.StringTokenizer;

import java.util.Vector;

import java.io.*;
 

/**

 * While working really hard to be able to send DataPacket objects over the network, I wasn't able to

 * get it to work so instead I'm simply sending a String that has commands delimited by a comma (,). The message is

 * read based on the integer at the beginning of the line as follows:

 * 1. "Shot", Coordinate(where shot was fired), isTurn(false so it is the oponents turn now)

 * 2. "NoHit", Coordinate, isTurn

 * 3. "Hit", Coordinate, Ship Hit, isTurn

 * 4. "Sunk", Coordinate, Ship Hit, Ship Sunk, youWin?

 * 5. "Enemy Name"

 * 6. "Play Again", boolean

 * 7. "Message", string 

 *

 */
 

public class GameBoard extends JFrame {
 

	private static final long serialVersionUID = 1L;
 

	JMenuBar menuBar;

	JMenu gameMenu, optionsMenu, helpMenu;

	JMenuItem newServerItem, newClientItem, exitItem, aboutItem, helpItem, settingsItem, disconnectItem;

	JCheckBoxMenuItem soundItem;

	Container contents;

		

	Game game;

	Messages msg;

	

	Listener listener;

	EnemyListener enemyListener;

	

	///////////////////

	Socket communicationSocket = null;

	PrintWriter outStream = null;

	BufferedReader inStream = null;

	Boolean communicationContinue = true;

	String disconnectString = "disconnect";

	String dataPacket = "";

	boolean goesFirst;

	

	Vector <Coordinate> enemyCarrier, enemyBattleship, enemySubmarine, enemyDestroyer, enemyPatrolBoat;

		

	//DataPacket inPacket, outPacket;

	String text = ""; //for putting on status pannel

	final static String newline = "\n"; //for text areaa display
 

	public GameBoard(){

		super("Battleship V 1.01");

		setSize(765,520);

		setResizable(false);

		contents = getContentPane();

		contents.setLayout(new BorderLayout());

		game = new Game();

		msg = new Messages();

		contents.add(game, BorderLayout.NORTH);

		
 

		

		menuBar = new JMenuBar();

		gameMenu = new JMenu();

		optionsMenu = new JMenu();

		helpMenu = new JMenu();

		

		newServerItem = new JMenuItem();

		newClientItem = new JMenuItem();

		disconnectItem = new JMenuItem();

		exitItem = new JMenuItem();

		aboutItem = new JMenuItem();

		helpItem = new JMenuItem();

		settingsItem = new JMenuItem();

		soundItem = new JCheckBoxMenuItem();

		

		

		gameMenu.setText("Game");

		optionsMenu.setText("Options");

		helpMenu.setText("Help");

		newServerItem.setText("New Server Game");

		newClientItem.setText("New Client Game");

		disconnectItem.setText("Disconnect");

		exitItem.setText("Exit");

		aboutItem.setText("About");

		helpItem.setText("Help");

		settingsItem.setText("Settings");

		soundItem.setText("Sound");

		

		//adding components

		setJMenuBar(menuBar);

		menuBar.add(gameMenu);

		menuBar.add(optionsMenu);

		menuBar.add(helpMenu);

		

		gameMenu.add(newServerItem);

		gameMenu.add(newClientItem);

		gameMenu.addSeparator();

		gameMenu.add(disconnectItem);

		gameMenu.addSeparator();

		gameMenu.add(exitItem);

		

		optionsMenu.add(settingsItem);

		optionsMenu.addSeparator();

		optionsMenu.add(soundItem);

		

		helpMenu.add(helpItem);

		helpMenu.addSeparator();

		helpMenu.add(aboutItem);

		

		disconnectItem.setEnabled(false);

		//inPacket = new DataPacket();

		//outPacket = new DataPacket();

		enemyCarrier = new Vector<Coordinate>();

		enemyBattleship = new Vector<Coordinate>();

		enemySubmarine = new Vector<Coordinate>();

		enemyDestroyer = new Vector<Coordinate>();

		enemyPatrolBoat = new Vector<Coordinate>();

		

		

		listener = new Listener();

		newServerItem.addActionListener(listener);

		newClientItem.addActionListener(listener);

		exitItem.addActionListener(listener);

		settingsItem.addActionListener(listener);

		soundItem.addActionListener(listener);

		helpItem.addActionListener(listener);

		aboutItem.addActionListener(listener);

		game.sendButton.addActionListener(listener);

		game.message.addKeyListener(new KeyAdapter(){

			public void keyTyped(KeyEvent ke){

				if(ke.getKeyChar()==KeyEvent.VK_ENTER){

					sendMessage(game.message.getText());

					game.addUserMessage(game.message.getText());

					game.message.setText("");

				}

			}

		});

		

		

		enemyListener = new EnemyListener();

		for(int x=1; x<=10; x++){

			for(int y=1; y<=10; y++){

				game.battlefield.enemy.grid[x][y].addActionListener(enemyListener);

			}

		}

		game.battlefield.enemy.enableOcean();

		//game.battlefield.setEnabled(false);

		/////////////////////////
 

		

		 

	}

	

	

	

	public void refresh(){

		SwingUtilities.updateComponentTreeUI(this);

	}

	

	

	

	public void setCommunicationSocket(Socket sock){

		communicationSocket = sock;

		communicationContinue = true;

		disconnectItem.setEnabled(true);

	}

	

	public void setOutStream(PrintWriter out){ 

	    outStream = out;

	   }
 

	 public void setInStream(BufferedReader in){

	    inStream = in;

	   }
 

	 public void setUpServer(){ 

	    ServerThread st = new ServerThread (this);

	    st.start();

	   } 
 
 

	 public  void setUpClient() {

	    ClientThread st = new ClientThread (this);

	    st.start();

	   }
 

	 public void disconnectClientServer(Boolean sendMessage){

	    if (communicationSocket == null)

	       return;

	    try {

	         // shut down socket read loop

	         communicationContinue = false;

	         disconnectItem.setEnabled (false);

	         // send notification to other end of socket

	         if (sendMessage == true)

	             outStream.println(disconnectString);

	        	 

	         // sleep to let read loop shut down

	         Thread t = Thread.currentThread(); 

	         try{ 

	        	 t.sleep(500); 

	        	 } 

	         catch(InterruptedException ie){ 

	        	 return; 

	        	 }

	         outStream.close(); 

	         inStream.close(); 

	         communicationSocket.close(); 

	        }

	    catch (IOException e){ 

	         System.err.println("Stream Read Failed."); 

	         JOptionPane.showMessageDialog( GameBoard.this, "Disconnection Failed", "SimpleChat", JOptionPane.PLAIN_MESSAGE );

	         return; 

	        } 

	    finally{ 

	         communicationSocket = null; 

	        }

	   }
 

	 

	 public void sendData (){

	    if(communicationSocket != null){

	        //String data = dataPacket;

	        outStream.println(dataPacket);

	        //System.out.println("data sent"); //debugging purpose

	       }

	   }
 
 

	 public void getData(){

	    String inputLine; 

	    try{

	       while(communicationContinue == true){

	              communicationSocket.setSoTimeout(100);

	              //System.out.println ("Waiting for Connection");

	             try{

	            	 while(((inputLine = inStream.readLine()) != null)){ 

	                        System.out.println ("From Socket: " + inputLine); //here add decodeString or something

	                        if (inputLine.equals(disconnectString)){

	                            disconnectClientServer(false);

	                            return;

	                           }

	                        	//System.out.println("From Client: "+inputLine); //for debugging

	                        	decodeInput(inputLine);

	                         }

	                  }

	              catch (SocketTimeoutException ste){

	                   //System.out.println ("Timeout Occurred");

	                  }

	             } // end of while loop

	          System.out.println ("communication is false");

	        }

	    catch (IOException e){ 

	         System.err.println("Stream Read Failed."); 

	         JOptionPane.showMessageDialog( GameBoard.this, "Input Stream read failed", "SimpleChat", JOptionPane.PLAIN_MESSAGE );

	         return; 

	        } 

	   }

	 public void decodeInput(String input){  //when reading message from enemy

		 String [] str = input.split(",");

		 int code = Integer.parseInt(str[0]);

		 switch(code){

		 case 1:	int row = Integer.parseInt(str[1]); int col = Integer.parseInt(str[2]);	

		 			if(game.battlefield.ocean.grid[row][col].isFree()){

		 				game.battlefield.ocean.grid[row][col].setSplash();

		 				game.battlefield.ocean.grid[row][col].setEnabled(false);

		 				//game.battlefield.enemy.permanetKill(new Coordinate(row,col));

		 				game.addEnemyMessage("fired on coordinate" + new Coordinate(row,col).toString());

		 				//game.battlefield.enemy.smartEnable();

		 				game.battlefield.enemy.enableOcean();

		 				game.battlefield.enemy.smartDisable();

		 				checkBoats(new Coordinate(row,col));

		 				sendResultNoHit(new Coordinate(row,col)); break;

		 				

		 				

		 			}

		 			else{

		 				game.battlefield.ocean.grid[row][col].setHit();

		 				game.battlefield.ocean.grid[row][col].setEnabled(false);

		 				String boat = this.findBoat(new Coordinate(row,col));

		 				game.addEnemyMessage("fired on coordinate" + new Coordinate(row,col).toString());

		 				game.addEnemyMessage("Hit your "+ boat);

		 				addShot(new Coordinate(row,col), boat);

		 				//game.battlefield.enemy.smartEnable();

		 				game.battlefield.enemy.enableOcean();

		 				game.battlefield.enemy.smartDisable();

		 				checkBoats(new Coordinate(row,col));

		 				sendResultHit(new Coordinate(row,col),boat); break;

		 			}

		 case 2:	int row2 = Integer.parseInt(str[1]); int col2 = Integer.parseInt(str[2]);

			 		game.battlefield.enemy.grid[row2][col2].setSplash();

			 		game.addUserMessage("wasted a bomb. You missed!");

			 		game.battlefield.enemy.grid[row2][col2].setEnabled(false); break;

		 			

		 case 3:	int row3 = Integer.parseInt(str[1]); int col3 = Integer.parseInt(str[2]);

		 			game.battlefield.enemy.grid[row3][col3].setHit();

		 			game.battlefield.enemy.grid[row3][col3].setEnabled(false); 

		 			game.addUserMessage("Hit the enemy's "+ str[3]); break;

		 case 4:	System.out.println(str[1]);

		 			String toSink = str[1];

		 			game.addSystemMessage("You sank the enemy's "+str[1]);

			 		sinkEnemy(toSink); break;

		 case 5: 	System.out.println("Not yet implemented"); break;

		 //case 6: 	game.enemyName = str[1]; break;

		 case 7:	String s = "";

			 		for(int i=1; i<str.length; i++){

			 			s+=str[i];

			 		}

			 		game.addEnemyMessage(s);break;

			 				 

		 default:	System.out.println("I gave up");			break;

		 }

		 

	 }
 
 

	 public void sendShot(Coordinate coord){

		 dataPacket= 1+","+coord.getRow()+","+coord.getColumn();

		 sendData();

		 }

	 public void sendResultNoHit(Coordinate coord){

		 dataPacket = 2+","+coord.getRow()+","+coord.getColumn();

		 sendData();

		 }

	 public void sendResultHit(Coordinate coord, String ship){//, String ship){

		 dataPacket = 3+","+coord.getRow()+","+coord.getColumn()+","+ship;;//+","+ship;

		 sendData();

		 }

	 public void sendResultSunk(String ship){

		 dataPacket = 4+","+ship;

		 sendData();

		 }

	 public void continuePlaying(String play){

		 dataPacket = 5+","+play;

		 }

	 //public void sendName(String name){

	//	 dataPacket = 6+","+name;

	//	 sendData();

	//	 }

	 public void sendMessage(String msg){

		 dataPacket = 7+","+msg;

		 sendData();

		 }

	 

	 public void checkCarrier(Coordinate coord){

		 if(game.carrier.isDestroyed){ System.out.println("Carrier already destroyed"); }

		 else{

			 for(int i=0; i<game.carrier.coordinates.length; i++){

				 if(game.carrier.coordinates[i].isEquals(coord)){

					 game.carrier.hitNumber++;

					 if(game.carrier.hitNumber==5){

						 game.carrier.isDestroyed=true;

						 this.game.sinkShip(game.carrier);

						 sendResultSunk("carrier");

					 }	 }	 }	 }	 }

	 public void checkBattleship(Coordinate coord){

		 if(game.battleship.isDestroyed){System.out.println("Battleship already destroyed"); }

		 else{

			 for(int i=0; i<game.battleship.coordinates.length; i++){

				 if(game.battleship.coordinates[i].isEquals(coord)){

					 game.battleship.hitNumber++;	

					 if(game.battleship.hitNumber==4){

						 game.battleship.isDestroyed=true;

						 this.game.sinkShip(game.battleship);

						 sendResultSunk("battleship");

						 }	 }	 }	 }	 }

	 public void checkSubmarine(Coordinate coord){

		 if(game.submarine.isDestroyed){System.out.println("Submarine already destroyed"); }

		 else{

			 for(int i=0; i<game.submarine.coordinates.length; i++){

				 if(game.submarine.coordinates[i].isEquals(coord)){

					 game.submarine.hitNumber++;	

					 if(game.submarine.hitNumber==3){

						 game.submarine.isDestroyed=true;

						 this.game.sinkShip(game.submarine);

						 sendResultSunk("submarine");

						 }	 }	 }	 } }

	 	 public void checkDestroyer(Coordinate coord){

		 if(game.destroyer.isDestroyed){System.out.println("Destroyer already destroyed"); }

		 else{

			 for(int i=0; i<game.destroyer.coordinates.length; i++){

				 if(game.destroyer.coordinates[i].isEquals(coord)){

					 game.destroyer.hitNumber++;

					 if(game.destroyer.hitNumber==3){

						 game.destroyer.isDestroyed=true;

						 this.game.sinkShip(game.destroyer);

						 sendResultSunk("destroyer");

						 }	 }	 }		 }	 }

	 public void checkPatrol(Coordinate coord){

		 if(game.patrolBoat.isDestroyed){System.out.println("Patrol boat already destroyed");}

		 else{

			 for(int i=0; i<game.patrolBoat.coordinates.length; i++){

				 if(game.patrolBoat.coordinates[i].isEquals(coord)){

					 game.patrolBoat.hitNumber++;

					 if(game.patrolBoat.hitNumber==2){

						 game.patrolBoat.isDestroyed=true;

						 this.game.sinkShip(game.patrolBoat);

						 sendResultSunk("patrol boat");

						 }	 }	 }	 }	 }

	 public void checkBoats(Coordinate coord){

		 this.checkCarrier(coord);

		 this.checkBattleship(coord);

		 this.checkSubmarine(coord);

		 this.checkDestroyer(coord);

		 this.checkPatrol(coord);

	 }

	 

	 public String findBoat(Coordinate coord){

		 String boatHit ="";

		 boolean flag = false;

		 while(!flag){

			 for(int i=0; i<game.carrier.coordinates.length; i++){

				 if(game.carrier.coordinates[i].isEquals(coord)){

					 boatHit = game.carrier.name;

					 flag = true;	 }		 }

			 for(int i=0; i<game.battleship.coordinates.length; i++){

				 if(game.battleship.coordinates[i].isEquals(coord)){

					 boatHit = game.battleship.name;

					 flag = true;	}			 }

			 for(int i=0; i<game.submarine.coordinates.length; i++){

				 if(game.submarine.coordinates[i].isEquals(coord)){

					 boatHit = game.submarine.name;

					 flag = true;	}			 }

			 for(int i=0; i<game.destroyer.coordinates.length; i++){

				 if(game.destroyer.coordinates[i].isEquals(coord)){

					 boatHit = game.destroyer.name;

					 flag = true;	}			 }

			 for(int i=0; i<game.patrolBoat.coordinates.length; i++){

				 if(game.patrolBoat.coordinates[i].isEquals(coord)){

					 boatHit = game.patrolBoat.name;

					 flag = true;	}			 }

		 }

		 return boatHit;
 

	 }

	 

	 

	 public void addShot(Coordinate coord, String ship){

		 if(ship=="carrier"){ enemyCarrier.add(coord); }

		 else if(ship=="battleship"){ enemyBattleship.add(coord);}

		 else if(ship=="destroyer"){ enemyDestroyer.add(coord);}

		 else if(ship=="submarine"){ enemySubmarine.add(coord);}

		 else if(ship=="patrol boat"){enemyPatrolBoat.add(coord);}

		 else{System.out.println("Error addinng coordinate to enemy ship");}

		}

	 

	 public void sinkEnemy(String ship){

		 if(ship.equals("carrier")){

			 for(int i=0; i<enemyCarrier.size(); i++){

				 int r = enemyCarrier.get(i).getRow();

				 int c = enemyCarrier.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 }		 }

		 else if(ship.equals("battleship")){

			 for(int i=0; i<enemyBattleship.size(); i++){

				 int r = enemyBattleship.get(i).getRow();

				 int c = enemyBattleship.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 } 		 }

		 else if(ship.equals("destroyer")){

			 for(int i=0; i<enemyDestroyer.size(); i++){

				 int r = enemyDestroyer.get(i).getRow();

				 int c = enemyDestroyer.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 }		 }

		 else if(ship.endsWith("submarine")){

			 for(int i=0; i<enemySubmarine.size(); i++){

				 int r = enemySubmarine.get(i).getRow();

				 int c = enemySubmarine.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 }		 }

		 else if(ship.equals("patrol boat")){

			 for(int i=0; i<enemyPatrolBoat.size(); i++){

				 int r = enemyPatrolBoat.get(i).getRow();

				 int c = enemyPatrolBoat.get(i).getColumn();

				 game.battlefield.enemy.grid[r][c].setSunk();		 }		 }

		 else{ 	System.out.println("error during sinking enemy ship. the actual name is "+ship );		 }

	 }

	 

	 

	 public boolean isGameOver(){

		 if(game.carrier.isDestroyed==true && game.battleship.isDestroyed==true &&

			game.submarine.isDestroyed==true && game.destroyer.isDestroyed==true &&

			game.patrolBoat.isDestroyed==true){

			 return true;

		 }

		 else{

			 return false;

		 }

	 }

	 

	 

	 class Listener implements ActionListener{
 

		

		public void actionPerformed(ActionEvent e) {

			if(e.getSource() == newServerItem){

				 //String input =  JOptionPane.showInputDialog("Enter Your Name");

                 //if(input==null || input==""){

                //	 game.userName = "unnamed";

                 //}

                 //else{

                 //    game.userName = input;

                 //}

                 game.resumeGame();

                 game.battlefield.setBorder(new TitledBorder("Running In Server Mode"));

                 game.shipsPanel.setBorder(new TitledBorder("Select A Ship To Place. Right-Click To Change Direction"));

                 game.chatPanel.setBorder(new TitledBorder("Chat Disabled. Place All Ships To Enable Chat Console"));

                 game.setBorder(null);

                 setUpServer();

                 goesFirst = false; //as courtesy we let the client go first

                 //game.battlefield.enemy.disableOcean();

                 game.addSystemMessage("Waiting On Client Connection ...");

			}

			else if(e.getSource() == newClientItem){

				 //String input =  JOptionPane.showInputDialog("Enter Your Name");

                 //if(input==null || input==""){

                //	 game.userName = "unnamed";

                 //}

                 //else{

                  //   game.userName = input;

                 //}

                 game.resumeGame();

                 game.battlefield.setBorder(new TitledBorder("Running In Client Mode"));

                 game.shipsPanel.setBorder(new TitledBorder("Select A Ship To Place. Right-Click To Change Direction"));

                 game.chatPanel.setBorder(new TitledBorder("Chat Disabled. Place All Ships To Enable Chat Console"));

                 game.setBorder(null);

                 setUpClient();

				 goesFirst = true; //client always goes first

			}

			else if(e.getSource() == disconnectItem){

				disconnectClientServer(true);

			}

			else if(e.getSource() == game.message){

				sendData();

			}

			else if(e.getSource() == exitItem){

				System.exit(0);

			}

			else if(e.getSource() == settingsItem){

				System.out.println("not implemented yet");

			}

			else if(e.getSource() == soundItem){

				System.out.println("not implemented yet");

			}

			else if(e.getSource() == helpItem){

				msg.help();

			}

			else if(e.getSource() == aboutItem){

				msg.about();

			}

			else if(e.getSource() == game.sendButton){

				sendMessage(game.message.getText());

				System.out.println("message sent");//debugging

				game.addUserMessage(game.message.getText());

				game.message.setText("");

			}

			

			else{

				System.out.println("error occured");

			}

			

		}
 

	}

	 

	 class EnemyListener implements ActionListener{
 

		

		public void actionPerformed(ActionEvent e) {

			for(int x=1; x<=10; x++){

				for(int y=1; y<=10; y++){

					if(e.getSource()==game.battlefield.enemy.grid[x][y]){

						Coordinate shot = new Coordinate(x,y);

						String msg = "fired on coordinate " + shot.toString();

						game.addUserMessage(msg);

						System.out.println(shot.toString());

						

						game.battlefield.enemy.smartDisable();

						game.battlefield.enemy.disableOcean();

						game.battlefield.enemy.permanetKill(shot);

						sendShot(shot);

						

						//game.battlefield.enemy.disableOcean(); //will be enabled once we get a shot back from the enemy

					}

				}

			}

		}

	}

}

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	class ServerThread extends Thread{

		private GameBoard sc; 

		public ServerThread(GameBoard gb){

			sc = gb;

		}

		public void run(){

			ServerSocket connectionSocket = null;

			try{

				connectionSocket = new ServerSocket(30000);

			}

			catch(IOException e){

				System.err.println("Could not listen to port 30000");

				JOptionPane.showMessageDialog(sc, "Could not listen to port 30000", "Server", JOptionPane.PLAIN_MESSAGE);

				return;

			}

			JOptionPane.showMessageDialog(sc, "Server Game Activated", "Server", JOptionPane.PLAIN_MESSAGE);

			

			Socket communicationSocket = null;

			try{

				communicationSocket = connectionSocket.accept();

			}

			catch(IOException e){

				System.err.println("Accept failed");

				JOptionPane.showMessageDialog(sc, "Accept Failed", "Server", JOptionPane.PLAIN_MESSAGE);

				return;

			}

			JOptionPane.showMessageDialog(sc, "Communication is now activated", "Server", JOptionPane.PLAIN_MESSAGE);

			//sc.sendName(sc.game.userName);

			sc.game.addSystemMessage("Client is now connected");

			sc.game.addSystemMessage("Client shoots first, wait for shot");

			sc.game.battlefield.enemy.smartDisable();

			

			try{

				PrintWriter out = new PrintWriter(communicationSocket.getOutputStream(), true);

				

				BufferedReader in = new BufferedReader(new InputStreamReader(communicationSocket.getInputStream()));

				sc.setCommunicationSocket(communicationSocket);

				sc.setOutStream(out);

				sc.setInStream(in);

				connectionSocket.close();

				sc.getData();

			}

			catch(IOException e){

				System.err.println("Accept failed");

				JOptionPane.showMessageDialog(sc, "Creation I/O Stream failed", "Server", JOptionPane.PLAIN_MESSAGE);

				return;

			}

			

		}

		

	}

	

	class ClientThread extends Thread{

	 private GameBoard sc;
 

	 public ClientThread (GameBoard scParam) {

	    sc = scParam;

	   }
 

	 public void run(){

	        Socket echoSocket = null;

	        PrintWriter out = null;

	        BufferedReader in = null;

	        String ipAddress = "127.0.0.1";
 

	        try{

	            echoSocket = new Socket(ipAddress, 30000);

	            out = new PrintWriter(echoSocket.getOutputStream(), true);

	            in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));

	        } 

	        catch(UnknownHostException e){

	            System.err.println("Don't know about host: " + ipAddress);

	            JOptionPane.showMessageDialog( sc, "Don't know about host: " + ipAddress, "Client", JOptionPane.PLAIN_MESSAGE );

	            return;

	        } 

	        catch(IOException e){

	            System.err.println("Couldn't get I/O for " + "the connection to: " + ipAddress);

	            JOptionPane.showMessageDialog( sc, "Couldn't get I/O for the connection to: " + ipAddress, "Client", JOptionPane.PLAIN_MESSAGE );

	            return;

	        }

	        JOptionPane.showMessageDialog( sc, "Comminucation is now activated", "Client", JOptionPane.PLAIN_MESSAGE );

	        sc.game.addSystemMessage("Please place your first shot");

	        //sc.sendName(sc.game.userName);

	        sc.setCommunicationSocket (echoSocket);

	        sc.setOutStream (out);

	        sc.setInStream (in);
 

	        sc.getData ();
 

	    }
 

	}

Open in new window

0
 
LVL 12

Assisted Solution

by:basav_com
basav_com earned 40 total points
Comment Utility
0
 
LVL 92

Assisted Solution

by:objects
objects earned 120 total points
Comment Utility
print out the value oif ship so you can check what it is


       public void sinkEnemy(String ship){
             System.out.println(ship);
             if(ship.equals("carrier")){

0
 
LVL 1

Assisted Solution

by:hadesflames5855
hadesflames5855 earned 220 total points
Comment Utility
even though .equals() is recommended, == DOES work for strings.
0
 
LVL 1

Assisted Solution

by:hadesflames5855
hadesflames5855 earned 220 total points
Comment Utility
adding to my above statement, it only works if they point to the same place in memory, .equals() runs through it and makes sure they hold the same value.
0
 
LVL 1

Author Comment

by:ubuntuguy
Comment Utility
well I used

ship.compareTo(theOtherShip.name);

that worked...
thanks all
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now