How to store Scanner data in string in java?
I am new to java, currently I am working on a program regarding networking.
My program compiles without error.
I have placed 3 checks in my program. It passes through check 1 but does not reach 2.
I want string player2msg to store whatever data comes from scanner fromServer.
I expected player2Msg = fromServer.nextLine(); to work but it does not.
import java.net.*;
import java.util.*;
import java.io.*;
public class newClient {
static Scanner shipPlace = new Scanner(System.in);
static Scanner shipAlignment = new Scanner(System.in);
public static void main(String[] args) throws Exception{
Socket servConn = new Socket("localhost", 10176);
Scanner fromServer = new Scanner(servConn.getInputStream());
Scanner fromUser = new Scanner(System.in); // command line input.
PrintWriter toServer = new PrintWriter(servConn.getOutputStream(), true);
BattleBoard player2 = new BattleBoard();
int hit;
boolean gameOver;
String player1msg;
int x_cor_target;
int y_cor_target;
String gameEnd = "All of your ships destroyed.";
String reHit = "Already shot at target. Please specify another target";
int player2Moves = 0;
int newCounter = 0;
boolean myMessage = false;
boolean gameStart = false;
String player2Msg;
System.out.println("A connection has been made. Please wait while other player plant ships. \n");
System.out.println("Plant your own ships");
for (int I = 0; I<5; I++) {
newCounter = plantNavy(player2,I);
newCounter++;
}
System.out.println("Please wait while other player plant ships");
player1msg = "Player2: I have planted my ships";
fromUser = new Scanner(player1msg);
while(true) {
try {
if (fromServer.hasNext()) {
System.out.println("Server Says: " + fromServer.nextLine());
System.out.println("check1111");
player2Msg = fromServer.nextLine();
System.out.println("check2222");
System.out.println(player2Msg);
if (player2Msg.equals("Player1: I have planted my ships")) {
System.out.println("check3333");
gameStart = true;
}
}
} catch(Exception e) {
e.printStackTrace();
}
if (myMessage == true && gameStart == true) {
fromUser = new Scanner(System.in);
}
if (fromUser.hasNext()) {
toServer.println(fromUser.nextLine());
}
}
}
}