2D array and method calling - java

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.

Related

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
}

Array not copying another array

I am trying to develop a program to delete all the median values from an array (the middle value if it has an odd number of elements, the two middle values if it has an even number of elements) until there are only two elements left, elements [0] and [1]. For example, if the user inputs 1, 2, 3, 4, 5, the program will return [1, 5]. I put down what I thought logically might help, but my array x isn't copying myArray in the for loops. I am not looking for someone to completely do the code for me, just to point out where I am wrong. Here is my code:
import java.util.*;
public class Deletion
{
public static void main(String[]args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the array length:");
int [] myArray = new int[kb.nextInt()];
int [] x = new int[myArray.length - 1];
int index1 = 0;
int index2 = 0;
int index3 = 0;
if(myArray.length < 3)
{
System.out.println("Please make sure array length is greater than two. Run again.");
System.exit(0);
}
else
{
for(int i = 0; i < myArray.length; i++)
{
System.out.println("Please enter a number for position " + i + ":");
myArray[i] = kb.nextInt();
}
for(int i = 0; i < myArray.length; i++)
{
while(myArray.length > 2)
{
if(myArray.length%2 != 0)
{
index1 = (myArray.length/2);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index1)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
else
{
index2 = (myArray.length/2);
index3 = (myArray.length/2 - 1);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index2 && j != index3)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
}
}
}
System.out.println(Arrays.toString(myArray));
}
}
You must create the array and populate it, else it's using the same memory address, hence won't work. Use the following:
myArray = ArrayUtils.clone(x);
When you are doing do β€œmyArray = x”, your are actually merely assigning a reference to the array. Hence, if you make any change to one array, it would be reflected in other arrays as well because both myArray and x are referring to the same location in memory.
Thus, what you need is
myArray = x.clone();
I cleaned up your code a bit. According to what you described, what really matters is pulling in the minimum and maximum values in the array - everything else will be deleted, so you simply need a single traversal through the array to find those two values.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isValid = false;
int validLength = 0;
System.out.println("Please enter the array length:");
while (!isValid) {
int length = scanner.nextInt();
if (length < 3) {
System.out.println("Please make sure array length is greater than two. Try again.");
}
else {
isValid = true;
validLength = length;
}
}
int minimumValue = Integer.MAX_VALUE, maximumValue = Integer.MIN_VALUE;
for (int i = 0; i < validLength; i++) {
System.out.println("Please enter a number for position " + i + ":");
int nextInt = scanner.nextInt();
if (nextInt < minimumValue) minimumValue = nextInt;
else if (nextInt > maximumValue) maximumValue = nextInt;
}
System.out.println(Arrays.toString(new int[] {minimumValue, maximumValue}));
}
Edit: made another revision as using an array is unnecessary. Just keep track of the minimum and maximum values as they are being entered.

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.

Print a rhombus pattern from user input

I have a task to ask user for input (user's name) and then to print a rhombus pattern out of it.
For example:
If user's name is Thomas, then the output should be like this:
T
Th
Tho
Thom
Thoma
Thomas
homas
omas
mas
as
s
This is my code so far. I am having trouble with second for loop. I can easily print out lines until "Thomas", but I don't know, how to print whitespace infront so that the end of the word will be on the same place.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
for (int j = 1, k = 1; j <= enteredNamesLength; i++, k++) {
System.out.println(k * " " + name.substring(j, enteredNamesLength));
}
}
}
}
I think there must be one for loop to print the name like what you did, then another for space and inside the same print the substring.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int i = 0; i <= enteredNamesLength; i++) {
System.out.println(name.substring(0, (int) i));
}
for(int i = 1;i <= enteredNamesLength; i++ ) {
for(int j = 0;j < i; j++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
}
It would be easier to do it in 2 times : substring from start to an index, and then print the spaces followed by the end of the world, ans some changes to do :
no need to cast i as int, it's already an int
first loop : start index i at 1 and not 0, no avoid empty line
second loop : end index for i at enteredNamesLength-1 and not enteredNamesLength to avoid also an empty line
for (int i = 1; i <= enteredNamesLength; i++) { // start at 1
System.out.println(name.substring(0, i)); // don't cast
}
for (int i = 1; i < enteredNamesLength; i++) { // stop at enteredNamesLength-1
for (int space = 0; space <= i; space++) {
System.out.print(" ");
}
System.out.println(name.substring(i, enteredNamesLength));
}
Here is another solution, you can extract a print method which accepts a start and stop. If the index between them, then print character at index, otherwise print whitespace.
import java.util.Scanner;
public class wordRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
int enteredNamesLength = name.length();
for (int start = 0, stop = 0; start < enteredNamesLength && stop < enteredNamesLength; ) {
print(start, stop, name);
if (stop < enteredNamesLength - 1) {
stop++;
} else {
start++;
}
}
}
private static void print(int start, int stop, String name) {
for (int index = 0; index < name.length(); index++) {
if (index >= start && index <= stop) {
System.out.print(name.charAt(index));
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
You can combine the upper increasing part and the lower decreasing part in one loop.
Try it online!
public static void main(String[] args) {
String str = "RHOMBUS";
int n = str.length();
// two parts: negative and positive
for (int i = 1 - n; i < n; i++) {
// leading whitespaces for the positive part
for (int j = 0; j < i; j++) System.out.print(" ");
// negative part: str.substring(0, n + i);
// positive part: str.substring(i, n);
String sub = str.substring(Math.max(0, i), Math.min(n + i, n));
// output the line
System.out.println(sub);
}
}
Output:
R
RH
RHO
RHOM
RHOMB
RHOMBU
RHOMBUS
HOMBUS
OMBUS
MBUS
BUS
US
S
See also: Writing a word in a rhombus / diamond shape
This code works with both regular UTF8 characters and surrogate pairs.
Try it online!
public static void main(String[] args) {
String str = "π—₯π™·π™Ύπ™Όπ™±πš„π—¦";//"RHOMBUS";
int n = (int) str.codePoints().count();
// two parts: negative and positive, i.e.
// upper increasing and lower decreasing
IntStream.range(1 - n, n)
// leading whitespaces for the positive part
.peek(i -> IntStream.range(0, i)
.forEach(j -> System.out.print(" ")))
// negative part: range(0, n + i);
// positive part: range(i, n);
.mapToObj(i -> str.codePoints()
.skip(Math.max(0, i))
.limit(Math.min(n + i, n))
.mapToObj(Character::toString)
.collect(Collectors.joining()))
// output the line
.forEach(System.out::println);
}
Output:
π—₯
π—₯𝙷
π—₯𝙷𝙾
π—₯𝙷𝙾𝙼
π—₯𝙷𝙾𝙼𝙱
π—₯π™·π™Ύπ™Όπ™±πš„
π—₯π™·π™Ύπ™Όπ™±πš„π—¦
π™·π™Ύπ™Όπ™±πš„π—¦
π™Ύπ™Όπ™±πš„π—¦
π™Όπ™±πš„π—¦
π™±πš„π—¦
πš„π—¦
𝗦

java matrix 0's and 1's

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);
}
}

Categories

Resources