How to change 2d array by input? - java

I have a 2D array of 5 rows and 5 columns, all filled with the value 0. How can I make my program do this:
Enter any random combination of row and column like 2-5, without the [] brackets. Just typing 2-5 should be enough to make my program understand I mean row 2 column 5
Assign value I enter to said array in row-column combination.
This is what I got so far. As you can see I have only managed to output the values of all array elements.
import java.util.*;
public class stink {
public static void main(String[]args){
int[][] kuk = new int[5][5];
printMatrix(kuk);
}
public static void printMatrix(int[][] matrix)
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[row].length; col++)
System.out.printf("%2d", matrix[row][col]);
System.out.println();
}
}
}

you should use Scanner class from java API to get the inputs from the user like in the below code.
pass the inputs with a delimiter like if you want to have 2X3 array pass like 2-3 where '-' is a delimiter.
here are the links for String the and scanner java API.
Scanner sc = new Scanner(System.in);
System.out.println("please enter two numbers");
String inputs = sc.next();
int a=Integer.valueOf(inputs.split("-")[0]);
int b=Integer.valueOf(inputs.split("-")[1]);;
System.out.println(a + " " + b);
int[][] x = new int[a][b];
System.out.println(x.length);

this is not a copy/paste ready answer, but it should at least give you an indication on how you could handle this.
int rows = 0;
int columns = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Rows: ");
rows = scan.nextInt();
System.out.println("Columns: ");
columns = scan.nextInt();
int[][] kuk = new int[rows][columns];

import java.util.*;
public class stink
{
public static void main(String[]args)
{
int[][] kuk = new int[5][5];
// Where x and y are keys, integer is the integer you want to push
pushIntoMatrix(kuk, x, y, integer);
//kuk = pushIntoMatrix(kuk, x, y, integer); // Use if you want the method to return a value.
}
public static void pushIntoMatrix(int[][] matrix, int x, int y, int integer)
//public static int[][] pushIntoMatrix(int[][] matrix, int x, int y, int integer) // Use if you want to return the array.
{
matrix[x][y] = integer;
//return matrix; // Use if you want to return the array.
}
}
Since as you know, any data type in Java that's not a primitive is a reference, passing the kuk array into the method would affect the actual array reference. You can set a return in pushIntoMatrix() if you want, but you don't have to.

Related

I need to find the value in a two dimensional array using the x and y cordinates

This is the grid I'm using in my code and I need to find the value which is in the coordinates when I give the x and y coordinates from the Scanner.
int [][] grid = {
{1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,1,0,1,0,0,0,0,0,1},
{1,0,1,0,0,0,1,0,1,1,1,0,1},
{1,0,0,0,1,1,1,0,0,0,0,0,1},
{1,0,1,0,1,1,1,0,1,0,1,0,1},
{1,0,0,0,0,0,0,0,0,0,1,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1}
};
It seems very easy or you didn't show all your task:
It will be:
int targetValue = grid[x][y]
You need to use grid[y][x].
public void test(String args[]) {
int [][] grid = {
{1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,1,0,1,0,0,0,0,0,1},
{1,0,1,0,0,0,1,0,1,1,1,0,1},
{1,0,0,0,1,1,1,0,0,0,0,0,1},
{1,0,1,0,1,1,1,0,1,0,1,0,1},
{1,0,0,0,0,0,0,0,0,0,1,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1}
};
System.out.println(getValueAt(grid,4,2));
}
private int getValueAt(int[][] grid, int x, int y) {
return grid[y][x];
}
Sometimes it is the other way around but that is up to you.
The most simple way to do this is via: int userValue = grid[x][y];
x value indicates the row you're looking for and y value indicates the column.
In your case with using scanner, the code should look something like this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter x value: ");
int x = sc.nextInt();
System.out.println("Enter y value: ");
int y = sc.nextInt();
System.out.println(grid[x][y]);

How to use previous parameter from array in for loop

