Server classes and client classes - multidimensional arrays - java

I'm having some trouble in a couple of areas here. First, when the array is printed to screen, the "P" is placed at [0][0] - which is OK, but it is surrounded by 'null' for any other cell. I'd like it to be filled with dashes " - ". I'm also needing to code in an infinite loop that asks the user to input either 'up', 'down', 'left', 'right' or 'exit'. Does this infinite loop go into the "Driver" class, or the "World" class, and would a switch statement work for this?
Second - the rows and columns are not being summed and displayed. The "World" class is:
import java.util.*;
public class World
{
private static final String P = "P";
private String[][] array;
public World()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
int crow = input.nextInt();
System.out.println("Enter number of columns: ");
int ccol = input.nextInt();
array = new String[crow][ccol];
array[0][0]=P;
}
public void displayWorld()
{
System.out.println();
for(int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
System.out.print(array[i][j] + " - ");
}
System.out.println();
}
}
public void moveUp()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i - 1][j] = P;
}
return;
}
}
}
}
public void moveDown()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i + 1][j] = P;
}
return;
}
}
}
}
public void moveLeft()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i][j - 1] = P;
}
return;
}
}
}
}
public void moveRight()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i][j + 1] = P;
}
return;
}
}
}
}
}
The "Driver" class is:
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
World world=new World();
world.moveUp();
world.moveDown();
world.moveLeft();
world.moveRight();
world.displayWorld();
}
}

You need to intialize every element in the array. Add this to the end of the World constructor:
for(int i=0;i<crow;i++){
for(int j=0;j<ccol;j++){
array[crow][ccol]="-";
}
}
You will need to add the infinite loop asking for input in the Driver class. In the infinite loop you need to:
Get input
Use switch statement to detect left, right, etc
Driver.java:
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
World world = new World();
Scanner s = new Scanner(System.in);
while (true) {
String input = s.nextLine();
switch (input) {
case "up":
world.moveUp();
case "down":
world.moveDown();
case "left":
world.moveLeft();
case "right":
world.moveRight();
}
}
s.close();
}
}

Related

Java, 2D array specified organization

I have to make 2D array [10][10] to be filled like this:
(https://i.stack.imgur.com/WCRGu.png)
Please, can someone help me with this?
`
int j, i;
int n=1;
for (j=9; j>=0;j--) {
for (i=11-j; i>=9-j; i++) {
if(i<10) {
a[i][j]=n;
n++;
}else{
break;
}
}
}
for (i=0;i<=9;i++) {
for(j=0;j<=9;j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
`
Here the program for your problem. I've also added the printing of the 2d array. It accepts any 1:1 size of the array, you can modify the size of your wanting using the variable final int ARRAY_SIZE.
public class StackOverflow {
public static void main(String[] args) {
final int ARRAY_SIZE = 10;
int[][] array = new int[ARRAY_SIZE][ARRAY_SIZE];
//filling of values for 2d array
for (int i = 0, k = 1; i < array.length ; i++) {
for (int j = i + 3; j > i; j--, k++) {
if (j > array.length) {
k--;
continue;
}
array[j - 1][array.length - i - 1] = k;
}
}
//printing of 2d array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i][j] == 0)
System.out.print(array[i][j] + " ");
else if (array[i][j] > 9)
System.out.print(array[i][j] + " ");
else
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}

180 degree rotated half pyramid(pattern question in JAVA)

I am actually trying to print this pattern: https://imgur.com/a/ObixO5I
import java.util.*;
public class ques5 {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int n = 4;
// outer loop
for (int i = 1; i <= n; i++) {
// inner loop
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("*");
}
}
}
}
}
Output I am getting is : * ** *******
Add System.out.println() at end of second inner loop.
Try this
import java.util.*;
public class ques5 {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int n = 4,m=1;
// outer loop
for (int i = n; i >=1; i--) {
// inner loop
for (int j = 1; j <= i - 1; j++) {
System.out.print(" ");
}
for (int k = 1; k <= m; k++) {
System.out.print("*");
}
System.out.print("\n");
m++;
}
}
}
}

How to write a function to read elements from 2D array?

When I run the code in the stdin line the program gives me an exception. How to solve it so the program works?
static double read_matrix(double matrix[][]) {
int i, j;
for (i = 0; i < matrix.length; i++) {
for (j = 0; j < matrix[i].length; j++) {
System.out.println("Enter elements:");
matrix[i][j]=stdin.nextInt();
}
}
return 0;
}
You are not declaring stdin inside your method.
To read from the user-input you can use for example: Scanner(System.in) that is provided by java.util.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main.read_matrix(new double[2][2]);
}
static double read_matrix(double matrix[][]) {
int i, j;
final Scanner scanner = new Scanner(System.in);
for (i = 0; i < matrix.length; i++) {
for (j = 0; j < matrix[i].length; j++) {
System.out.println("Enter element:");
matrix[i][j] = scanner.nextInt();
System.out.println("[" + i + "][" + j + "] = " + matrix[i][j]);
}
}
scanner.close(); // make sure to close it to prevent memory leaks
return 0;
}
}

