java matrix 0's and 1's - java

Hey guys so this is my homework question: Write a method that displays an n by n matrix in a dialog box using the following header:
public static void printMatrix(int n)
Each element in the matrix is 0 or 1, which is generated randomly.
A 3 by 3 matrix may look like this:
0 1 0
0 0 0
1 1 1
So far, I could easily print out my problem in a scanner, however I'm not sure how to do it in a dialog box.
At the moment I'm getting the error:
error: 'void' type not allowed here JOptionPane.showMessageDialog(null, printMatrix(n));
1 error
I know that it's a void, and can't be returned however, my assignment requires the method to be void. My real question is how would I print it in the method then? I've been working on this problem for 4 hours and it's really frustrating me.
import java.util.*;
import java.lang.*;
import java.io.*;
import javax.swing.JOptionPane;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
// Main method
public static void main(String[] args)
{
// Prompt user to enter numbers
String stringInteger = JOptionPane.showInputDialog(null, "Enter a integer n to determine the size of matrix: ", "Size of Matrix Input", JOptionPane.INFORMATION_MESSAGE);
// Convert string to integer
int n = Integer.parseInt(stringInteger);
JOptionPane.showMessageDialog(null, printMatrix(n));
}
// Generate and display random 0's and 1's accordingly
public static void printMatrix(int n)
{
// Row depending on n times
for (int row = 0; row < n; row++)
{
// Column depending on n times
for (int col = 0; col < n; col++)
{
String randomN = ((int)(Math.random() * 2)+ " ");
}
}
}
}

I think you are being asked to print. Also, I would prefer Random.nextBoolean() for generating the character. Loop and call System.out.print. Something like,
public static void printMatrix(int n) {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(rand.nextBoolean() ? "1 " : "0 ");
}
System.out.println();
}
}
public static void main(String[] args) {
printMatrix(3);
}
If you really want to use a JOptionPane you might use a StringBuilder to construct the matrix and then display it. Something like,
public static void printMatrix(int n) {
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sb.append(rand.nextBoolean() ? "1 " : "0 ");
}
sb.append(System.lineSeparator());
}
JOptionPane.showMessageDialog(null, sb.toString());
}
But a void method doesn't return anything, so you can't print the result of a void method in the caller.

A slight modification done to your method I am providing screenshot of output.
private static Object printMatrix(int n) {
// Column depending on n times
String randomN[][] = new String[n][n];
for(int row = 0 ;row<n;row++)
{
for (int col = 0; col < n; col++)
{
randomN[row][col] = ((int)(Math.random() * 2)+ " ");
}
}
String s = Arrays.deepToString(randomN).replace("], ", "\n").replaceAll(",|\\[|\\]", "");
return s;
}
Hope you found my code helpful cheers happy coding.

This code will do everything inside your printMatrix();
class DialogPrint
{
public static void main(String[] args)
{
// Prompt user to enter numbers
String stringInteger = JOptionPane.showInputDialog(null, "Enter a integer n to determine the size of matrix: ", "Size of Matrix Input", JOptionPane.INFORMATION_MESSAGE);
// Convert string to integer
int n = Integer.parseInt(stringInteger);
printMatrix(n);
}
// Generate and display random 0's and 1's accordingly
public static void printMatrix(int n)
{
// Row depending on n times
String sb="";
for (int row = 0; row < n; row++)
{
// Column depending on n times
for (int col = 0; col < n; col++)
{
String randomN = ((int)(Math.random() * 2)+ " ");
sb+=randomN;
}
sb+="\n";
}
System.out.print(sb);
JOptionPane.showMessageDialog(null, sb);
}
}

Related

Creating a box in Java from user inputs, but how do I replace the interior of the box with a different input than its borders?

