How to accept values within a certain range 2d array - java

I was wondering how to i set a range between certain number when entering numbers in?
Thanks
I tried using a do loop but it just kept looping even when i entered numbers within the range
public static void main(String args[])
{
int row, col, i, j;
int a[][]=new int[10][10];
do{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the order of a square matrix :");
row=sc.nextInt();
col=sc.nextInt();
/* checking order of matrix and then if true then enter the values
* into the matrix a[][]
*/
if(row == col)
{
System.out.println("Enter elements in the matrix:"+row*col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
a[i][j]=sc.nextInt();
}
}
} while(row != col);
// Display the entered value
System.out.println ("You have entered the following matrix");
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
System.out.print (a[i][j] + " ");
System.out.println ();
}

First of all you should learn to extract tasks in methods and add Javadoc to make your code easier to read.
Hope this helps you:
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int dimension;
System.out.println("Enter the dimension of a squared matrix :");
dimension = sc.nextInt();
final int col = dimension;
final int row = dimension;
int[][] matrix = fillMatrix(row, col);
displayMatrix(matrix);
}
/**
* Prints the given matrix to console
*
* #param matrix to be printed
*/
private static void displayMatrix(int[][] matrix) {
System.out.println("You have entered the following matrix");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
/**
* Uses users input to fill create a matrix with the given dimensions
*
* #param row matrix row dimension
* #param col matrix column dimension
*
* #return a filled matrix
*/
private static int[][] fillMatrix(final int row, final int col) {
System.out.println("Enter elements in the matrix:" + row * col);
int[][] matrix = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int tmpNumber = 0;
while(tmpNumber<15 || tmpNumber >60){
System.out.println(String.format("Enter value for row %s, column %s between 15 and 60", i, j));
tmpNumber = sc.nextInt();
}
matrix[i][j] = tmpNumber;
}
}
return matrix;
}
Output:
Enter the dimension of a squared matrix :
2
Enter elements in the matrix:4
Enter value for row 0, column 0 between 15 and 60
2
Enter value for row 0, column 0 between 15 and 60
17
Enter value for row 0, column 1 between 15 and 60
18
Enter value for row 1, column 0 between 15 and 60
19
Enter value for row 1, column 1 between 15 and 60
20
You have entered the following matrix
17 18
19 20

First add the bounds as constant
final int LOWER_BOUND = 0;
final int UPPER_BOUND = 100;
Then check in the loop each entered value against the bounds before adding the value to the array
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
The problem remaining is that you can't use you for loops as they are now since the user might need several iterations to enter the right value. One simple solution is to surround the above code in a infinite while loop that is not exited until a correct value is given.
while (true) {
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
break;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
}
A better solution might be to replace the innermostfor loop with a while loop where you increase j manually when a correct value has been entered

This is simple example for your cause.
public static void main(String[] args) {
int number;
String getInputLine;
Scanner sc = new Scanner(System.in);
int a[][] = new int[10][10];
// for number of rows in your array
for (int i = 0; i < a.length; i++) {
// for number of columns in your array
for (int j = 0; j < a[0].length; j++) {
// print this message on screen
System.out.print("Enter your number: ");
// get input from next line
getInputLine = sc.nextLine();
//if you haven't match one or more integers
while (!getInputLine.matches("\\d{1,}")) {
System.out.print("Error! You inputted an invalid passcode, try again: ");
getInputLine = sc.nextLine(); // Prints error, gets user to input again
}
number = Integer.parseInt(getInputLine); // parse input into an integer
a[i][j] = number; // store it to array at position i j
System.out.println("You've set number " + number + " for array[" + i + " " + j + "]"); // Prints the passcode
}
}
//print your array
System.out.println(Arrays.deepToString(a));
}
}

Related

Adding columns and rows in a 2D array of String type?