How can I check if every single int in a randomly generated array is even and make it create another random array if it's not?

So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}

Creating a Christmas Tree using for loops

I am trying to make a christmas tree using for loops and nested for loops. For me to do that I need to be able to make a pyramids with *. I have tried countless times and I am having problems making one. Here is my code:
for(int i=1;i<=10;i++){
for(int j=10;j>i;j--){
System.out.println(" ");
}
for(int k=1;k<=i;k++){
System.out.print("*");
}
for(int l=10;l<=1;l++){
for(int h=1;h<=10;h++){
System.out.print(" ");
}
}
System.out.println();
}
What I am trying to do is:
*
***
*****
*******
Try this much simpler code:
public class ChristmasTree {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i; j++)
System.out.print(" ");
for (int k = 0; k < (2 * i + 1); k++)
System.out.print("*");
System.out.println();
}
}
}
It uses 3 loops:
first one for the number of rows,
second one for printing the spaces,
third one for printing the asterisks.
You can do it with simple logic
for (int i = 0; i < 4; i++)
System.out.println(" *******".substring(i, 4 + 2*i));
import java.util.Scanner;
public class cmastree{
public static void main (String[]args){
Scanner keyboard=new Scanner (System.in);
int j;
System.out.println ("Enter a number");
j=keyboard.nextInt();
/*take the above part out and change the j variable if you want to set
the size*/
for(int i=1; i<=j; i+=2){
int numSpaces = (j-i)/2;
for (int k=0; k<numSpaces; k++){
System.out.print(" ");
}
for(int k=0; k<numSpaces; k++){
System.out.print("*");
}
System.out.println();
}
}
}
public class ChrismasTree {
public static void main(String[] args) {
int sizeOfTree = 9;
double remainderVal = sizeOfTree % 2 ;
double ans = sizeOfTree / 2 ;
if (remainderVal == 0) {
System.out.println("Invalid number enter 9,19 calculat rest yourself u looser ..");
System.exit(0);
}
int middlePos = (int) Math.round(ans + .5);
for (int i = 0; i <= sizeOfTree; i++) {
int lStar = middlePos - i;
int rStar = middlePos + i;
if (lStar < 1) {
break;
}
printleaves(lStar, rStar, sizeOfTree);
}
}
public static void printleaves(int a,int b, int size){
System.out.println();
for (int i = 1; i <= size; i++) {
if (i > a && i < b ){
System.out.print("*");
}else System.out.print(" ");
}
}
}
public class Stars {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter Row/Column Value::");
int i,j,k,n;
n=s.nextInt();
for(i=1; i<n; i++){
for(j=n+(n/2); j>i; j--){
System.out.print(" ");}
for(k=1; k<=2*i-1; k++){
System.out.print("*");}
System.out.println("");
}
for(i=1; i<n+(n/2); i++){
for(j=n+(n/2); j>i; j--){
System.out.print(" ");}
for(k=1; k<=2*i-1; k++){
System.out.print("*");}
System.out.println("");
}
for(i=1; i<n-(n/2); i++){
for(j=n+(n/2); j>1; j--){
System.out.print(" ");}
for(k=n/2; k<=(n/2)+1; k++){
System.out.print("*");}
System.out.println("");
}
}
}
public class ChristmasTree {
public static void printStars(int number) {
for (int i = 1; i <= number; i++) {
System.out.print("*");
}
System.out.println("");
}
public static void printSpaces(int number) {
for (int i = 0; i < number; i++) {
System.out.print(" ");
}
}
public static void christmasTree(int height) {
for (int i = 1; i <= height; i++) {
printSpaces(height - i);
printStars(i + (i - 1));
}
}
public static void main(String[] args) {
// int x = pick some number, but not TOO big )))
christmasTree(x);
}
}
def fist(n)
k=2*n-2
for i in range(0,n):
for j in range(0,k):
k=k-1
print(end=" ')
for j in range(0,i+1):
print("*",end=" ")
print()
def second(n)
k=2*n-2
for i in range(0,n):
for j in range(0,k):
k=k-1
print(end=" ')
for j in range(0,i+1):
print("*",end=" ")
print()
def stem(m)
k=11
for i in range(0,5):
for j in range(0,k):
print(end=" ")
for j in range(0,3):
print("*",end=" ")
print()
first(7)
second(7)
steam(3)

Categories