Ok i created a board that can have two types of ships, S and M, however, I want java to show me different messages whenever the board either contains only S but no M or only M but no S or when both are present. I am not able to do that. Please do help. This is what i have tried so far
import java.util.ArrayList;
import java.util.Scanner;
public class bord {
public static void main(String[] args) {
String Board[][]= new String[4][4];
int n=0;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
Board[i][j]="-";
}
}
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
System.out.print(Board[i][j]);
}
System.out.println();
}
System.out.println("_______________");
//from here!
Board[1][1]="S";
Board[3][2]="M";
int a=0;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(Board[i][j].equalsIgnoreCase("S") && !Board[i][j].equalsIgnoreCase("M"))
{
a=1;
}
else if(Board[i][j].equalsIgnoreCase("M") && !Board[i][j].equalsIgnoreCase("S"))
{
a=2;
}
else if(Board[i][j].equalsIgnoreCase("S") || Board[i][j].equalsIgnoreCase("M") )
a=3;
}
}
if(a==0)
{
System.out.println("No ship found");
}
else if(a==1)
System.out.println("Found it");
else if(a==2)
{
System.out.println("Found it yet again");
}
else
System.out.println("keep playing again");
}
}
May be you can try this:
boolean foundS= false;
boolean foundM = false;
for (int i = 0;i < 4;i ++) {
for (int j = 0;j < 4;j ++) {
if (Board[i][j].equalsIgnoreCase("S")) {
foundS = true;
continue;
}
if (Board[i][j].equalsIgnoreCase("M")) {
foundM = true;
continue;
}
}
}
if (foundS && foundM) {
System.out.println("both");
} else if (foundS) {
System.out.println("found S");
} else if (foundM) {
System.out.println("found M");
} else {
System.out.println("none");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.