So im new to Stack Overflow and hope I am saying this question correctly.
I was given this assignment from class and was done with it until my professor tweak the assignment a little bit. In summary i made 2 classes the would work with each other and call off the variable from the other class into the class it was being called to. Now my professor want 1 java file which mean one class file. I do not know how to rewrite the program with both code into one class.
Assignment:
"(The Location class) Design a class named Location for locating a maximal value and its location in a two-dimensional array. The class contains public data fields row, column, and maxValue that store the maximal value and its indices in a two-dimensional array with row and column as int types and maxValue as double type.
Write the following method that returns the location of the largest element in a two-dimensional array:
public static Location locateLargest(double[][] a)
The return value is an instance of Location. Write a test program that prompts the user to enter two-dimensional array and displays the location of the largest element in the array. Here is sample run:
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 45 at (1, 2)
SO i did all that with the 1st class coding:
public class Location {
int row; //blue variable = class variable
int column;
double maxValue;
}
Then here the code that call in the program in the second class
import java.util .*;
public class TestLocation {
public static void main(String[] args)
{
Location mylocation;
int row;
int column;
double [][] numArray; //we can leave this blank
Scanner Reading = new Scanner(System.in);
System.out.println(" How many rows will you be entering?");
row = Reading.nextInt(); //nextInt -what it reads will convert into a integer
System.out.println(" How many columns will you be entering?");
column = Reading.nextInt();
numArray = new double [row][column];
System.out.println("Enter the array please");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
numArray[i][j] = Reading.nextDouble();
//i is the row and j is the column
}
}
mylocation = locateLargest(numArray);
int temp = (int)mylocation.maxValue; //this is to print out the difference between int and double(decimal)
if (temp == mylocation.maxValue)
System.out.println("Highest Number: " +(int)mylocation.maxValue); //(int forces to be an integer then the double it was, eliminate decimal places)
else
System.out.println("Highest Number: " +mylocation.maxValue); //print out with decimal
System.out.println("Position: (" + mylocation.row+", " + mylocation.column +")");
Reading.close();
}
public static Location locateLargest(double[][] a)
{
Location mylocation = new Location(); //this is where we are going to store my information in
mylocation.maxValue = a[0][0]; //this is the max value to the first number
mylocation.row = 0;
mylocation.column = 0;
for (int i = 0; i < a.length; i++) //Length of the row; how many row there are
{
for (int j = 0; j < a[0].length; j++) //Length of a row; how many column in that row
//we added array here in the second because we want of get the length of the second dimension
//.length get the length of the current dimension , so a.length get the length of the first dimension
{
if (mylocation.maxValue < a[i][j] )
{
mylocation.maxValue = a[i][j];
mylocation.row = i;
mylocation.column = j;
}
}
}
return mylocation;
}
}
how can i reprogram this with the new instruction that was in the assignment box above that require me to but all the coding into one class = 1 java file? I tried almost everything And could not get the results i want.
One java file only allows one public class file. Remove public keyword from the first java file, and put them into the same file as the second one will work.
class Location {
int row; //blue variable = class variable
int column;
double maxValue;
}
Related
Okay, so I need to print 10 rows from 1 to 10 and 15 columns in every row from 1 to 15 with lines in between numbers. The second subroutine runs on its own, but only prints 0's and the first subroutine is me trying to give value to rows and columns, but I know I'm doing it very wrong. Any help is appreciated
static int ROWS = 10;
static int COLUMNS = 15;
static int[][] myArray = new int[10][15];
static int i; // loops through the number of rows
static int j; // loops through the number of columns
static int num1 = 0;
static int num2 = 0;
public static void vlueArray() {
for (i = 1; i < ROWS; i++) {
myArray[i][j]= num1++;
for (j = 1; j < COLUMNS; j++) {
myArray[i][j] = num2++;
System.out.print(myArray[i][j]);
}
System.out.println("");
}
}
public static void display2DArray() {
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLUMNS; j++) {
System.out.print(myArray[i][j] + " | ");
}
System.out.println("");
System.out.println("_____________________________________________________________");
}
}
you have not initialized elements in array and that is why you are getting zero displayed because int values are always initialized by the compiler even if you don't initialize them. The default value of int is 0.
Initialize your 2D array like this:
int[][] myArray = new int[10][15]{{2,3},{3,5},..........};
Hope this helps.
There are two issues here. First, you don't have very good syntax, while the way you have this set up does work, let me give you a couple of tips about settings this up, and then we can fix your problem fairly easily.
Some general rules here:
You don't have to initialize loop variables in the class variables, just initialize them in the loop structure (I'll show you this below).
Use the ROW and COLUMN in declaring your array, it helps make sure the array length values are the same throughout.
Your loop for creating the values in vlueArray is incorrect. I'll show you some correct formatting for placing these values below.
When you array is initialized, each place in the array (if it is an integer array) is automatically given a value of zero. You can change this, but since the first method doesn't run correctly, printing the values in the array without changing them will give the array of zeros.
Now, it seems like you want to just have 1 - 15 on 10 different rows. To do this, you only need one variable, so my response code will only have one variable, but if this isn't what you want, I'd be glad to help you get a different setup.
So now that you have a little bit of background information, let's get you some working code.
static int ROWS = 10; //Your row count.
static int COLUMNS = 15; //Your column count.
static int num = 0; //Our number.
//Using the constants to make sure rows and columns values match everywhere.
static int[][] myArray = new int[ROWS][COLUMNS];
public static void fillArray() {
//Initializing the loop variables in the loop is the common practice.
//Also, since the first index is zero, the loop needs to start at 0, not 1.
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
//If you want 0 - 14, use `num++`.
//If you want 1-15, use `++num`.
myArray[i][j] = num++;
}
num = 0; //This sets num back to zero after cycling through a whole row.
}
//Your display method works just fine.
public static void display2DArray() {
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLUMNS; j++) {
System.out.print(myArray[i][j] + " | ");
}
System.out.println("");
System.out.println("_____________________________________________________________");
}
Okay so I'm still working on a matrix project for my APCS class, and I am currently trying to figure out how to get the user to input all the numbers for the matrix. Right now I have a setNums class that uses the Rows and Columns already inputted to throw up a bunch of inputboxes and then inputs those numbers into a 2 dimensional array like so:
public void setNums(String Matrixnum){
for (int i = 1; i <= myRows; i++){
for(int j = 1; j <= myColumns; j++){
String StrNum = JOptionPane.showInputDialog(null, Matrixnum + " Row " + i + " Column " + j + " enter number:");
myNums[i][j] = Double.parseDouble(StrNum);
}
}
}
I then have a getNums class that should go through the array and return them one by one, when I need the numbers later on for adding, subtracting, and multiplying the matrices:
public double[][] getNums(){
for(int i = 1; i <= myRows; i++) {
for(int j = 1; j <= myColumns; j++) {
return myNums[i][j];
}
}
}
The issue is that when I try to return myNums, it says "cannot convert from double to double[][]" I don't understand why the code thinks it's a double and not a double[][]. I initialized it correctly:
private double[][] myNums;
...and I made sure my parsedouble was outputting to the array, which was the issue in a similar thread I found. This is my first time working with 2 dimensional arrays, so I bet there's something simple here that I don't understand. Any help is greatly appreciated. Thanks!
The compiler returns this error Cannot convert double into double[][]
because your are actually returning single double number instead of your double array double[][] that you defined as return type of your method getNums()
Instead you can fix the problem by returning only myNums array:
public double[][] getNums(){
return myNums;
}
Also you can declare another method if you want to get any specific number from your array by using array indexes i and j:
public double getNumber(int i, int j){
return myNums[i][j];
}
I'm beginner programmer, I have fallen into a rabbit hole trying to understand how to use arrays. I'm trying to create a table using multidimensional arrays and I am looking to create a table with 7 rows and 5 columns.
column 1 = will take values from the user input.This input is stored in an array.
column 2 = will print the highest input in that array.
column 3 = will print the lowest input in that array
column 4 = will print take the increment Total. i.e current input + previous input.
column 5 = will take the increment average. i.e Total/Index
Complete Code below
import java.util.Scanner;
public class Numbers {
public static void main(String[] args)
{
//----User Input - Add values to array ----//
Scanner keyboard = new Scanner(System.in);
int places = 7;
int [] values = new int [places];
int sum = 0;
System.out.println("Enter a Numbers:");
for (int count = 0; count < places; count++)
{
values[count] = keyboard.nextInt();
System.out.println(values[count]);
}
//----------------Total---------------------//
for (int numb : values)
{
sum = sum + numb;
}
System.out.println("\n Total:" + sum);
//----------Average------------------------/
double avg = 0;
if (values.length > 0)
{
avg = sum / values.length;
}
System.out.printf("\n Average:"+ avg);
//---------Table Start---------------------//
int [] [] table = new int [7][5];
for (int row =0; row < 7; row++)
for (int column = 0; column < 5; column++)
table [row][column] = getTable(column, column, column, column, avg);
System.out.println("\n\nIndex\tInput\tHigest\tLowest\tTotal\tAverage");
for (int row = 0; row < 7; row++)
{
System.out.print((row + 1) + " ");
for (int column = 0; column < 5; column++)
System.out.print("\t " + table[row][column] + " ");
System.out.println();
}
}
public static int getTable(int input, int highest, int lowest, int total, double average) {
/* TO DO:
* - add each user input from values array into Input column
*
* - add highest/lowest values in the Highest/Lowest column
*
* - add each of the array element total in Total column - this column should take previous Total plus current total.
* i.e Total = Total + Input
*
* - add Average - Current average value.
*/
return 0;
}
}
What I don't know is how to get my code to fill each of the rows using different values each time.
For Example:
Index 1
1st column take first value of the values array
2nd column: take highest value of the values array
3rd column: take lowest value of the values array
4th column: take previous element of values array plus the current value
5th column: take total/index
I know that may need to create a method to get my program to loop through but I just don't know how to do it. I've tried a few different ways, but I'm just getting confused. In the left corner of the screenshot below, is how the columns would look like. Notice how they are all returning 0, which I known that is coming from the getTable method that I created, which is doing just that.
Basically, in this code, you're looping over all the columns:
for (int row =0; row < 7; row++)
for (int column = 0; column < 5; column++)
table [row][column] = getTable(column, column, column, column, avg);
You don't want to do this. Looping over all the columns would make sense if you were doing pretty much the same thing with each column. But you're not. You want each column to have the result of a very different computation. So it would make more sense to say something like
for (int row = 0; row < table.length; row++) {
table[row][0] = getFirstValue(values);
table[row][1] = getHighestValue(values);
table[row][2] = getLowestValue(values);
...
and so on. (However, I don't really understand how "values" is supposed to be used. You're inputting one set of values, but you're creating a table with 7 rows based on that one set of values. Perhaps there's more things wrong with your code.)
Note a couple of things: (1) I replaced 7 with table.length in the loop. table.length is the number of rows, and will be 7. But if you change things to use a different number of rows, then using table.length means you don't have to change the for loop. (2) My code passes values as a parameter to the different methods, which is necessary because the methods will be making computations on the input values. Your code didn't pass values to getTable(), so there's no way getTable() could have performed any computations, since it didn't have the data.
The code could be improved further. One way would be to define constants in the class like
private static final int FIRST_VALUE_COLUMN = 0;
private static final int HIGHEST_VALUE_COLUMN = 1;
...
table[row][FIRST_VALUE_COLUMN] = getFirstValue(values);
table[row][HIGHEST_VALUE_COLUMN] = getHighestValue(values);
which would be more readable.
A more significant improvement would be not to use a 2-D array at all. Since you have five values with different meanings, the normal approach in Java would be to create a class with five instance variables to hold the computed data:
public class ComputedData {
private int firstValue;
private int highestValue;
private int lowestValue;
public void setFirstValue(int firstValue) {
this.firstValue = firstValue;
}
public int getFirstValue() {
return firstValue;
}
// similarly for other fields
}
table would then be a 1-dimensional array of ComputedData.
This is better because now you don't have to assign meaningless column numbers to different computed values. Instead, the names tell you just what each computed value is. Also, it means you can add new values later that don't have to be int. With an array, all elements in the array have to be the same type (you can use Object which can then hold a value of any type, but that can make the code messier). In fact, you may decide later that the "average" should be a double instead of an int since averages of integers aren't always integers. You can make this change pretty easily by changing the type of an instance variable in the ComputedData class. If you use an array, though, this kind of change gets pretty complicated.
I'm not sure how to return an instance of an object from a method with values. Is there some way to convert an int type into my object type?
Here is some instructions I have:
/* Design a class named Location for locating a maximal value and its location in a
two-dimensional array. The class contains:
-Public double type data field maxValue that stores the maximal value in a two-dimensional
array
-Public int type data fields row and column that store the maxValue indices in a
two-dimensional array
Write a the following method that returns the location of the largest element in a two
dimensional array:
public static Location locateLargest(double[][] a)
The return value is an instance of Location. Write a test program that prompts the user to
enter a two-dimensional array and displays the location of the largest element in the
array. Here is a sample run:
Enter the number of rows and columns in 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 45 at (1, 2) */
And here is my code:
class Location {
public static double maxValue;
public static int row;
public static int column;
public static Location locateLargest(double[][] a) {
maxValue = a[0][0];
row = 0;
column = 0;
Location result = new Location();
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
if(a[i][j] > maxValue) {
maxValue = a[i][j];
row = i;
column = j;
if((i == a.length-1) && (j == a[i].length-1))
//Place indices of maxValue in result variable
}
else
continue;
}
}
return result;
}
}
I'm thinking I should just create a constructor for Location that takes arguments, but I'm reluctant because the instructions didn't say to do so. Is there any other way to do this? Thanks
Your mistake is, you are using static fields for an Object:
public static double maxValue;
public static int row;
public static int column;
Each time you call
public static Location locateLargest(double[][] a)
You think that you are creating a new Location object with different maxValue, row and column but because these fields are static you are just overriding class variables.
Just remove static modifier.
I am trying to write a polling program that takes five issues and puts the issue on the row of a 2d Array. Also how would I make the program count how many times a person rated the issue. For example if five people gave rating of five how would I write the program to count the rating and put it on the 2d Array.
These are the instructions:
Write a simple polling program that:
Allows users to rate five social-consciousness issues from 1 (least important) to 10 (most important);
Pick five causes that are important to you (e.g., political issues, global environmental issues). Use a one-
dimensional array topics (of type String) to store the five causes;
To summarize the survey responses, use a 5-row, 10-column two-dimensional array responses (of type int):
Each row corresponding to an element in the topics array.
When the program runs, it should ask the user to rate each issue. People in the range of (5, 13) have respond to the survey. Then have the program display a summary of the results, including:
a) A tabular report with the five topics down the left side and the 10 ratings across the top, listing in each column the number of ratings received for each topic.
b) To the right of each row, show the average of the ratings for that issue.
c) Which issue received the highest point total? Display both the issue and the point total. d) Which issue received the lowest point total? Display both the issue and the point total.
This is my code:
import java.util.Arrays;
import java.util.*;
public class Polling {
/**
* #param args the command line arguments
*/
public static String[] issues=new String[20];
public static void main(String[] args) {
Scanner console=new Scanner(System.in);
issues[0]="Global Warming";
issues[1]="Earth Quakes";
issues[2]="Stopping war";
issues [3]="Equal Rights";
issues[4]="Curing Cancer";
int[][] polling =new int[5][10];
Random rand=new Random();
int random=rand.nextInt(9)+5;
int poll=0;
String polling2=Arrays.toString(polling);
for(int i=1;i<random;i++){
System.out.println("Person"+i);
System.out.println("Rate these issues from 1-10");
System.out.println(issues[0]);
int zero=console.nextInt();
System.out.println(issues[1]);
int one=console.nextInt();
System.out.println(issues[2]);
int two=console.nextInt();
System.out.println(issues[3]);
int three=console.nextInt();
System.out.println(issues[4]);
int four=console.nextInt();
}
System.out.println();
Something like this?:
public static final String[] ISSUES = {
"Global Warming",
"Earth Quakes",
"Stopping war",
"Equal Rights",
"Curing Cancer",};
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random rand = new Random();
int pollings = rand.nextInt(9) + 5;
int [][] rates= new int[pollings][ISSUES.length];
for (int i = 0; i < pollings; i++) {
System.out.println("Person" + i);
System.out.println("Rate these issues from 1-10");
for (int j = 0; j < ISSUES.length; j++) {
System.out.println(ISSUES[j]);
rates[i][j] = console.nextInt();
}
}
// ADDED
int minRating = Integer.MAX_VALUE;
int maxRating = Integer.MIN_VALUE;
int minRatingIndex = -1;
int maxRatingIndex = -1;
for (int i = 0; i < ISSUES.length; i++) {
System.out.print(ISSUES[i]+":");
int rating = 0;
for (int j = 0; j < pollings; j++) {
System.out.print("\t"+rates[j][i]);
rating += rates[j][i];
}
double average = ((double)rating)/pollings;
System.out.println("\tavr: "+average);
if (rating < minRating ){
minRating = rating;
minRatingIndex = i;
}
if (rating > maxRating ){
maxRating = rating;
maxRatingIndex = i;
}
}
System.out.println("Max points:\t"+ISSUES[maxRatingIndex]+":\t"+maxRating+" points");
System.out.println("Min points:\t"+ISSUES[minRatingIndex]+":\t"+minRating+" points");
System.out.println();
}