Solved

What's wrong with this simple code?

Posted on 2009-04-07
11
247 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
ID: 24092849
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
ID: 24092851
>                  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
ID: 24092856
Sorry that's wrong, you're ship isn't an object. Ignore me it's late.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 3

Assisted Solution

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

Accepted Solution

by:
hadesflames5855 earned 220 total points
ID: 24092876
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
 
LVL 1

Author Comment

by:ubuntuguy
ID: 24092888
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
ID: 24092899
0
 
LVL 92

Assisted Solution

by:objects
objects earned 120 total points
ID: 24092902
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
ID: 24092945
even though .equals() is recommended, == DOES work for strings.
0
 
LVL 1

Assisted Solution

by:hadesflames5855
hadesflames5855 earned 220 total points
ID: 24092951
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
ID: 24092963
well I used

ship.compareTo(theOtherShip.name);

that worked...
thanks all
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JavaScript/Java - Changing an image background color 4 75
print map entry 34 71
iterator/ListIterator approach 17 39
American Express @Work site and Java 4 9
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

789 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