The problem is when you entry an input with scanner ,it shows on console. I want them to shown in an order. I want them shown like a matris. But with nextInt method all shows bottom of each other.
I want a console output like this:
But with nextInt() method your new int shows on nextLine like this:
How can i show multiple variables in same line with scanner?
import java.util.Scanner;
public class ProbilityMatrixTest {
static int M;
static int N;
static float[][] matrixX;
static float[][] matrixY;
static boolean isProbilityMatrix;
public static void main(String[] args) {
initiate();
testMatrix(matrixX);
System.out.println();
multiplyMatrix();
testMatrix(matrixY);
}
public static void initiate() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row and column size of matrix : ");
M = sc.nextInt();
N = sc.nextInt();
System.out.println();
matrixX = new float[M][N];
System.out.println("Enter values of " + M + "x" + N + " matrix :");
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
matrixX[i][j] = sc.nextFloat();
}
}
}
public static void testMatrix(float[][] givenMatrix) {
isProbilityMatrix = true;
if (M != N) {
isProbilityMatrix = false;
}
for (int j = 0; j < N; j++) {
float rowVariablesTotal = 0;
for (int i = 0; i < M; i++) {
rowVariablesTotal += givenMatrix[i][j];
if (givenMatrix[i][j] < 0) {
isProbilityMatrix = false;
}
}
if (rowVariablesTotal != 1.0f) {
isProbilityMatrix = false;
}
}
System.out.print("TEST RESULT : ");
if (isProbilityMatrix) {
System.out.println("Probility matrix");
} else {
System.out.println("not Probility matrix");
}
}
public static void multiplyMatrix() {
matrixY = new float[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
float newMatrixVariable = 0;
for (int a = 0; a < M; a++) {
newMatrixVariable += (matrixX[i][a] * matrixX[a][j]);
}
matrixY[i][j] = newMatrixVariable;
}
}
System.out.println("The square of given matrix:");
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
System.out.print(matrixY[i][j] + " ");
}
System.out.println();
}
}
}
You need to scan entire lines at a time. Otherwise, you're always pressing the enter key, causing it to look like you're entering one value before the other on previous lines
For example, type 3 3, then enter, then you can type three space separated decimal values, enter, then repeat that twice
System.out.print("Enter the row and column size of matrix : ");
String[] mn = sc.nextLine().split("\\s+");
int M = Integer.parseInt(mn[0]);
int N = Integer.parseInt(mn[1]);
System.out.println();
double[][] matrixX = new double[N][];
for (int i = 0; i < N; i++) {
matrixX[i] = new double[M];
String[] row = sc.nextLine().split("\\s+");
for (int j = 0: j < M: j++) {
matrix[i][j] = Double.parseDouble(row[j]);
//...
}
}
Related
I have been stuck on this exercise for 2 weeks now, hopefully someone can help...
So basically the user starts by providing the number of lines and columns and the corresponding crossed words table(which is a 2d char array) , then inputs the number of words and the words that have to be detected in that board.
The program is supposed to print the table that was given but with every non-word substituted for zeros.
An example:
Input:
4 5
GBCDP
AGGGM
MYIEU
ENBHJ
2
GAME
JUMP
Should output:
G000P
A000M
M000U
E000J
My problem is still in the method for finding the words...
this is my code(it's commented to be easier to understand)
NOTE: the words cannot be found diagonally... also I am missing the part of the program that's supposed to substitute non-words for zeros, because I still can't find the words
import java.util.Scanner;
class game {
private int rows;
private int cols;
private char m[][];
game(int r, int c)
{
rows = r;
cols = c;
m = new char[r][c];
}
//read the game
public void read(Scanner in) {
for (int i=0; i<rows; i++) {
m[i] = in.next().toCharArray();
}
}
//writes the game
public void write() {
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols; j++)
{
System.out.print(m[i][j]);
}
System.out.println();
}
}
//finds the words
public void find(String word) {
for(int i = 0; i < rows; i++)
{
if(word.equals(new String(m[i]))){
System.out.print(i);
}
}
for(int z = 0; z < cols; z++)
{
if(word.equals(new String(m[z]))) {
System.out.print(z);
}
}
}
}
public class wordg {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rows = scan.nextInt();
int columns = scan.nextInt();
game j = new game(rows,columns);
j.read(scan);
//j.write();
int wordnumber = scan.nextInt();
String words[] = new String[wordnumber];
for(int i = 0; i < wordnumber; i++)
{
words[i] = scan.nextLine();
}
for(int w = 0; w < words.length; w++)
{
j.find(words[w]);
}
}
}
Thanks!
How to fix the code
In this part of the answer, I will try to give a step-by-step guide on how to make your code work properly:
The first problem with your code is that you are using the rows instead of the columns, although you obviously want to use columns. This can be done like this:
String col = "";
for(int i = 0; i < rows; i++) {
col += m[i][z];
}
The next problem is that you also have to search for the reversed words. You can do that by just calling the method find with the reversed words also:
for(int w = 0; w < words.length; w++)
{
j.find(words[w]);
j.find(j.reverse(words[w]);
}
The reverse-method could look like this:
public String reverse(String word) {
String result = "";
for(int i = word.length() - 1; i >= 0; i--) {
result += word.charAt(i);
}
return result;
}
After this, your find-method should work.
To output the grid like you want it to look like, we will have to save, where we found a word. This can be done like this:
if(word.equals(new String(m[i]))){
System.out.println("Word found in row: " + i);
for(int j = 0; j < cols; j++) {
test[i][j] = true;
}
}
test is a boolean-array initialized with false in the constructor.
Now we just have to change the write-method:
//writes the game
public void write() {
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols; j++)
{
if(test[i][j]) { //Only print found words, otherwise print "0"
System.out.print(m[i][j]);
}
else {
System.out.print("0");
}
}
System.out.println();
}
}
At this point the program should produce the output you want it to produce.
Possible improvements
If you want to improve your find-method, you could make the program recognize words inside a row or a column, for example recognize the word "YOU" in this grid:
AAYOUA
AAAAAA
AAAAAA
AAAAAA
This can be done like this:
public void find(String word) {
for(int i = 0; i < rows; i++) {
int index = new String(m[i]).indexOf(word); //Index were found word starts (-1 if row/col doesn't contain the word)
if(index >= 0) {
System.out.println("Word found in row: " + i); //Added some information for the user
for(int j = index; j < index + word.length(); j++) {
test[i][j] = true; //Save that word was found in this "cell"
}
}
}
for(int z = 0; z < cols; z++) {
String col = "";
for(int i = 0; i < rows; i++) { //Get column
col += m[i][z];
}
int index = col.indexOf(word);
if(index >= 0) {
System.out.println("Word found in col: " + z);
for(int j = index; j < index + word.length(); j++) {
test[j][z] = true;
}
}
}
}
Some other suggestions:
Class-names should begin with an uppercase-letter
Try to always use the same indentation
Try to always use the same "bracket-style"
(I changed this for you in the final code.)
Final code
All in all your code looks like this now:
Game.java
import java.util.Scanner;
public class Game { //Classes start with uppercase
private int rows;
private int cols;
private char m[][];
private boolean test[][]; //Purpose: test if "cell" where word was found
Game(int r, int c) {
rows = r;
cols = c;
m = new char[r][c];
test = new boolean[r][c];
}
//read the game
public void read(Scanner in) {
for (int i=0; i<rows; i++) {
m[i] = in.next().toCharArray();
}
}
//writes the game
public void write() {
for(int i = 0; i < rows;i++) {
for(int j = 0; j < cols; j++) {
if(test[i][j]) { //Only print found words, otherwise print "0"
System.out.print(m[i][j]);
}
else {
System.out.print("0");
}
}
System.out.println();
}
}
//finds the words
public void find(String word) {
for(int i = 0; i < rows; i++) {
int index = new String(m[i]).indexOf(word); //Index were found word starts (-1 if row/col doesn't contain the word)
if(index >= 0) {
System.out.println("Word found in row: " + i); //Added some information for the user
for(int j = index; j < index + word.length(); j++) {
test[i][j] = true; //Save that word was found in this "cell"
}
}
}
for(int z = 0; z < cols; z++) {
String col = "";
for(int i = 0; i < rows; i++) { //Get column
col += m[i][z];
}
int index = col.indexOf(word);
if(index >= 0) {
System.out.println("Word found in col: " + z);
for(int j = index; j < index + word.length(); j++) {
test[j][z] = true;
}
}
}
}
public String reverse(String word) {
String result = "";
for(int i = word.length() - 1; i >= 0; i--) {
result += word.charAt(i);
}
return result;
}
}
WordG.java
import java.util.Scanner;
public class WordG {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rows = scan.nextInt();
int columns = scan.nextInt();
Game j = new Game(rows,columns);
j.read(scan);
int wordnumber = scan.nextInt();
scan.nextLine(); //To clear the scanner
String words[] = new String[wordnumber];
for(int i = 0; i < wordnumber; i++) {
words[i] = scan.nextLine();
}
for(int w = 0; w < words.length; w++) {
j.find(words[w]);
j.find(j.reverse(words[w])); //You also have to search for reversed words!
}
j.write(); //Write grid after searching
}
}
(I added comments on the right where I changed your code to explain what I did.)
Output
With your example-input, this code creates the following output:
Word found in col: 0
Word found in col: 4
G000P
A000M
M000U
E000J
And with the added functionality, the input
5 5
SHARK
AYOUB
MABCD
EABCD
ABCDE
3
YOU
ME
SHARK
gives the output
Word found in row: 1
Word found in col: 0
Word found in row: 0
SHARK
0YOU0
M0000
E0000
00000
I'm trying to randomly place 1D string array into 2D char array but I'm having issues with my for-loop.
userWords is 1D array of String while puzzleBoard is a 2D array of char.
I've tried
for(int i=0; i<userWords.length;i++) {
puzzleBoard[r++] = userWords[i].toCharArray();
}
but it's not placing it randomly like I want it to
So I tried
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
but it's printing only 3 char instead of the 3 strings of char into the char array.
I've also tried
puzzleBoard[r][c] = userWords[i].toCharArray();
instead of
puzzleBoard[r][c] = userWords[i].charAt(i);
But it display error "cannot convert from char[] to char"
Thank you
Full Code
public static void main(String[] args) {
String[] userWords = new String[3];
Methods.userInput(userWords); //ask user for input
Methods.fillPuzzle(puzzleBoard); //fill the puzzle with random char
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
Methods.printPuzzle(puzzleBoard); //print out the puzzle
}//end main
public static void printPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print((i+1));
System.out.println();
}
}//end printPuzzle
public static void fillPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = '*';
}
}
}//end fillPuzzle
public static void userInput(String a[]) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < a.length;i++) {
System.out.println((i+1) + ". enter word:");
a[i] = input.next().toUpperCase();
}
}//end userInput
You can try this one:
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(puzzleBoard.length);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
And you should add something that detects whether there is already a word at this position, otherwise you would overwrite it if the random numbers point to a location where is already written a word.
I think you should use 2 for-loops because you want to select first the string and next the characters in the string.
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
I have this text file:
2
2
12
13
23
24
49
59
69
79
the first two numbers should be the rows and columns of the matrix, which is 2x2 in this case. My issue that I'm trying to get around is finding a way to include a second 2D array that holds the second matrix.
my code:
Scanner fileInput = new Scanner(new File("input1.txt"));
int n1 = fileInput.nextInt();
int n2 = fileInput.nextInt();
System.out.print("matrix is " + n1 + "x" + n2 +"\n");
int [][] firstMatrix = new int [n1][n2];
int [][] secondMatrix = new int [n1][n2];
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
firstMatrix[i][j] = fileInput.nextInt();
}
}
}
System.out.println("Matrices: ");
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.println(firstMatrix[i][j]);
}
}
it only prints the following:
12
13
23
24
How do I make it read the next four lines of integers from the file? It would also be helpful to understand how I can make it look something like this:
12 13
23 24
EDIT: This approach seemed to help with the last question:
for(int i=0; i<n1; i++)
{
for(int j=0; j<n2; j++)
{
System.out.print(firstMatrix[i][j] + " " );
//System.out.print(secondMatrix[i][j] + " ");
}
System.out.println();
}
The only problem I'm facing now is being able to include the four other integers and turn them into a matrix.
You can group them to 1 array:
int matrixNumb = 2; // number of matrix
int [][][] matrix = new int [matrixNumb][n1][n2];
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
matrix [h][i][j] = fileInput.nextInt(); // read from file
}
}
}
}
System.out.println("Matrices: ");
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.print(matrix[h][i][j]);
System.out.print("\t"); //How do you want to separate columns?
}
System.out.print("\r\n"); //How do you want to separate rows?
}
System.out.println(); //How do u want to print next matrix?
}
I have not compiled or run it, but hope it help.
You can just read data for the two arrays from file sequentially, like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
private static void readMatrix(final Scanner scanner, final int[][] matrix) {
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[i].length; ++j) {
if (scanner.hasNextInt()) {
matrix[i][j] = scanner.nextInt();
}
}
}
}
private static void displayMatrix(final int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(final String... args) throws FileNotFoundException {
final Scanner scanner = new Scanner(new File("input.txt"));
final int n1 = scanner.nextInt();
final int n2 = scanner.nextInt();
System.out.print(String.format("The matrix is %d x %d \n", n1, n2));
final int[][] firstMatrix = new int[n1][n2];
final int[][] secondMatrix = new int[n1][n2];
System.out.println("Reading data to first matrix");
readMatrix(scanner, firstMatrix);
System.out.println("Reading data to second matrix");
readMatrix(scanner, secondMatrix);
System.out.println("First Matrix");
displayMatrix(firstMatrix);
System.out.println("Second Matrix");
displayMatrix(secondMatrix);
}
}
for(int i = 0; i < n1*n1; i++)
{
for(int j = 0; j < n2*n2; j++)
{
if(fileInput.hasNextInt())
{
if(i < n1){
firstMatrix[i][j] = fileInput.nextInt();
}
else
{
secondMatrix[i][j] = fileInput.nextInt();
}
}
}
}
You have two matrix of size n*n so you can do like this:
I have multiple arrays whose sizes need to be determined by the user input. These arrays should be accessible in the main method as well as the stepTwo() method. However, I am stuck. The user input doesn't come until the main method, but if I declare the arrays in the main method, then I can't access the arrays in the stepTwo() method. I would prefer not to pass the arrays as parameters to stepTwo() as I tried that before but came up with multiple errors. Any suggestions? See below for complete code:
public class AssignmentIII
{
public static int numProcesses; // Represents the number of processes
public static int numResources; // Represents the number of different types of resources
public static int[] available = new int[numResources]; // Create an emptry matrix for available processes
public static int[][] allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
public static int[][] request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
public static int[] work = new int[numResources]; // Create an empty work matrix
public static Boolean[] finish = new Boolean[numProcesses]; // Create an empty finish matrix
public static void main(String[] args) throws FileNotFoundException
{
try
{
Scanner scan = new Scanner(System.in);
Scanner fileScan = new Scanner(new File("input1.txt")); // Create file scanner
System.out.println("Please enter the total number of processes: ");
numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
numResources = scan.nextInt();
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
// Begin deadlock detection algorithm
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
stepTwo();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
}
public static void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
}
Declare the array as you do - "above main", but initialize it after reading in the appropriate size.
Declaration:
public static int[] available;
Initialization:
available = new int[numResources];
you must initialize the array into de main block, something like this.
public class AssignmentIII
{
public static int numProcesses; // Represents the number of processes
public static int numResources; // Represents the number of different types of resources
public static int[] available ;
public static int[][] allocation ;
public static int[][] request ;
public static int[] work ;
public static Boolean[] finish ;
public static void main(String[] args) throws FileNotFoundException
{
try
{
Scanner scan = new Scanner(System.in);
Scanner fileScan = new Scanner(new File("input1.txt")); // Create file scanner
System.out.println("Please enter the total number of processes: ");
numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
numResources = scan.nextInt();
available = new int[numResources]; // Create an emptry matrix for available processes
allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
work = new int[numResources]; // Create an empty work matrix
finish = new Boolean[numProcesses]; // Create an empty finish matrix
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
// Begin deadlock detection algorithm
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
stepTwo();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
}
public static void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
}
but this, is not a recommended way. Because is not the right way for use the static method and static attribute. Furthermore you should use encapsulation.
Using a better design and encapsulation method, your code can be improved something like this.
public class AssignmentIII
{
int numProcesses; // Represents the number of processes
int numResources; // Represents the number of different types of resources
String filepath;
int[] available = new int[numResources]; // Create an emptry matrix for available processes
int[][] allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
int[][] request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
int[] work = new int[numResources]; // Create an empty work matrix
Boolean[] finish = new Boolean[numProcesses]; // Create an empty finish matrix
public AssignmentIII(int numResources,int numProcesses, String filepath){
this.numProcesses = numProcesses;
this.numResources = numResources;
this.filepath = filepath;
available = new int[numResources]; // Create an emptry matrix for available processes
allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
work = new int[numResources]; // Create an empty work matrix
finish = new Boolean[numProcesses]; // Create an empty finish matrix
}
public void initilizeMatrix() throws FileNotFoundException{
Scanner fileScan = new Scanner(new File(filepath)); // Create file scanner
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
fileScan.close();
}
public void print(){
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
}
// Begin deadlock detection algorithm
public void deadLockdetecter(){
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
}
public void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
public static void main(String[] args) throws FileNotFoundException
{
AssignmentIII assignment;
String p_filepath;
int p_numProcesses;
int p_numResources;
p_filepath = "inpu1t.txt";
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the total number of processes: ");
p_numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
p_numResources = scan.nextInt();
scan.close();
assignment = new AssignmentIII(p_numResources, p_numProcesses, p_filepath);
try
{
assignment.initilizeMatrix();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
assignment.stepTwo();
}
}
Ok, the title might be deceiving. All i want to do is take my Bingo program and when the second bingo card is printed, i want to replace all the "0"'s with "X"'s. I was thinking i would have to go and change the array to an string, but i'm not surer where to start.
Here is the Bingo program:
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Bingo
{
public static final int ROWS = 5;
public static final int COLS = 5;
public static final int VERTICAL = 1;
public static final int DIAGONAL = 2;
public static final int HORIZONTAL = 3;
public static int winFound;
public static int currPick = 0;
public static int randomPick = 0;
public static int WinFound;
public static void main(String[] args)
{
int Totcards;
int[][] card = new int[ROWS][COLS];
int[] picks = new int[25];
fillCard (card);
printCard(card);
playGame(card);
printCard(card);
finalCard(card);
}
private static void fillCard (int[][] card)
{
// FileReader fileIn = new FileReader("Bingo.in");
// Bufferreader in = new Bufferreader(fileIn);
try {
Scanner scan = new Scanner(new File("bingo.in"));
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
card[i][j] = scan.nextInt();
}
}
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
}
private static void printCard (int[][] card)
{
System.out.println("\n\tYOUR BINGO CARD : ");
System.out.println("\n\tB I N G O");
System.out.println("\t----------------------");
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
System.out.print("\t" + card[i][j]);
}
System.out.print("\n");
}
}
private static void playGame (int[][] card)
{
int numPicks = 0;
System.out.println("\n\tBINGO NUMBERS PICKED AT RANDOM FROM BIN: ");
while (true)
{
markCard (card); // Generate a random num & zero-it out
winFound = checkForWin(card); // Look for zero sums
numPicks++;
if (winFound != 0)
{
if (winFound == 1)
{
System.out.print("\n\n\tYOU WIN WITH A VERTICAL WIN AFTER " + numPicks + " PICKS\n");
}
else if (winFound == 2){
System.out.print("\n\n\tYOU WIN WITH A DIAGONAL WIN AFTER " + numPicks + " PICKS\n");
}
else if (winFound == 3){
System.out.print("\n\n\tYOU WIN WITH A HORIZONTAL WIN AFTER " + numPicks + " PICKS\n");
}
announceWin (numPicks);
return;
}
}
}
private static void markCard (int[][] card)
{
int randomPick = (int) (Math.random() * 74) + 1;
for (int j = 0; j < ROWS; j++){
for (int k = 0; k < COLS; k++){
if (card[j][k]==randomPick)
card[j][k] = 0;}
}
System.out.print("\t " + randomPick + " ");
System.out.print("");
}
private static int checkForWin(int[][] card)
{
int sum=0;
for (int i = 0; i < ROWS; i++)
{
sum = 0;
for (int j = 0; j < COLS; j++)
sum += card[i][j];
if (sum == 0)
return HORIZONTAL;
}
for (int j = 0; j < COLS; j++)
{
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][j];
if (sum == 0)
return VERTICAL;
}
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][ROWS-i-1];
if (sum == 0)
return DIAGONAL;
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][i];
if (sum == 0)
return DIAGONAL;
return WinFound;
}
private static void makeCard(int[][] card, int[] picks)
{
int count = 100;
int currPick = 0;
for (int i=0; i<count; i++){
currPick = (int)(Math.random() * 74) + 1;
System.out.print(" " + currPick + "\n");
picks[i] = currPick;
}
}
private static void announceWin(int numPicks)
{
}
private static boolean duplicate (int currPick, int[] picks, int numPicks)
{
for (int i = 0; i < numPicks; i++){
if (picks[i] == currPick){
return true;}
}
return false;
}
private static void finalCard (int[][] card)
{
Arrays.sort(card);
final String stringRep = Arrays.toString(card);
final String[] out =
stringRep.substring(1, stringRep.length() - 1).split("\\s*,\\s*");
System.out.println(Arrays.toString(out));
}
}
Try this:
System.out.print("\t" + (card[i][j] == 0 ? "X" : card[i][j]))
Why don't you just use a String[][] for the fields from the beginning? You can still compare String values with ints (with Integer.valueOf for instance) and this way you don't have to switch types runtime...