This project was to make a 2d battleship project using arrays. If you hit, it makes an "X." If it's one slot away up, down, right, or left, it is "H" for hot. If it's two slots away, it's "W" for warm. "C" for cool for three slots, and miss for everything else.
Every time I go to test out my code, it works for the first time perfectly fine, but afterwards it marks every input as a hit, when it should mark it as "H", "W", "C", or "M."
import java.util.Scanner;
public class Battleship
{
public static void main ()
{
int rowLoc = 0;
int colLoc = 0;
int rowGuess;
int colGuess;
int guesses = 1;
int shipNum = 5;
//variable declaration
String[][] battleGrid = new String[10][10];
String[][] battleGridKnown = new String[10][10];
//grid declaration
System.out.println("Welcome to Battleship!\nFive ships are hidden in row 0-9 and columns 0-9.");
System.out.println("After each guess, you will been told if your guess was...");
System.out.println("- Hit (X)\n- Close (H for hot)\n- Somewhat close (W for warm)\n- Not that close (C for cool)\n- Miss (M).");
//welcome message
for (int r = 0; r < battleGrid.length; r++)
{
for (int c = 0; c < battleGrid[r].length; c++)
{
battleGrid[r][c] = "-";
}
}
//initializes what is in battleGrid by default
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
battleGridKnown[r][c] = "-";
}
}
//initializes what is in battleGridKnown by default
for (int k = 1; k <= shipNum; k++)
{
do
{
rowLoc = (int)(Math.random() * 10 + 0);
colLoc = (int)(Math.random() * 10 + 0);
} while(battleGrid[rowLoc][colLoc] == "S");
battleGrid[rowLoc][colLoc] = "S";
}
//sets ships and also the stuff around the ships
/*for (int r = 0; r < battleGrid.length; r++)
{
for (int c = 0; c < battleGrid[r].length; c++)
{
System.out.print(battleGrid[r][c] + "");
}
System.out.println("");
}
System.out.println("");
//test printer*/
while(shipNum > 0)
{
System.out.print("Enter your row guess (0-9): ");
Scanner in = new Scanner (System.in);
rowGuess = in.nextInt();
System.out.print("Enter your column guess (0-9): ");
colGuess = in.nextInt();
// enter row + column guesses
if (battleGrid[rowGuess][colGuess] == battleGrid[rowLoc][colLoc])
{
shipNum--;
battleGridKnown[rowGuess][colGuess] = "X";
System.out.println("Hit! There are " + shipNum + " ships remaining.");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc-- || rowGuess == rowLoc++ || colGuess == colLoc-- || colGuess == colLoc++)
{
battleGridKnown[rowGuess][colGuess] = "H";
System.out.println("Hot!");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc - 2 || rowGuess == rowLoc + 2 || colGuess == colLoc - 2 || colGuess == colLoc + 2)
{
System.out.println("Warm...");
battleGridKnown[rowGuess][colGuess] = "W";
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc - 3 || rowGuess == rowLoc + 3 || colGuess == colLoc - 3 || colGuess == colLoc + 3)
{
System.out.println("Cool...");
battleGridKnown[rowGuess][colGuess] = "C";
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else
{
System.out.println("Miss.");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
battleGridKnown[rowGuess][colGuess] = "M";
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
guesses++;
}
System.out.println("Thank you for playing!\nYou found all the ships in " + guesses + " guesses.");
}
}
Related
I am trying to make a tic tac toe game and am new to java. I am getting outofbounds at the first if statement within the method isHorizontalWin and I am assuming it would happen within isVerticalWin as well. Correct me if I am wrong but I believe it is happening because part of gameboard has no value so the if statement is outofbounds however I am unsure in how to fix this. A side note: the formatting got messed up a little bit when pasting the code so I had to make some of the JOptionPanes go onto multiple lines to fit. Thanks!
import javax.swing.JOptionPane;
public class TicTacToe
{
public static void main(String[] args)
{
char gameboard[][] = new char[3][3];
printCurrentState(gameboard);
int Turn = 0;
int gameon=0;
while(gameon<9)
{
if(Turn==0)
{
JOptionPane.showMessageDialog(null, "Player 1's turn aka X");
}
else
{
JOptionPane.showMessageDialog(null, "Player 2's turn aka O");
}
boolean proceed=true;
String yo =JOptionPane.showInputDialog("Enter the row and column"+ "one"+
"after another. Example-for row 1 and comlumn 2 type \"12\"");
if(yo.length()!=2)
{
JOptionPane.showMessageDialog(null, "You did not put the row"+ "and column one after another- Try again");
proceed=false;
}
if(proceed==true) {
String aa= yo.charAt(0)+"";
int x = Integer.parseInt(aa)-1;
String ba= yo.charAt(1)+"";
int y = Integer.parseInt(ba)-1;
if((x < 0 || x > 2)||(y<0||y>2))
{
JOptionPane.showMessageDialog(null, "Please enter a row and"+
"column that both at least 1 and no bigger than 3. Try again!");
yo =JOptionPane.showInputDialog("Enter the row and column one"+
"after another. Example-for row 1 and comlumn 2 type \"12\"");
aa= yo.charAt(0)+"";
x = Integer.parseInt(aa)-1;
ba= yo.charAt(1)+"";
y = Integer.parseInt(ba)-1;
}
if(gameboard[x][y] == 'X' || gameboard[x][y] == 'O')
{
JOptionPane.showMessageDialog(null, "That is already taken"+
"by an "+ gameboard[x][y]+". Go again!");
yo =JOptionPane.showInputDialog("Enter the row and column"+
"one after another. Example-for row 1 and comlumn 2 type \"12\"");
aa= yo.charAt(0)+"";
x = Integer.parseInt(aa)-1;
ba= yo.charAt(1)+"";
y = Integer.parseInt(ba)-1;
}
if(Turn== 0)
{
gameboard[x][y] = 'X';
printCurrentState(gameboard);
isHorizontalWin(gameboard);
isVerticalWin(gameboard);
isDiagnolWin(gameboard);
Turn++;
}
else if(Turn == 1)
{
gameboard[x][y] = 'O';
printCurrentState(gameboard);
isHorizontalWin(gameboard);
isVerticalWin(gameboard);
isDiagnolWin(gameboard);
Turn--;
}
gameon++;
}
}
if(isHorizontalWin(gameboard)==false&&isVerticalWin(gameboard)==false&&isDiagnolWin(gameboard)==false)
{
JOptionPane.showMessageDialog(null, "There was no winner this game ");
}
}
public static void printCurrentState(char gameboard[][])
{
System.out.println(" COLUMN");
System.out.println(" 1 2 3");
System.out.print(gameboard[0][0] + " | " + gameboard[0][1] + " | " + gameboard[0][2] +" 1 R"+ "\n"
+ "--|---|--\n" +
gameboard[1][0] + " | " + gameboard[1][1] + " | " + gameboard[1][2] +" 2 O"+ "\n"
+ "--|---|--\n" +
gameboard[2][0] + " | " + gameboard[2][1] + " | " + gameboard[2][2] +" 3 W "+"\n");
System.out.println();
}
public static boolean isHorizontalWin(char[][] gameboard)
{
int tally[][]= new int[3][3];
for(int r = 0; r < 3; r++)
{
for(int c = 0; c < 3; r++)
{
if(gameboard[r][c]=='O')
{
tally[r][c]=10;
}
else if(gameboard[r][c]=='X')
{
tally[r][c]=1;
}
else
{
tally[r][c]=0;
}
}
}
int c=0;
for(int m = 0; m < 3; m++)
{
c++;
int cool = 0;
for(int n = 0; n < 3; n++)
{
cool += tally[m][n];
if(cool == 30)
{
JOptionPane.showMessageDialog(null, "Player 2(O) is the winner with a horizontal win in row " +c);
System.exit(0);
return true;
}
else if(cool==3)
{
JOptionPane.showMessageDialog(null, "Player 1(X) is the winner with a horizontal win in row " + c);
System.exit(0);
return true;
}
}
}
return false;
}
public static boolean isVerticalWin(char[][] gameboard)
{
int tally[][]= new int[3][3];
for(int r = 0; r < 3; r++)
{
for(int c = 0; c < 3; r++)
{
if(gameboard[r][c]=='O')
{
tally[r][c]=10;
}
else if(gameboard[r][c]=='X')
{
tally[r][c]=1;
}
else
{
tally[r][c]=0;
}
}
}
int r=0;
for(int m = 0; m < 3; m++)
{
r++;
int cool = 0;
for(int n = 0; n < 3; n++)
{
cool += tally[n][m];
if(cool == 30)
{
JOptionPane.showMessageDialog(null, "Player 2(O) is the winner with a vertical win in column " +r);
System.exit(0);
return true;
}
else if(cool==3)
{
JOptionPane.showMessageDialog(null, "Player 1(X) is the winner with a vertical win in column " + r);
System.exit(0);
return true;
}
}
}
return false;
}
public static boolean isDiagnolWin(char[][] gameboard)
{
if((gameboard[0][0]=='O'&&gameboard[1][1]=='O'&&gameboard[2][2]=='O')||(gameboard[0][2]=='O'&&gameboard[1][1]=='O'&&gameboard[3][1]=='O'))
{
JOptionPane.showMessageDialog(null, "Player 2(O) is the winner with a diagonal win" );
System.exit(0);
return true;
}
if((gameboard[0][0]=='X'&&gameboard[1][1]=='X'&&gameboard[2][2]=='X')||(gameboard[0][2]=='X'&&gameboard[1][1]=='X'&&gameboard[2][0]=='X'))
{
JOptionPane.showMessageDialog(null, "Player 1(X) is the winner with a diagonal win" );
System.exit(0);
return true;
}
return false;
}
}
In isHorizontalWin, you probably forgot to change the r++ into c++ in the second for loop.
This results into r being incremented too many times.
So when r reaches a number that is higher than the amount of entries, the index (r) is out of bounds.
for(int r = 0; r < 3; r++)
{
for(int c = 0; c < 3; r++)
{
Needs to be:
for(int r = 0; r < 3; r++)
{
for(int c = 0; c < 3; c++)
{
Made some edits to the code to try and figure out why my X's [-1] are not being included in finding my average for that row. That is throwing of my averages. Any idea why It is not counting my -1's?
output[expected]:
USER INPUT: 3
O O O
X X X
X X X
TOTAL OPENNESS OF [I][J] = 1
TOTAL OPENNESS OF [I][J+1] = 2
TOTAL OPENNESS OF [I][J+2] = 1
TOTAL SUM AVERAGE FOR THAT ROW = 1.3
HOWEVER..FOR ROW 2 AND ROW 3
TOTAL SUM AVERAGE FOR THOSE ROWS = 0
WHICH IS INCORRECT IT SHOULD = -1
public static void openfactor(char[][] mazeValue, int n){
for(int i = 1; i<=n; i++)
{
double rowAvg=0;
double totalRowAvg=0;
for(int j=1;j<=n;j++)
{
int count=0;
int totalOpeness=0;
int totalRowOpeness = 0;
//double rowAvg=0;
if(mazeValue[i][j]=='X'){
System.out.println("tHIS IS AN X FOR : [" + i + "]" +"[" + j + "] IS -1 ");
count = -1;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=1)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1 && j-1>=1)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n && i+1<=n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<=n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=1 && i+1<=n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=1 && j+1<=n)
{
if(mazeValue[i-1][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " +totalOpeness);
totalRowOpeness = totalRowOpeness + totalOpeness;
//}//eND OF iF CONDITION\
}
rowAvg = (double)totalRowOpeness/(double)n;
System.out.println("ROW AVERAGE: "+rowAvg);
totalRowAvg = totalRowAvg + rowAvg;
System.out.println("SUM ROW AVERAGE: "+totalRowAvg);
}
System.out.println("TOTAL SUM ROW AVERAGE: " +totalRowAvg);
}
}
public static void printMaze(char mazeValue[][]) {
System.out.println("MAZE");
for (int i = 1; i < mazeValue.length; i++) {
for (int j = 1; j < mazeValue[i].length; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n + 1][n + 1];
System.out.println("ENTER A PATH: ");
for (int i = 0; i < mazeValue.length; i++) {
for (int j = 0; j < mazeValue[i].length; j++) {
if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
mazeValue[i][j] = 'X';
else {
mazeValue[i][j] = kbd.next().charAt(0);
}
}
}
printMaze(mazeValue);
horizontalPath(mazeValue, n);
System.out.println(" ");
verticalPath(mazeValue,n);
System.out.println(" ");
openfactor(mazeValue, n);
}
}
I do not completely understand what u want to accomplished but I am going to to assume you want to find repeated values, do this using some search algorithm below is an example of a binary search. Hope it helps.
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
Here's the complete code for your request. you need to reorder your if statements a little bit your logic was right:
and here is the output :
MAZE
O O X
O O O
X X O
TOTAL OPENESS FOR : [0][0] IS 3
TOTAL OPENESS FOR : [0][1] IS 4
THERE IS AN X HERE FOR : [0][2]
Average of O's in this row is : 66.66667%
TOTAL OPENESS FOR : [1][0] IS 3
TOTAL OPENESS FOR : [1][1] IS 5
TOTAL OPENESS FOR : [1][2] IS 3
Average of O's in this row is : 100.0%
THERE IS AN X HERE FOR : [2][0]
THERE IS AN X HERE FOR : [2][1]
TOTAL OPENESS FOR : [2][2] IS 2
Average of O's in this row is : 33.333336%
here's the code:
import java.util.Scanner;
public class sof {
public static boolean IsOutOfBound(int i, int j, int n)
{
if (i-1<1 || j-1<1 || i+1>n || j+1>n)
return true;
else
return false;
}
public static void openfactor(char[][] mazeValue, int n)
{
for(int i = 0; i<n; i++)
{
int TotalCounts=0;
for(int j=0;j<n;j++)
{
int count=0;
if(mazeValue[i][j]=='X'){
System.out.println("THERE IS AN X HERE FOR : [" + i + "]" +"[" + j + "] ");
//TotalCounts--;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=0)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0 && j-1>=0)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n && i+1<n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=0 && i+1<n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=0 && j+1<n)
{
if(mazeValue[j+1][i-1]=='O')
count++;
}
// System.out.println("cout: "+count);
//totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " + count);
TotalCounts++;
}//END OF else CONDITION
}//End of J loop
float Average = ((float)TotalCounts/(float)n) * 100;
System.out.println("Average of O's in this row is : " + Average+ "%");
}//End of I loop
}
public static void printMaze(char mazeValue[][],int n) {
System.out.println("MAZE");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for (int i = 0; i <n; i++) {
for (int j = 0; j < n; j++) {
//if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
// mazeValue[i][j] = 'X';
// else {
mazeValue[i][j] = kbd.next().charAt(0);
// }
}
}
printMaze(mazeValue,n);
openfactor(mazeValue, n);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is a program for calculate the area of triangle that create by six points
and point out what types of triangle.
import java.util.Scanner;
public class assignment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int m = 0,n = 0;
int[][] x = new int[6][2];
double a,b,c,a1,b1,c1;
String y = "";
System.out.println("Please enter six points,");
for(int i = 0 ; i < x.length ; i++ ){
for(int j = 0 ; j < x[i].length ; j++)
x[i][j] = input.nextInt();
}
for(int i = 0 ; i < 30 ; i++)
System.out.print("--");
System.out.print("\n\t\t\t\tTypes of Triangles\n");
for(int i = 0 ; i < 30 ; i++)
System.out.print("--");
System.out.println();
System.out.println("Point1\t\tPoint2\t\tPoint3\t\tType of Triangle");
for(int i = 0 ; i < 30 ; i++)
System.out.print("--");
System.out.println();
for(int j = 0 ; j < 4 ; j++){
for(int k = j + 1 ; k < 5 ; k++ ){
for(int l = k + 1 ;l < 6 ; l++ ){
a = Math.sqrt(Math.pow((x[j][0]-x[k][0]),2)+Math.pow((x[j][1]-x[k][1]),2));
b = Math.sqrt(Math.pow((x[j][0]-x[l][0]),2)+Math.pow((x[j][1]-x[l][1]),2));
c = Math.sqrt(Math.pow((x[l][0]-x[k][0]),2)+Math.pow((x[l][1]-x[k][1]),2));
c1=Math.max(Math.max(a,b),c);
b1=Math.min(Math.min(a,b),c);
a1=(a+b+c)-c1-b1;
if ( a1 > 0 && b1 > 0 && c1 > 0 && a1 + b1 > c1 && b1 + c1 > a1 && c1 + a1 > b1 ){
if(Math.pow(c1,2) == (Math.pow(b1,2) + Math.pow(a1,2))){
if(a1==b1 || b1==c1 || c1==a1){
y = ("Right-angled\tIsosceles");
}
else if(a1!=b1 && b1!=c1 && c1!=a1){
y = ("Right-angled\tScalene");
}
}
else if(a1==b1 || b1==c1 || c1==a1){
y = ("Isosceles");
}
else if(a1!=b1 && b1!=c1 && c1!=a1){
y=("Scalene");
}
}
else{
y = ("Non-triangle");
}
System.out.println("(" + x[j][0] + "," + x[j][1]+ ")\t\t" + "(" + x[k][0] + "," + x[k][1] + ")\t\t" + "(" + x [l][0] + "," + x[l][1]+")\t\t" + y );
}
}
}
System.out.print("Maximum area of triangle =" + Math.max(area()));
System.out.print("Maximum area of triangle =" + Math.min(area()));
}
public static double area(double[][] n){
double s = 0;
int i;
for(int j = 0 ; j < 4 ; j++){
for(int k = j + 1 ; k < 5 ; k++ ){
for(int l = k + 1 ;l < 6 ; l++ ){
a = Math.sqrt(Math.pow((x[j][0]-x[k][0]),2)+Math.pow((x[j][1]-x[k][1]),2));
b = Math.sqrt(Math.pow((x[j][0]-x[l][0]),2)+Math.pow((x[j][1]-x[l][1]),2));
c = Math.sqrt(Math.pow((x[l][0]-x[k][0]),2)+Math.pow((x[l][1]-x[k][1]),2));
s = (a+b+c)/2;
n[i][0] = Math.sqrt(s * (s-a) * (s-b) * (s-c));
i++;
}
}
}
return n[][];
}
}
I have got a error: '.class' expected,
I am a beginner ,can someone help me please?
thx a lot
There are quite a few problems with the code you posted. Things like assigning to undefined variables such as the following in the area method:
a = Math.sqrt(Math.pow((x[j][0]-x[k][0]),2)+Math.pow((x[j][1]-x[k][1]),2));
You're also referencing the variable x in that statement which is not the correct variable name. The return type and value returned don't match, and there's a syntax problem in the return.
A lot of these problems will be pointed out using an IDE like Eclipse. I think you would do yourself a favor to learn coding in Eclipse.
Here is a revision of your code that runs. I'm not sure about correctness of what you're trying to do:
public class assignment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int m = 0, n = 0;
int[][] x = new int[6][2];
double a, b, c, a1, b1, c1;
String y = "";
System.out.println("Please enter six points,");
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++)
x[i][j] = input.nextInt();
}
for (int i = 0; i < 30; i++)
System.out.print("--");
System.out.print("\n\t\t\t\tTypes of Triangles\n");
for (int i = 0; i < 30; i++)
System.out.print("--");
System.out.println();
System.out.println("Point1\t\tPoint2\t\tPoint3\t\tType of Triangle");
for (int i = 0; i < 30; i++)
System.out.print("--");
System.out.println();
for (int j = 0; j < 4; j++) {
for (int k = j + 1; k < 5; k++) {
for (int l = k + 1; l < 6; l++) {
a = Math.sqrt(Math.pow((x[j][0] - x[k][0]), 2) + Math.pow((x[j][1] - x[k][1]), 2));
b = Math.sqrt(Math.pow((x[j][0] - x[l][0]), 2) + Math.pow((x[j][1] - x[l][1]), 2));
c = Math.sqrt(Math.pow((x[l][0] - x[k][0]), 2) + Math.pow((x[l][1] - x[k][1]), 2));
c1 = Math.max(Math.max(a, b), c);
b1 = Math.min(Math.min(a, b), c);
a1 = (a + b + c) - c1 - b1;
if (a1 > 0 && b1 > 0 && c1 > 0 && a1 + b1 > c1 && b1 + c1 > a1 && c1 + a1 > b1) {
if (Math.pow(c1, 2) == (Math.pow(b1, 2) + Math.pow(a1, 2))) {
if (a1 == b1 || b1 == c1 || c1 == a1) {
y = ("Right-angled\tIsosceles");
} else if (a1 != b1 && b1 != c1 && c1 != a1) {
y = ("Right-angled\tScalene");
}
} else if (a1 == b1 || b1 == c1 || c1 == a1) {
y = ("Isosceles");
} else if (a1 != b1 && b1 != c1 && c1 != a1) {
y = ("Scalene");
}
} else {
y = ("Non-triangle");
}
System.out.println("(" + x[j][0] + "," + x[j][1] + ")\t\t" + "(" + x[k][0] + "," + x[k][1] + ")\t\t" + "(" + x[l][0] + "," + x[l][1] + ")\t\t" + y);
}
}
}
System.out.print("Maximum area of triangle =" + area(x));
//System.out.print("Maximum area of triangle =" + Math.min(area(x)));
}
public static double area(int[][] n) {
double s = 0;
double max = 0;
for (int j = 0; j < 4; j++) {
for (int k = j + 1; k < 5; k++) {
for (int l = k + 1; l < 6; l++) {
double a = Math.sqrt(Math.pow((n[j][0] - n[k][0]), 2) + Math.pow((n[j][1] - n[k][1]), 2));
double b = Math.sqrt(Math.pow((n[j][0] - n[l][0]), 2) + Math.pow((n[j][1] - n[l][1]), 2));
double c = Math.sqrt(Math.pow((n[l][0] - n[k][0]), 2) + Math.pow((n[l][1] - n[k][1]), 2));
s = (a + b + c) / 2;
if (s > max) {
max = s;
}
}
}
}
return max;
}
}
What I need is a little modification to my code so that every part of my hollow diamond prints a letter of the word "HURRICANE"
My code is:
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
The output comes out as:
H
H H
H H
H H
H H
H H
H H
H H
H
I need to modify my "charAt" statement a little so it comes out to be:
H
U U
R R
R R
I I
C C
A A
N N
E
How should I make my print statement?
It's worth noting that the example provided only works for Strings the same length as "HURRICANE". A superior solution would work for all strings.
Partial solution for you to complete, since I guess it's your coursework and I don't want you to copy / paste / fail exams :P
public static void main(String[] args) {
String st1 = "HURRICANE";
char[] st1CharArray = st1.toCharArray();
int maxSpaces = st1CharArray.length / 2 + 1;
for (int i = 0; i <= st1CharArray.length / 2; i++) {
if (i == 0) {
System.out.println(getSpacesString(maxSpaces) + st1CharArray[i]);
} else {
System.out.println(getSpacesString(maxSpaces - i)
+ st1CharArray[i] + getSpacesString(i * 2 - 1)
+ st1CharArray[i]);
}
}
// Loop from st1CharArray.length / 2 + 1 and get the second half done.
}
private static String getSpacesString(int numberOfSpaces) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < numberOfSpaces; i++) {
strBuilder.append(" ");
}
return strBuilder.toString();
}
//: Playground - noun: a place where people can play
import UIKit
var name : String = "HURRICANE"
var dimensions : Int = name.count - 1
var k : Int = 0
for rows in 0...dimensions{
for columns in 0...dimensions{
k = abs( (dimensions/2) - rows )
if columns == k || columns == dimensions - k{
print(Array(name)[rows], terminator: "")
}
else{
print(" ", terminator: "" )
}
}
print("")
}
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(5 - i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(3 + i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
Let's assume that a word has an odd number of characters, otherwise we get a crooked diamond.
Try it online!
public static void main(String[] args) {
String str = "abrahadabra";
int n = str.length() / 2;
for (int i = -n, ch = 0; i <= n && ch < str.length(); i++, ch++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print(str.charAt(ch));
else
System.out.print(" ");
System.out.println();
}
}
Output:
a
b b
r r
a a
h h
a a
d d
a a
b b
r r
a
I want to loop through an array and print any values that are not null, here is the code I am trying to use:
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
}
}
Array:
static String[] studentNamesArray = new String[10];
The problem is that it is only printing out index[0]. How can I fix this?
EDIT:
Here is my full code:
static void deleteStudent() {
boolean studentFound = false;
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
for (i = 0; i < 10; i++) {
for (i = studentChoice + 1; i < studentNamesArray.length; i++) {
studentNamesArray[i - 1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount - 1;
studentNamesArray[studentNamesArray.length - 1] = null;
for (i = studentChoice + 1; i < 9; i++) {
for (int y = 0; y < 3; y++) {
studentMarksArray[i - 1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for (int y = 0; y < 3; y++) {
studentMarksArray[9][y] = 0;
}
}
}
if (!studentFound) {
System.out.println("There are no students stored");
}
}
Use the for-loop only to print the students names. And read the studentChoice once after you printed all the students. Otherwise it waits for input after printing the studentNamesArray[0]
System.out.println("Which student would you like to delete?");
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println(i + ": " + studentNamesArray[i]);
}
}
int studentChoice = input.nextInt();
Make sure that the contents of the array are not null, or they wont print out
Only reason I can see here, other elements should be null. You can make sure it as follows
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();// you need to check this
}else{
System.out.println(i + ": " + studentNamesArray[i]);
}
}
But may be there is another reason. If input.nextInt() is take from Scanner, your program will wait there for a user input. Then you have to provide that input to continue. Make sure those things.