I have been try to code this, to increment the user input by 33 if the input is "31" or more up to the input or "90", and I have hit a wall where I want to use the user input from the array but I cannot. Could anyone help? Thank you.
if (choice.equals("R")) {
System.out.println("You have selected to draw a Rectangle!");
System.out.println("Please enter the Height and Width of the rectangle that is within 30cm - 90cm: ");
int[] array = new int[2];
int[] array2 = new int[2];
Scanner scan = new Scanner(System.in);
String line1 = scan.nextLine();
String[] numbers1 = line1.split(" ");
for(int i=0;i<numbers1.length;i++){
array[i] = Integer.parseInt(numbers1[i]);
}
I am trying to make a method to be able to easily call upon it later on, but that's the problem as I cannot complete my calculation.
public static void timeTurn (int a, int b) {
for(int i = 1000; i < 3001; i+= 33) {
if(numbers1.equals(>=30)) {
}
}
}
int[] array2 = new int[2]; is useless here.
By the way, please do not name a variable "array" or "array2". It's hard to understand for others and for yourself in the future.
if you defined the "array"s length to 2, then this for loop for(int i=0;i<numbers1.length;i++){...} is meaningless cause you already defined that you can only have two integers in this array.
I do not know the meaning of "convert cm to milliseconds" since one is distance and the other is time...
I can not understand (int a, int b) what "a", "b" means.
by my understanding the second code should be:
public static void timeTurn (int[] length) {
int minMillsecond = 1000;
int maxMillsecond = 3001;
int gap = 33;
for(int len : length){
if (30 <= len <= 90){
len += minMillsecond;
while(len < 3000){ len+=gap;}
print len;
}
}
}

simple Java 2D Array with input

I'm new to Java and got some work at school.
Now I don't know how to continue and I hope you can help me.
That's my code till now
package bp;
import java.util.Scanner;
public class BenzinP {
private int row = 4;
private int col = 4;
private int[][] matrix;
public BenzinP(int trow, int tcol) {
this.row = trow;
this.col = tcol;
}
public BenzinP(int trow, int tcol, int[][] m) {
this.row = trow;
this.col = tcol;
this.matrix = m;
}
public int[][] fill(){
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in);
for(int row = 0; row< matrix.length; row++){
for(int col = 0 ;col< matrix.length; col++){
System.out.println("Date");
data[row][0] = in.nextInt();
System.out.println("Price");
data[row][1] = in.nextInt();
}
System.out.println();
}
for(int row = 0; row< matrix.length; row++){
for(int col = 0 ;col< matrix[row].length; col++){
System.out.print(data[row][col]);
}
System.out.println();
}
return data;
}
public static void main(String[] args){
int[][] ma = new int[3][2];
BenzinP q2 = new BenzinP(3, 2,ma);
q2.fill();
}
}
The task is:
Create a Java program which can save the prices for gas for different days and can be outputted in different formats (sort for highes price or date).
You should use a 2D Array which can safe data for at least 30 days.
Also it should show the average, min. and max price.
Also the program should be outsourced in methodes etc.
I hope you can help and keep it simple.
I will make some assumptions in order to be able to answer this:
if BenzinP is a class, that should not contain the main method. Only the main class in your project should contain the main, since that is what the JVM expects to be the "point of entry" in your code.
public static void main(String[] args)
Since this is an exercise, dont worry so far about this.
Then, the BenzinP class has 2 constructors that are not really needed.
I suggest the following:
BenzinP(){
this.matrix=new int[this.row][this.col];
}
Create the rest of the methods you want, such as query the highest value, lowest, etc.. and start your main
public static void main(String[] args){
BenzinP q2 = new BenzinP();
q2.fill();
q2.getHighest();
// q2.getLowest();
// q2.getEtc();
}
As a suggestion, in order to search the highest and lowest value, iterate your array and compare that value with an initialized one, if its bigger/smaller, update the value, at the end of the array, return the initialized value:
public int getHighest(){
int max = -2147483648; // the lowest possible integer.
for(int i=0 i<this.row;i++){
if(matrix[i][1]>max){
max = matrix[i][1];
}
}
return max;
}

