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;
}
Related
This is how it should work, i Put in put for the 1 st array like: 2 3 1 2 3 4 5 6 then 2 and 3 are row and colum and the rest are the values. Problem is the 1st array work, but when i reach EOF ( ctrl+z) then there is out of bound exception. Which mean i cant input value for the 2nd Array like the 1st one. I know there is anotherway where that i can declare array size first then value. But how could i fix this f i still want to usr StdIn.readAllInts() ?
public class MatrixMult {
public static void main(String[] args){
System.out.println("First Matrix Config");
int[] einGabeMatrix1= StdIn.readAllInts();
int zeileM1 = einGabeMatrix1[0];
int spalteM1 = einGabeMatrix1[1];
int[][] ersteMatrix= new int [zeileM1][spalteM1];
int k=2;
int sum;
for(int i=0;i<zeileM1-1;i++){
for(int j=0;j<spalteM1-1;j++){
ersteMatrix[i][j]=einGabeMatrix1[k];
k++;
}
}
System.out.println("Second Matrix Config");
int[] einGabeMatrix2 = StdIn.readAllInts();
int zeileM2 = einGabeMatrix2[0];
int spalteM2 = einGabeMatrix2[1];
int h=2;
int[][] zweiteMatrix= new int [zeileM2][spalteM2];
for(int m=0;m<zeileM2-1;m++){
for(int n=0;n<spalteM2-1;n++){
zweiteMatrix[m][n]=einGabeMatrix2[h];
h++;
}
}
int[][] ergebnisMatrix= new int [zeileM1][spalteM2];
for (int t = 0; t < zeileM1; t++) {
for (int c = 0; c < spalteM2; c++) {
sum = 0;
for (int d = 0; d < spalteM1; d++) {
sum = sum + ersteMatrix[t][d] * zweiteMatrix[d][c];
}
ergebnisMatrix[t][c] = sum;
}
}
for(int i=0;i<zeileM1;i++){
for(int j=0;j<spalteM1;j++){
System.out.println(ergebnisMatrix[i][j]);
}
}
}
}
// This is StdIn.readAllInts(), standard method by java.
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
It looks like the issue is coming from the fact that StdIn.readAllInts() reads until the EOF. There will be no values left to read by the time your code gets to the second call.
I would suggest instead using the StdIn.readInt() call to read each integer one at a time and then you can use it within your loop to read the exact number of values your need.
Here is an example of how you could get the first 2 integers to find your matrix size:
int zeileM1 = StdIn.readInt();
int spalteM1 = StdIn.readInt();
You will also need to apply this method in your for loops to read the data into the matrix.
so, I'm supposed to make a matrix using HashMap<Integer,ArrayList<Number>>, where Number is a class who's instance variables are numerator and denominator.
Class Matrix inherits Class Number, which have methods like fillMatrix(), printMatrix(), addMatrix(Matrix,Matrix) and subMatrix(Matrix,Matrix), problem is in those last two methods, i made them but I'm pretty sure they are completely wrong since i get a NullPointerxception, How do i make such methods?
here is the code.
public class Matrix extends Number implements Calculation
{
public static int rows;
public static int cols;
private ArrayList<Number> myArray;
private ArrayList<Double> myArray2;
private ArrayList<Double> myArray3;
private ArrayList<Double> myArray4;
private HashMap <Integer, ArrayList<Number>> hm;
private HashMap <Integer, ArrayList<Double>> hm2;
public Matrix(int r, int c)
{
hm = new HashMap<>();
hm2 = new HashMap<>();
rows = r;
cols = c;
}
public void fillMatrix()
{
Scanner input = new Scanner(System.in);
myArray = new ArrayList<>();
myArray2 = new ArrayList<>();
System.out.println("Enter the number of rows");
rows = input.nextInt();
System.out.println("Enter the number of columns");
cols = input.nextInt();
Number n = new Number();
for (int i = 0; i < cols;i++)
{
n.setNumerator(i);
n.setDenominator(i+1);
myArray.add(new Number(i,i+1));
double xn = n.getNumerator();
double xd = n.getDenominator();
myArray2.add(xn/xd);
}
for (int i = 0; i < rows; i++)
hm2.put(rows,myArray2);
}
public void printMatrix()
{
for (int i = 0; i < rows; i++)
{hm.put(rows,myArray);
System.out.println(myArray3.toString());
}
}
public Number getItem(int rowNO,int colNO)
{
rows = rowNO - 1;
cols = colNO - 1;
hm.get(rows);
return myArray.get(cols);
}
public void addMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sum = a1+a2;
myArray3 = new ArrayList<>();
myArray3.add(sum);
}
x1=a;
x2=b;
}
}
public void subMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
{ x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sub = a1-a2;
myArray4 = new ArrayList<>();
myArray4.add(sub);
}
x1=a;
x2=b;
}
}
}
}
I'm a bit confused here, so I'll point out some things I noticed.
First off it's difficult to understand your code because of the variable names.
Also none of the methods are static, so i don't really understand why you're bringing in two Matrices for the calculation, then setting them equal to the first two you create in the beggining of both methods.
Next, you have two brackets after your for loop in the subtraction method, I'm guessing it was just a typo when pasting in StackOverflow.
The myArray objects you're adding the sum too is not going to be accumulating all the sums because you are creating a new arraylist each time that loop goes through. Create it outside the loop.
The NullPointerException could be anywhere really, it's hard to tell because the code is a bit confusing.
I would recommend using the LWJGL library which has has classes like Matrix4fand methods like Matrix4f.add();which will help you accomplish this.
Try running your program in debug mode so you can understand which statement gives you null pointer exception.
And I've noticed you have your rows and columns as static but you can change change them within constructor. It seems there is a logical mistake there. These two may be the cause of your exception if you didn't ever give initial value of them before.
If your matrixes can have different rows and columns then you definitely shouldn't use static for them.
To actually understand where nullpointerexception is given, you should also write your main code. But like I said, in debug mode, you can also see it yourself.
So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.
import java.util.Scanner;
public class MarkCalculator {
public static int[] exam_grade = new int[6];
public static int[] coursework_grade = new int[6];
public static int[] coursework_weight = new int[2];
public static int[] module_points = new int[6];
public static String[] module_grade = new String[20];
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
for (int i=0; i<3; i++){
System.out.printf(i+". Modelue"+" Enter grade of exam:");
exam_grade[i]=input.nextInt();
System.out.printf(i+". Modelue"+" Enter grade of coursework:");
coursework_grade[i]=input.nextInt();
}
for(int i = 0 ;i < 3; i++){
System.out.println(exam_grade[i]+" "+coursework_grade[i]);
}
computeMark(module_points, coursework_grade, exam_grade);
for(int i = 0 ;i < 3; i++){
System.out.println(module_points[i]);
}
input.close();
}
public static int[] computeMark (int coursework_grade[], int exam_grade[], int module_points[]){
coursework_weight[0]= 50;
coursework_weight[1]= 50;
for(int i=0;i<3;i++){
if (coursework_grade[i] < 35 || exam_grade[i] < 35){
module_points[i]=((coursework_grade[i]*coursework_weight[0] + (exam_grade[i]*(100-coursework_weight[1])))/100);
}
}
return module_points;
}
}
I wonder why it doesn't return any value. The function module_points worked few days ago and now I just can't find any error there. The output is all the time 0 only. Anyone can help pls? Thank you.I bet it's just something simple but really stuck at this point. What i need to do is: based on input (coursework_grade and exam_grade) count the module_points (formula is given), store these values in the array and return this array to the main method where is this array showed. Thanks for help guys.
You are calling the function computeMark() without storing the returned result.
Change:
computeMark(module_points, coursework_grade, exam_grade);
To: [edited]
module_points = computeMark(coursework_grade, exam_grade, module_points);
I guess you got 0 with divide by 100. Declare module_points[] as double[] to get the fraction value.
see the part:
if (coursework_grade[i] < 35 || exam_grade[i] < 35)
{
module_points[i]= ......
}
This means all your inputs must be >= 35 Otherwise no association of module_point array elements will occur.
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.