I found an exercise in my textbook that makes this 2D array.
I have the input loop working, and the table prints successfully but I can't find a way to take the values in each row and column and print out the totals as shown in the exercise.
I have asked my professor and he said he couldn't remember how to do it with a string array. I hope there is a way to convert each number from string to an int. I assume that creating a double array would have been much easier than a String array but at this point I wouldn't know convert all my work over.
package Assignment2;
import java.util.*;
/**
*
* #author Lyan
*/
public class Exercise7_20
{
public static void sales2DArray(int salesPerson, int product, double value)
{
}
public static void main(String[] args)
{
int salesP = 0; //salesPerson set to 0
String[][] table = new String[5][5]; // A matrix of '5 rows and '5 Columns'
//For loop that replaces null values in table with 0.00
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (table[i][j] == null) {
table[i][j] = " 0.0";
}
}
}
//Input for salesPerson
Scanner inSales = new Scanner(System.in);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//While loop to ask for salesPerson, product, and sales amount (val)
while(salesP > 0 && salesP < 5)
{
//input for Product number
Scanner inProduct = new Scanner(System.in);
System.out.println("Enter product number");
int productNum = inProduct.nextInt();
//input for sales amount
Scanner inValue = new Scanner(System.in);
System.out.println("Enter Sales amount");
double val = inValue.nextDouble();
//sets the values onto the table.
table[productNum - 1][salesP] = " " + Double.toString(val);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//makes the 1-5 on the left hand side of the table
}
for(int i = 1; i < 6; i++)
{
table[i-1][0] = " " + i + "";
}
//Hardcoded header
System.out.println("Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total");
//Makes the 2D array to print in a box format rather than a straight line.
System.out.println(Arrays.deepToString(table).replace("],","]\n"));
//Anything below is my testing to get the total to print out for each individual salesPerson (column)
//and the totals for the products for all salesPerson (rows)
System.out.print("Total ");
String total = "";
int sum = 0;
for(int down = 0; down < 5; down++)
{
//append
}
//successfully reads the last value of each column but does not print the total
//only successfully prints the last value
for(int c = 1; c < 5; c++)
{
for(int r = 0; r < 5; r++)
{
String temp = table[r][c];
total = temp;
}
System.out.print(total + " ");
}
}
}
You can use this simple logic to find the sum of each individual row and column of your 2D array.
double[] sumOfRows = new double[5];
double[] sumOfCols = new double[5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
sumOfRows[i] = sumOfRows[i] + Double.parseDouble(table[i][j]);
sumOfCols[i] = sumOfCols[i] + Double.parseDouble(table[j][i]);
}
}
Here we declare 2 additional arrays to store the sum of each row and column respectively. You can print them according to your logic as desired.
Also note use Double.parseDouble(...) to convert a String to a double.

Selection sort not working properly with zero or negative inputs

Im not really sure why the selection sort isn't working with negative numbers and zeros in the array. It works perfectly fine with all positive integers. Feedback would be greatly appreciated.
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
}
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
Selection sort method along with the class for the project:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = 0;
do {
n = getNumDigits(in);
if (n != 0) {
int[] digits = new int[n];
getDigits(digits, in);
displayDigits(digits);
selectionSort(digits);
}
} while (n != 0);
in.close();
System.out.println("No digits to sort? Goodbye! ");
}
// Given a Scanner as input, prompts the user for the number of digits they will
// be
// entering into an array. If the number given by the user is less than 0,
// display
// an error message and ask for a number that is 0 or greater. When a valid
// number is
// received, return it to the calling program.
private static int getNumDigits(Scanner inScanner) {
int digits = 0;
do {
System.out.print("Please enter the number of digits to be stored: ");
digits = inScanner.nextInt();
if (digits < 0) {
System.out.println("ERROR! You must enter a non-negative number of digits!\n");
}
} while (digits < 0);
return digits;
}
// Given an array and a Scanner as input, prompt the user to input integers to
// fill the
// array. The procedure should display a prompt for the user to enter an
// integer, and
// should loop until the entire array is filled with integer.
private static void getDigits(int[] digits, Scanner inScanner) {
int i = 0;
while (i < digits.length) {
System.out.print("Enter integer " + i + ": ");
digits[i] = inScanner.nextInt();
i++;
}
}
// Given an array as input, displays the total number of digits contained in the
// array
// and displays the contents of the array in order, starting at index 0 and
// ending
// with the final index of the array.
private static void displayDigits(int[] digits) {
System.out.println("\nArray before sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i = 0; i < digits.length; i++) {
System.out.print(digits[i] + " ");
}
System.out.println("\n");
}
// FOR LAB10B
// Given an array of integers as input, sorts the array using the Selection Sort
// algorithm
// provided in the Closed Lab 10 write-up.
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
}
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
Thanks & I apologize for all the edits. I never use online forums.
Try doing swapping outside inner for loop :-
private static void selectionSort(int[] digits) {
for (int i = 0; i < digits.length - 1; i++) {
int index = i;
for (int j = i + 1; j < digits.length; j++) {
if (digits[j] < digits[index]) {
index = j;
}
//previously u were doing swapping here
//System.out.println("inner : " + convert(digits));
}
//i shifted the swapping block to this place
int min = digits[index];
digits[index] = digits[i];
digits[i] = min;
//System.out.println("outer : " + convert(digits));
}
System.out.println("Array after sorrting:");
System.out.println("Number of digits in array: " + digits.length);
System.out.print("Digits in array: ");
for (int i: digits) {
System.out.print(i + " ");
}
System.out.println("\n");
}
============
input : 4,0,-4,5,2,1,
Array after sorrting:
Number of digits in array: 6
Digits in array: -4 0 1 2 4 5
============
input : 3,4,2,5,3,21,-7,3,26,-43,-12,22,
Array after sorrting:
Number of digits in array: 12
Digits in array: -43 -12 -7 2 3 3 3 4 5 21 22 26