arrays and static methods java

I have a question on how to call an array static method. In my case, I believe that my array static method is fine because the compiler does not complain about it, but it does when I call it, it says double cannot be converted to double[] How can I fix this? Any help will be greatly appreciated. Below is a snippet of my code:
// create allowed x values for calculation static method
public static double[] allowedValuesX(double[] x, double[] y, int choice){
double allowedVx[] = new double[choice];
int i = 0;
for(i = 0; i < allowedVx.length; i++){
if((Math.pow(x[i], 2) + (Math.pow(y[i], 2))) <= 1){
allowedVx[i] = x[i];
}
}
return allowedVx;
}
// main method
public static void main(String args[]){
// create Scanner object
Scanner in = new Scanner(System.in);
// call to promptUser
promptUser();
// create variable for recieving user input
int choice = in.nextInt();
double x[] = new double[choice];
int i = 0;
for(i = 0; i < x.length; i++){
x[i] = Math.random();
}
// call to allowed x values
allowedValuesX(x[i], y[j], choice);
You are passing specific array elements when calling allowedValuesX:
allowedValuesX(x[i], y[j], choice);
But you should pass the arrays themselves, to match the parameter types of the method:
allowedValuesX(x, y, choice);

Dynamic variables

I'm tring to assign variables dynamically, but I don't have a clue how to do that.
What my program should do:
"Write a program to have the user enter three lengths of sides and determine whether the figure is a triangle or not."
This is what I have so far:
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
double z;
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z = Double.parseDouble(x.substring((y + 1), i));
y = i;
a += z;
}
}
}
}
What I would love to do would be to have this in the if statement:
int a++;
z(a) = Double.parseDouble(x.substring((y + 1), i));
But as I have found out this will not work and I need some kind of array. Sadly, my online class has not started arrays yet and I haven't gotten a grasp of them yet in my own learning.
I would like to make 3 variables (z1, z2, z3) and assign an integer to each one within the if statement.
Edit:
Here's some revised code that now works how I wanted now. Hope this helps someone else in the future!
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
Double[] z = new Double[3];
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z[a] = Double.parseDouble(x.substring((y + 1), i));
y = i;
a++;
}
}
//Some test code to see if it was working
System.out.println(z[0]);
System.out.println(z[1]);
System.out.println(z[2]);
}
}
You don't need to use arrays, especially that you haven't been introduced to them. You can simply use a Scanner class, and do something similar to
Scanner in = new Scanner(System.in); // this will read from the standard system input
System.out.println("Please enter three lengths of sides: ");
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
And write some logic (I guess that's the point of your homework) checking if this figure is a triangle.
In case you would like to use arrays , you could declare one by doing:
int[] sidesLenghtsArray = new int[3];
And then instead of refering to three different int variables, you could simply refer to your array elements:
int[0] = in.nextInt();
int[1] = in.nextInt();
int[2] = in.nextInt();
Just remember - the number in the brackets is the number of elements that your array will have, but refering to that elements, you start counting from 0. That's why we start with int[0] (1st element) and end with int[2] (3rd element).
Java does not support tuple assignment like
def (a,b,c) = "1,2,3".split(",")
It is possible to do this in Java 8 with a following code:
int[] abc = Arrays.stream("1,2,3".split(",")).mapToInt(Integer::parseInt).toArray();
Here, a would be abc[0], b is abc[1].
Similar code in Java 7 could be this:
String[] abc = "1,2,3".split(",");
int a = Integer.parseInt(a[0]);
int b = Integer.parseInt(a[1]);
int c = Integer.parseInt(a[2]);
The very basic idea is that in every triangle when you add the lengths of two sides, the resulting length should be greater than the length of the remaining sides. Let's say a, b, c are the sides of the triangle.
public static void main(String[] args){
int a=3, b=4, c=5;
if(a+b > c && a+c>b && c+b>a){
System.out.println("This is a valid trianlge");
}
else{
System.out.println("This is not a valid triangle");
}
}
make sure you replace the values of a,b, and c with the values you gain from user input.

Categories