I need to create a box using user inputs. My inputs are the dimensions (height x width), the "interior" (the character that the box is filled with), and the "border" (the character surrounding the interior). I'm almost done, I believe; I can assemble the box given the dimensions and border, but I'm struggling to figure out how to fill the inside.
I don't know how to use decision statements to determine which characters belong on which line. If the current line is the first line, I want to print only border characters, or if the current character on the line is the first character in that line, print a border character, but print the interior for the following characters (until the end char), etc.
My code:
// Below this comment: import the Scanner
import java.util.Scanner;
public class Box {
public static void main(String[] args) {
// Below this comment: declare and instantiate a Scanner
Scanner scnr = new Scanner(System.in);
// Below this comment: declare any other variables you may need
int width;
int height;
char border;
char interior;
// Below this comment: collect the required inputs
System.out.println("Enter width : ");
width = scnr.nextInt();
System.out.println("Enter height : ");
height = scnr.nextInt();
System.out.println("Enter border : ");
border = scnr.next().charAt(0);
System.out.print("Enter interior : ");
interior = scnr.next().charAt(0);
// Below this comment: display the required results
for (int j = 0; j < height; j++) {
for (int i = 1; i < width; i++) {
System.out.print(border);
}
System.out.print(border);
System.out.println("");
}
}
}
As an arbitrary example, running my code with 7x5 dimensions and X and O characters gives me:
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
But my desired result would be:
XXXXXXX
XOOOOOX
XOOOOOX
XOOOOOX
XXXXXXX
Change:
for (int j = 0; j < height; j++) {
for (int i = 1; i < width; i++) {
System.out.print(border);
}
System.out.print(border);
System.out.println("");
}
To:
for (int j = 0; j < height; j++) {
for (int i = 1; i <= width; i++) {
if (j==0 || j==(height-1)) {
System.out.print(border);
}
else {
if (i==1 || i==width) {
System.out.print(border);
}
else {
System.out.print(interior);
}
}
}
System.out.println();
}
This could obviously be written in many different ways, some much more compact than this. I think this way is easy to understand, though...
For instance, here's a shorter version that works, but is harder to interpret:
for (int j = 0; j < height; j++) {
for (int i = 1; i <= width; i++) {
System.out.print(((j==0 || j==(height-1)) || (i==1 || i==width)) ? border : interior);
}
System.out.println();
}
You can certainly use if-else control structures to do this, but a simpler option would be to create the inner box with 2 rows and 2 columns fewer than the given dimensions, and then append the borders. You didn’t say what the expectation is for boxes of 1 or 2 rows only, so, you’ll have to handle those cases as well.
Also, for testability purposes, I’d create a method that accepts the dimensions as integers, and returns the box. You can then print the box in the main method. You can even take it one step further and create one method to create the inner box, and another to pad it with borders. Basically, try not to shove your entire project into one main method.
Implementation 1:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
if (args.length < 2) {
throw new IllegalArgumentException("Usage: java MyClass <rows> <cols>");
}
int rows = Integer.parseInt(args[0]);
int cols = Integer.parseInt(args[1]);
List<String> inner = createBox(rows - 2, cols - 2);
List<String> box = new ArrayList<>();
box.add("X".repeat(cols));
for (String row : inner) {
box.add("X" + row + "X");
}
if (rows > 1) {
box.add(box.get(0));
}
for (String row : box) {
System.out.println(row);
}
}
private static List<String> createBox(int rows, int cols) {
if (rows <= 0 || cols <= 0) {
return Collections.emptyList();
}
String row = "O".repeat(cols);
return Collections.nCopies(rows, row);
}
}
Implementation 2, slightly optimized:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
if (args.length < 2) {
throw new IllegalArgumentException("Usage: java MyClass <rows> <cols>");
}
int rows = Integer.parseInt(args[0]);
int cols = Integer.parseInt(args[1]);
int innerRows = rows - 2;
int innerCols = cols - 2;
String innerRow = innerRows > 0 && innerCols > 0 ? "O".repeat(innerCols) : "";
List<String> box = new ArrayList<>();
box.add("X".repeat(cols));
for (int i = 0; i < innerRows; i++) {
box.add("X" + innerRow + "X");
}
if (rows > 1) {
box.add(box.get(0));
}
for (String row : box) {
System.out.println(row);
}
}
}

create two dimensional array that can store integer values inside, and square them in different method and print them in another method