How to dynamically format Strings in Java

The following program prints the multiplication table 9xN which N is given by the user. My cells are fixed to be aligned only when the product is 2 numbers long.
What can I do so the cells will be aligned with any size of numbers?
public static void main(String[] args) {
//Reading the number n.
System.out.print("Give a number: ");
int n = StdIn.readInt();
//Validating the number.
while(n<1) {
System.out.println("Please give a number greater or equal to 1");
n = StdIn.readInt();
}
/*---------------------------------
*
*Lines 27-36 -> Creating the first
*line and the first line's design.
*
----------------------------------*/
for (int i = 1; i <= n; i++) {
System.out.printf(" %-4d", i);
}
System.out.println();
System.out.print(" +");
for (int i = 1; i <= n; i++) {
System.out.print("-------+");
}
System.out.println();
/*----------------------------------
*
*Lines 45-58 -> Printing the product
*of the numbers and the design of
*the table.
*
----------------------------------*/
for (int i = 1; i <=9 ; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= n; j++) {
int a = (i * j);
String b = " | ";
System.out.printf("%2d %s", a, b);
}
System.out.println();
System.out.print(" +");
for (int k = 1; k <= n; k++) {
System.out.print("-------+");
}
System.out.println();
}
}
}
What can I do so the cells will be aligned with any size of numbers?
Not Aligned Cells
Aligned Cells
Thanks in advance.
To expand #Thomas Weller's comment a little, you need to separate the table cell value calculation loop from the table printing loop because you need to know the maximum number of digits in any cell before you start printing out the table so the 2 in %2d can be that max value instead.
EDIT: You will also need to know that max value in order to create the correct cell width instead of hard coding "-------+"

User Input java 2d Array

