I have a Java code that will output 3 column of double integer just like this (1 column, 2 column, 3 column):
( 0.09, 0.27, 0.01)
( 0.00, -0.00, 0.26)
( 0.02, -0.02, 0.24)
( 0.22, -0.11, -0.03)
Now, I wish to store all the values from the second column into an array and the values from the third column into another array. Is there a way I could modify it so that it will achieve that?
This is my partial code:
for (int i = 0; i < termVectors.length; ++i) {
System.out.print("(");
for (int k = 0; k < 3; ++k) {
if (k > 0) System.out.print(", ");
System.out.printf("% 5.2f",termVectors[i][k]);
}
System.out.print(") ");
}
Thanks!
Please try the following code.
int[] secondColVal = new int[termVectors.length];
int[] thirdColVal = new int[termVectors.length];
for (int i = 0; i < termVectors.length; ++i) {
System.out.print("(");
for (int k = 0; k < 3; ++k) {
if (k > 0) System.out.print(", ");
System.out.printf("% 5.2f",termVectors[i][k]);
if(k==1)
secondColVal[i] = termVectors[i][k];
if(k==2)
thirdColVal[i] = termVectors[i][k];
}
System.out.print(") ");
}
This should give you what you need :)
// since you're using the length multiple times, store it in a variable!
int len = termVectors.length;
// declare two arrays to represent your second and third columns
int[] secondColumn = new int[len];
int[] thirdColumn = new int[len];
for (int i=0;i<len;i++)
{
// populate your arrays
secondColumn[i] = termVectors[i][1];
thirdColumn[i] = termVectors[i][2];
}
Related
I'm a beginner at java at struggling with this:
I am trying to sum two jagged arrays ( n and m, both double [][]) of the same size (each is length 3 at the first level, then of length x-1,x and x-1 respectively at the second level).
The problem I'm having is to specify the length that each array within the jagged array should be, at the moment my code is producing an n x n array because I've specified the length as n[1] rather than as a parameter, but if I try and use sum[i].length=n[i].length I get the error, "cannot assign value to final variable". So I know this part is wrong but I don't know what is right...
Thanks for the help!
My code:
else if (isValidTridiagonal(m)== true && isValidTridiagonal (n) == true)
{
int size = n[1].length; /** specifying all lengths to be x where they shouldnt be*/
sum = new double[3][size];
for (int i = 0; i < n.length; i++)
{
for(int j = 0; j< n[i].length; j++)
{
sum [i][j]= n[i][j] + m [i][j];
}
}
return sum;
}
There is some missing information. As far as I can tell there are two things you need to fix. You seem to have "sum" as a final variable already defined in your code.
Secondly, you are declaring a new array that is 3xsize big. If you want a jagged array in that sence, you must leave one of the brackets empty and in the first loop insert a new array of the wanted size.
double[][] sum = new double[3][]; //Make sure this is unique within the scope
for(int i = 0; i < 3; i++) { //if you want dynamic scaling you'll need to replace 3 in the array as well.
int size = n[i].length; //size of the new row
sum[i] = new double[size]; // Inserting a new array of the wanted size
for(int j = 0; j< sum[i].length; j++)
{
sum[i][j]= n[i][j] + m[i][j];
}
}
return sum;
The problem is probably with this line:
sum = new double[3][size];
Here you create an incorrect, non-jagged array of size [3][2]
When you try to set sum[1][2] (2nd, 3rd index), you will not be able to.
Otherwise, the code looks correct and I got a sum to work using this:
public static void main(String[] args) {
int[][] n = new int[3][];
n[0] = new int[2];
n[0][0] = 1;
n[1] = new int[3];
n[2] = new int[2];
int[][] m = new int[3][];
m[0] = new int[2];
m[1] = new int[3];
m[1][2] = 1;
m[2] = new int[2];
int[][] sum = new int[3][];
sum[0] = new int[2];
sum[1] = new int[3];
sum[2] = new int[2];
for (int i = 0; i < n.length; i++) { // n.length will be 3
for (int j = 0; j < n[i].length; j++) { // n[i].length will be 2, 3 and 2
sum[i][j] = n[i][j] + m[i][j];
}
}
System.out.println("Sum: ");
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < sum[i].length; j++) {
System.out.print(sum[i][j] + "|");
}
System.out.println();
}
}
This will print off:
Sum:
1|0|
0|0|1|
0|0|
private void enterbtnActionPerformed(java.awt.event.ActionEvent evt) {
int [][] array = new int [4][4]; // my array
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j]= ;// use for feeding the code
}
popfield.setText(Arrays.deepToString( array ) );
}
I want to insert integers into 2d array via 2 textfields one for columns and one for rows elements via two text fields xfield and yfield
So.. For create 2D int array:
//int 2 dimensional array
int[][] array = null;
//your fields values
final int xFieldVal = 5;
final int yFieldVal = 7;
//values to fill into array
final int minArrayVal = 50;
final int maxArrayVal = 100;
//create matrix / grid with dimensions (xFieldVal x yFieldVal)
array = new int[xFieldVal][yFieldVal];
(that creates recangle xFieldVal x yFieldVal- or Y*X..)
While you have rectangle array you can acces to all value for filling eg. like that:
//random generator
Random rnd = new Random();
for (int i = 0; i < xFieldVal; i++) {
for (int j = 0; j < yFieldVal; j++) {
//generate new int in interval
array[i][j] = minArrayVal + rnd.nextInt(maxArrayVal- minArrayVal+ 1);
}
}
While you will dont have rectangle array (you can have eg. just 1st dimension fixed, and 2nd not- I mean each "row" can have difference "columns" count), you have to use that loop:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
//printing next line
System.out.println();
}
Eg. to find min and max value, you can use that:
//set on the max possible (every value should be less than that)
int min=Integer.MAX_VALUE;
//set on the min possible (every value should be more than that)
int max=Integer.MIN_VALUE;
//iteration through 1st index (eg. iteration through rows)
for (int i = 0; i < array.length; i++) {
//iteration through 2nd index of 1st index (eg. through all columns)
for (int j = 0; j < array[i].length; j++) {
//compare and assign if array value is less than actual found min
if(min > array[i][j]){
min = array[i][j];
}
//compare and assign if array value is more than actual found max
if(max < array[i][j]){
max = array[i][j];
}
}
}
I dont think you understand what a 2D array is
think of it as a grid. you insert into a single cell at a time.
a single cell belongs to a row and a column hence has a row number and column number...like an excel work book? cell b5?
so if you want to input numbers all you gotta do is have a single textfield lets call it txt
the rest is as follows
private void enterbtnActionPerformed(java.awt.event.ActionEvent evt)
{
int [][] array = new int [4][4]; // my array
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j]= Integer.parseInt(txt.getText());// use for feeding the code
}
popfield.setText(Arrays.deepToString( array ) );
}
I'm trying to return the mode of a 2D array using a frequency array. I have an array, score, which is of length 10, and has 3 columns. Each column contains an int that is between 0 and 100.
I'm trying to find a way that will iterate through the array and return the modal value. What I have so far is:
int value = 0;
int[] freq = new int[100];
for (int row = 0; row < score.length; row++) {
for (int col = 0; col < score[row].length; col++) {
score[row][col] = value;
freq[value]++;
}
}
int largest = 0;
int mode = -1;
for (int i = 0; i < 100; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);
Problem is that this is just returning the modal score as 0, which it isn't.
You have a problem on generating the freq array. If I understand correctly, on the first double-for block you are trying to put the frequencies of the numbers inside the freq array.
But all you do is:
int value = 0;
.....
score[row][col] = value;
freq[value]++;`
firstly you are changing the score array,( which is a problem for you I guess...) and the you go to freq[0] and do ++. Obviously modal is 0, that number appears in all of the array.
SOLUTION: in the first double for block you should do:
value = score[row][col];
freq[value]++;
so I think you mixed up the order of the line, it should be the other way around.
private static void printMode(double[][] doubles) {
HashMap<Double , Double> map = new HashMap();
for (int i = 0; i < doubles.length; i++) {
for (int j = 0; j < doubles[i].length; j++) {
double temp = doubles[i][j];
if(map.get(temp)==null){
map.put(doubles[i][j],1.0);
}else {
double temp2 = (double) map.get(temp);
map.put(doubles[i][j],++temp2);
}
}
}
Object[] objects = map.values().stream().sorted().toArray();
Stream stream = map.entrySet().stream().filter(val-> val.getValue().equals(objects[objects.length-1]));
stream.forEach(System.out::println);
}
I think using Stream for finding mode is the best way.
use int instead of double doesn't cause any problems.
int value = 0;
int [] freq = new int [arr.length];
for (int i = 0; i < arr.length; i++){
for (int j = 0; j < arr[i].length; j++){
value = arr[i][j];
freq[value]++;
}
}
int largest = 0;
int mode = 0;
for (int i = 0; i < freq.length; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);
I'm doing the old Lotto exercise and I need to specifically use an Array[] of integers and not an ArrayList. I have what I thought would work, but I seem to be wrong. I looked for posts similar to these and all of them involved an ArrayList<>. Here is a partition of my code.
Integer[] lottoNums;
lottoNums = new Integer[7];
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
if(i <= 5) {
if(lottoNums[i].equals(lottoNums[i+1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
else if(i >= 1) {
if(lottoNums[i].equals(lottoNums[i-1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
I need to get it to generate a number in between 1 and 59 and not duplicate. I was trying to pair it up with the value stored in the element before and after it (if it had one) and if it was equal to it, it would add 1 to it. I run it a few times and every once in a while im still getting duplicate numbers. How can i do this efficiently, using Arrays[] of integers ONLY?
EDIT:
Initialized array to remove NullPointerException.
Updated Code:
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
}
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt((lottoNums).length-i);
int k = lottoNums[lottoNums.length-i-1];
lottoNums[lottoNums.length-i-1] = lottoNums[rnd];
lottoNums[rnd] = k;
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
//PRINTING LOTTO NUMBERS
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
You can do this by switching the selected number with the last number in the array each time, and then selecting the next from the prefix you have not yet stored:
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt(numbers.length-i);
int k = numbers[numbers.length-i-1];
numbers[numbers.length-i-1] = numbers[rnd];
numbers[rnd] = k;
}
At the end of this loop your selected numbers will be in numbers[numbers.length-7..numbers.length-1], etc.
I would use two arrays. Each time you draw a number see if it exists in the second array. If not use it and add it to the second array.
I have to write a program using a method that returns the location of the largest element in a two dimensional array.
example
Enter the number of rows and columns of the array:
3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
the location of the largest element is at (1, 2)
I have finished my code but it isn't working. How can I fix it? All I got are the following errors:
symbol : variable maxvalue
location: class int[]
if (a[i][j] > largest.maxvalue)
^
homework1a.java:51: row is already defined in locateLargest(double[][])
double row = i;
^
homework1a.java:52: column is already defined in locateLargest(double[][])
double column = j;
^
homework1a.java:53: maxValue is already defined in locateLargest(double[][])
double maxValue = a[i][j];
^
homework1a.java:88: i is already defined in main(java.lang.String[])
for (int i = 0; i < 2; i++)
^
5 errors
My code
import java.util.Scanner;
public class hwm1 {
public static int[] locateLargest(double[][] a)
{
int[] largest = new int[2];
double row = 0;
double column = 0;
double maxValue = a[0][0];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)
{
double row = i;
double column = j;
double maxValue = a[i][j];
}
}
}
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");
int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();
//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
int[] largest = locateLargest(a);
System.out.println("The location of the largest element is at "+ "("+largest[0] +", " + largest[1] + ")");
for (int i = 0; i < 2; i++)
{
System.out.print(largest[i]);
}
}
}
}
You are declaring the variables row, column and maxValue twice.
Also, in the line:
if (a[i][j] > largest.maxvalue)
There is no such thing as maxvalue in your code, and neither is it a member of largest
In this part of your code:
Since i is already declared in the outer for-loop, you don't need to declare it again. Just use:
...
for(i = 0; i < 2; i++){
...
}
homework1a.java:51:, homework1a.java:52:, homework1a.java:53:
For these three, remove 'double'. If you state the type when referencing the variable, Java will assume you are trying to define the variable in question. Here you already have those three defined. Additionally, since you don't use row or column at all, I suggest that you simply remove them.
homework1a.java:88: i is already defined in main(java.lang.String[])
For this one, you have a nested for loop, but it uses i as well. You should use k for the second of the nested for loops (the one after the one using j).
. You don't need to post full code below code snippet is sufficient
double row = 0; //declaring first time
double column = 0;//declaring first time
double maxValue = a[0][0];//declaring first time
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)// there is no variable maxvalue in Array class in java
{
double row = i; // declaring again
double column = j;// declaring again
double maxValue = a[i][j];// declaring again
}
}
}
return largest;
Issues:
Loop on j should be using a[i].length
the lines in if block is re-declaring the variables, remove the keyword 'double '
You are not declaring setting largest anywhere so you have a logic issue
Using a largest.maxValue is logically incorrect as it should contain the row and column number and not the actual max value
I would solve this by re-writing the code as follows which I believe is the most efficient way of achieving the goal:
public static int[] locateLargest(double[][] a)
{
int maxRow=-1,maxCol=-1;
double maxVal=-1;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if (a[i][j] > maxVal)
{
maxRow = i;
maxCol = j;
maxVal = a[i][j];
}
}
}
return new int[]{maxRow,maxCol};
}
Good luck!