Complete question is: Create a program that uses a two dimensional array that can store integer values inside. (Just create an array with your own defined rows and columns). Make a method called Square, which gets each of the value inside the array and squares it. Make another method called ShowNumbers which shows the squared numbers.
What I attempted thou it has errors:
public class SquareMatrix {
public static void main(String[] args) {
int sqr[][]= {{1,3,5},{2,4,6}};
System.out.println("Your Original Matrix: ");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
System.out.print(sqr[i][j] + " ");
}
System.out.println();
}
Square();
ShowNumbers();
}
static void Square(){
for(int i = 0; i <= 1; i++) {
for(int j = 0; j <= 2; j++) {
sqr[i][j] = sqr[i][j] * sqr[i][j];
}
}
}
static void ShowNumbers(){
System.out.println("Matrix after changes: ");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
System.out.print(sqr[i][j] + " ");
}
System.out.println();
}
}
}
Also how would I write it if I wanted an input from the user for the col and row for a specific range of 0 to 10, I made an alternative version with many errors below. Below code is not as important as the one above
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
try{
System.out.print("Enter Number of Row for Array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter Number of Column for Array (max 10) : ");
col = scan.nextInt();
if(0>=row && row<=10 || 0>=col && col<=10 ){
}
}
catch (Exception e){
System.out.println("(!) Wrong input...\n");
}
System.out.print("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
arr[i][j] = scan.nextInt();
}
}
}
static void square(){
arr[row][col] = arr[row][col] * arr[row][col];
}
static void ShowNumbers(){
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}}}
PS I am new to java and would appreciate a response with the whole code pasted not just a section of the code so I don't get lost or with the number of the line the error is from.
thanks for any help
Since you are starting from scratch, it would be good to go over the basics of the language again. Take a look at oracle classvars For your upper problem you need to understand the difference between local and instance variables and the difference between static and non static variables respectively. To solve your issue just move the declaration of your array out of the main method and add a static modifier:
public class SquareMatrix {
static int sqr[][] = {{1, 3, 5}, {2, 4, 6}};
public static void main(String[] args) {
//rest of your code
}

What would be method to find count which contains only numbers one by one

I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.

Why wont my 2d array variable take input?

Noob to programming... I need to create a function that receives a 2d array and requests user input to fill both the rows and the columns. The error that shows me is "empty statement" / "not a statement" on the last line.
public static void fillMatrix(int [][] pmatrix) throws IOException {
int [][] matrix = new int [pmatrix.length][pmatrix.length];
int i, k; //loop variables
int rows, columns;
for(i = 0; i < pmatrix.length; i++){
print.println("set the value of the row " + (i + 1));
rows = Integer.parseInt(read.readLine());
}
for(k = 0; k < pmatrix.length; k++){
print.println("set the value of the column " + (k + 1));
colums = Integer.parseInt(read.readLine());
}
matrix = {{rows}, {columns}};
}
First, what you do here is reassigning the variables rows and columns in each iteration. So at the end, you will have one single value per row in your matrix.
Second, you're reassigning the local variable matrix to be a Matrix, that has two rows and one column. And since it doesn't have anything to do with the parameter pmatrix, nothing will happen to it after the method returns.
I assume you want to call that method on an empty 2D-Array and fill it with values from the console. To iterate through a 2D-Array, you will need a nested for-loop and access each index in your matrix individually:
public static void fillMatrix(int [][] pmatrix) throws IOException {
for(i = 0; i < pmatrix.length; i++){
for(int j = 0; j < pmatrix[i].length; i++ {
print.println("set the value of row " + (i + 1) + " in column " + (j + 1));
pmatrix[i][j] = Integer.parseInt(read.readLine());
}
}
}
It is easier to understand in the full context.
The following code has a main method that creates a matrix of size 3x3, you can change this if you like.
Next, it calls the fillMatrix method and then the printMatrix method.
fillMatrix goes through each row and for each row, it goes through each column. For an entry in the matrix, it reads an integer using Scanner instead of BufferedReader because it is easier to use.
printMatrix runs through all the entries and prints them as a table.
Running the program and giving 1 2 3 4 5 6 7 8 9 prints
1 2 3
4 5 6
7 8 9
The program
import java.io.IOException;
import java.util.Scanner;
public class Helper {
public static void main(final String[] args) throws IOException {
final int[][] matrix = new int[3][3];
fillMatrix(matrix);
printMatrix(matrix);
}
public static void fillMatrix(final int[][] matrix) throws IOException {
final Scanner scanner = new Scanner(System.in);
for (int i = 0; i < matrix.length; i++) {
final int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
final int userInput = scanner.nextInt();
row[j] = userInput;
}
}
}
private static void printMatrix(final int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
final int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
System.out.print(row[j] + " ");
}
System.out.println();
}
}
}

2D array and method calling

So, I'm creating this minesweeper game and I am confused with 2 of my methods which one, will initialize the array with a certain character and one method will actually print the game. Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = 0;
int b = 0;
System.out.println("Welcome to Mine Sweeper!");
a = promptUser(in, "What width of map would you like (3 - 20):", 3, 20);
b = promptUser(in, "What height of map would you like (3 - 20):", 3, 20);
eraseMap(new char[b][a]);
simplePrintMap(new char[b][a]);
}
public static int promptUser(Scanner in, String prompt, int min, int max) {
int userInput;
System.out.println(prompt);
userInput = in.nextInt();
while (userInput < min || userInput > max) {
System.out.println("Expected a number from 3 to 20.");
userInput = in.nextInt();
}
return userInput;
}
public static void eraseMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[i].length; ++j) {
map[i][j] = (Config.UNSWEPT);
}
}
return;
}
public static void simplePrintMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[i].length; ++j) {
System.out.print(map[b][a] + " ");
}
System.out.println();
}
return;
}
The methods that are in question is eraseMap and simplePrintMap. eraseMap is supposed to initialize the array with "." and simplePrintMap is supposed to actually print the array. So if i input 3 and 4, it will print periods will a width of 3 and height of 4.
(each period separated by space).
A) You create 2 seperate maps. You perform the erase on the first, then throw it all away, create a new map and print that. Which, of course, is empty.
Try creating one map and work on it:
char[][] map = new char[b][a]
eraseMap(map);
simplePrintMap(map);
B) in the print method, you use the wrong indices:
System.out.print(map[b][a] + " ");
change these to
System.out.print(map[i][j] + " ");
C) not an error, just a hint: you don't need return; at the end of void methods.

Categories

Resources