I need to create code that takes user input to create the size of the 2d array (rows and columns must be less than 6), then fill it up with values that the user gives (between -10 and 10). My loop for taking the values isn't working at all and I'm not sure why. Here's the code
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Implement scanner
Scanner input = new Scanner(System.in);
// create loop for accepting matrix input
// first accept row size
System.out.println("Please enter the number of rows in your matrix. Must be 5 or less.");
int row = input.nextInt();
while (row > 5 || row < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of rows in your matrix. Must be between 5 and 1.");
row = input.nextInt();
}
// next accept column size
System.out.println("Please enter the number of columns in your matrix. Must be 5 or less.");
int column = input.nextInt();
while (column > 5 || column < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of columns in your matrix. Must be between 5 and 1.");
column = input.nextInt();
}
// declare array with row and columns the user gave
int[][] userArray = new int[row][column];
// create loop for accepting values within the matrix
// first loop for row values
for (int i = 0; i < userArray.length; i++) {
System.out.println("Please enter numbers between -10 and 10 for your matrix rows");
int rowValues = input.nextInt();
while (rowValues > 10 || column < -10) {
System.out.println(
"Sorry. Your number is not the correct size. " + "Please enter a number between 10 and -10.");
rowValues = input.nextInt();
}
// second embedded loop for column values
for (int j = 0; j < userArray[i].length; j++) {
System.out.println("Please enter numbers between -10 and 10 for your matrix columns");
int columnValues = input.nextInt();
while (columnValues > 10 || column < -10) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter a number between 10 and -10.");
columnValues = input.nextInt();
}
}
}
printMatrix(userArray);
}
Couple of things here. First, your for-loop has two separate loops for the rows and columns. I assume what you're going for is prompting the user for each individual cell of the 2D array, which would require two nested loops. Second, at no point does your code example assign the user input to a variable, so I presume your output is just a bunch of 0 values?
You're probably looking for something more like this:
for (int i = 0; i < userArray.length; i++)
for(int j = 0; j < userArray[i].length; j++)
{
System.out.println("Please enter numbers between -10 and 10 for your matrix");
int valueIn = input.nextInt();
while (valueIn > 10 || valueIn < -10)
{
System.out.println("Sorry. Your number is not the correct size. " + "Please enter a number between 10 and -10.");
valueIn = input.nextInt();
}
userArray[i][j]=valueIn;
}
You need a nested loop, to read values at row and then column level.
Something like below:
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Implement scanner
Scanner input = new Scanner(System.in);
// create loop for accepting matrix input
// first accept row size
System.out.println("Please enter the number of rows in your matrix. Must be 5 or less.");
int row = input.nextInt();
while (row > 5 || row < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of rows in your matrix. Must be between 5 and 1.");
row = input.nextInt();
}
// next accept column size
System.out.println("Please enter the number of columns in your matrix. Must be 5 or less.");
int column = input.nextInt();
while (column > 5 || column < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of columns in your matrix. Must be between 5 and 1.");
column = input.nextInt();
}
// declare array with row and columns the user gave
int[][] userArray = new int[row][column];
for(int i=0;i< row ; i++){
for(int j=0; j< column; j++) {
System.out.print("Please enter the value for array["+i+"]["+j+"] (between -10 and 10):");
int val = input.nextInt();
if(val>10 || val< -10) {
System.out.println("Invalid value.");
continue;
}
userArray[i][j] = val;
}
}
printMatrix(userArray, row, column);
}
public static void printMatrix(int[][] array, int row, int column) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
public class Matrix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of rows.");
int rows = getValueFromConsole(scan, 1, 5);
System.out.println("Enter number of columns.");
int cols = getValueFromConsole(scan, 1, 5);
System.out.println("Enter matrix data.");
int[][] matrix = createMatrix(scan, rows, cols, -99, 99);
printMatrix(matrix);
}
private static int[][] createMatrix(Scanner scan, int rows, int cols, int min, int max) {
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
matrix[row][col] = getValueFromConsole(scan, min, max);
return matrix;
}
private static int getValueFromConsole(Scanner scan, int min, int max) {
while (true) {
System.out.format("Number [%d:%d]: ", min, max);
int val = scan.nextInt();
if (val >= min && val <= max)
return val;
System.out.println("Sorry. Your number is not correct. Try again.");
}
}
private static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++)
System.out.format("%4d", matrix[row][col]);
System.out.println();
}
}
}
Output:
Enter number of rows.
Number [1:5]: 3
Enter number of columns.
Number [1:5]: 3
Enter matrix data.
Number [-99:99]: 10
Number [-99:99]: -11
Number [-99:99]: 12
Number [-99:99]: -13
Number [-99:99]: 14
Number [-99:99]: -15
Number [-99:99]: 16
Number [-99:99]: -17
Number [-99:99]: 18
10 -11 12
-13 14 -15
16 -17 18

Java: Unable to get Median calculated with code

I have two files that I am using for my Array median code. The first file( ArrayMedian.java) is used to collect and then calculate the median, the second file is the tester file ( ArrayMedianTest.java)
I was supplied with some source code and needed to modify it accept a set range for each number in the dataset. I got that part done and the random range displays, but now when I get to he array it no longer calculates, I really can't put my finger on what is going wrong.
Another thing I am trying to do is in the ArrayMedian, is put a while loop in there to make it terminate if a '0' is input for the dataset, but it does not seem to want to work in that file, could it be due to no main in the file?
package bonus2.u06.exercise.ex3;
import java.util.Scanner;
public class ArrayMedian {
private int[] arr; // just declare array
Scanner keyboard; // shared field
// initialize keyboard and array
public void init() {
keyboard = new Scanner( System.in );
System.out.print("Enter the dataset size: ");
int size = keyboard.nextInt(); // must be odd number
arr = new int[ size ]; // instantiate
}
// Randomize the array
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
}
}
// find the median of array
public int calcMedian() {
int half_length = arr.length/2;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] > arr[j])
count++;
}
if (count == half_length) {
//<========= terminate this method
return arr[i];
}
}
return 0;
}
}
ArrayMedianTest:
package bonus2.u06.exercise.ex3;
public class ArrayMedianTest {
public static void main(String args[]) {
// instantiate
ArrayMedian obj = new ArrayMedian();
// execute all methods
obj.init();
obj.getRange();
int median = obj.calcMedian();
System.out.println("\nmedian : " + median);
System.out.println("\n--- done ---");
}
}
Turn out, your algorithm works perfectly fine, except in the getRange() method, you forgot to set the values of the array, so the array is an array of zeros. Here is how it should look:
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
arr[i] = myRnd; // <-- You missed this line right here!
}
}
Also, as a recomendation, if you want to put code in stackoverflow, it has to have a spacing of four at the begining of the line plus any indenting you might use. Good luck programming!

Categories