What's wrong with my constructor in this moving x matrix? - java

The idea is each iteration will move the [x] every time it prints. However it obviously can't print a 0x0 matrix. As you can see I summoned the constructor in the program to have the variables 4, 4. Yet for some reason, after running it, the program still outputs 0,0.
public class MovingX{
private int rowsN;
private int columnsM;
private int[][] matrixArr = new int[rowsN][columnsM];
private int x = 0;
private int y = 0;
public MovingX(int n, int m){
n = rowsN;
m = columnsM;
}
public void forLoopGrid(){
for(int i = 0; i < matrixArr.length; i++){
for(int j = 0; j < matrixArr.length; j++){
if(i == x && j == y) System.out.print("[x] ");
else System.out.print("[ ] ");
}
System.out.println();
}
System.out.println();
}
public void moveX(){
if(x < rowsN) x++;
else{
x = 0; y++;
}
}
public void runProgram(){
System.out.println("Program Starting");
System.out.println("Rows, Columns: " + rowsN + " " + columnsM);
for(int i = 0; i < (rowsN * columnsM); i++){
System.out.println("Stuff happening");
forLoopGrid();
moveX();
}
System.out.println("Program Ending");
}
public static void main(String[] args){
MovingX xLoop = new MovingX(4, 4);
xLoop.runProgram();
}
}

The problem seems to be the fact that you are assigning your object's fields(rowsN,columnsM) to the arguments(n,m) supplied to your class constructor.
You see, it doesn't matter what arguments you supply during instantiation when you use those local constructor variables to store the default value of your object's fields. You get (0,0) because all object fields get initialized to a default value and for int, that happens to be 0.
This should work--
public MovingX(int n, int m){
rowsN=n; //n = rowsN;
columnsM=m; //m = columnsM;
}

Reason maybe with the assignment.
public MovingX(int n, int m){
rowsN = n;
columnsM = m;
}
Try this, they may work.

Related

I can't print an array grid with objects and my class? Netbeans w/ Java

I am making a grid with the amounts determined by a scanner. I keep getting an error and I am not sure why. Here is the code for the grid that I am trying to make, I will also include the object and class for the maze/grid below.
public static void mazeSetup() {
System.out.println("How many rows and columns do you want? I would\n"
+ "suggest 10 minimum and 20 maximum.");
boolean mazeselect = true;
while(mazeselect) {
maze.columns = sc.nextInt();
maze.rows = maze.columns;
if (maze.rows > 30 || maze.rows < 10) {
System.out.println("Make sure that you make it within 10-30 rows.");
} else {
mazeselect = false;
}
}
mazeBuild();
}
public static void mazeBuild() {
for(int x = 0; x < maze.rows; x++) {
for(int y = 0; y < maze.columns; y++) {
maze.maze[x][y]= ".";
System.out.print(maze.maze[x][y]);
}
System.out.println();
}
characterPlacement();
}
I also have the object here:
static Maze maze = new Maze(null,0,0,0,0);
and the class with construtors for the maze/grid.
public class Maze {
String maze[][];
int rows;
int columns;
int xStart;
int yStart;
public Maze(String xMaze[][], int xRows, int xColumns, int xxStart, int xyStart) {
maze = xMaze;
rows = xRows;
columns = xColumns;
xStart = xxStart;
yStart = xyStart;
}
public String[][] maze() {
return maze;
}
public int rows() {
return rows;
}
public int columns() {
return columns;
}
public int xStart() {
return xStart;
}
public int yStart() {
return yStart;
}
}
Any help would be greatly appreciated. Thanks a lot! :D
Note: No errors occur until ran in console.
your String maze[][] is null because of this:
static Maze maze = new Maze(null,0,0,0,0); // notice that null
And you're trying to put values in it upon calling mazeBuild(). You should initialize it or pass an array instead of null. You can do this at the start of mazeBuild()
public static void mazeBuild() {
maze.maze = new String[maze.rows][maze.columns]; // <-- this one!
for(int x = 0; x < maze.rows; x++) { // <-- this loop tries to
for(int y = 0; y < maze.columns; y++) { // put values in your
maze.maze[x][y]= "."; // maze.maze (2D String array)
System.out.print(maze.maze[x][y]);
}
System.out.println();
}
You can also do this in exchange to the line of code I've added.
String[][] mazeArray = new String[maze.rows][maze.columns];
maze = new Maze(mazeArray, maze.rows, maze.columns, 0, 0);

Fibonacci sequence in Java using for statements

I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}

method cannot be applied to given types

In my program, I'm trying to call the throwDice method in a different class.
public class SimpleDice {
private int diceCount;
public SimpleDice(int the_diceCount){
diceCount = the_diceCount;
}
public int tossDie(){
return (1 + (int)(Math.random()*6));
}
public int throwDice(int diceCount){
int score = 0;
for(int j = 0; j <= diceCount; j++){
score = (score + tossDie());
}
return score;
}
}
import java.util.*;
public class DiceTester {
public static void main(String[] args){
int diceCount;
int diceScore;
SimpleDice d = new SimpleDice(diceCount);
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of dice.");
diceCount = scan.nextInt();
System.out.println("Enter target value.");
diceScore = scan.nextInt();
int scoreCount = 0;
for(int i = 0; i < 100000; i++){
d.throwDice();
if(d.throwDice() == diceScore){
scoreCount += 1;
}
}
System.out.println("Your result is: " + (scoreCount/100000));
}
}
When I compile it, an error pops up for the d.throwdice() and says it can't be applied. It says it needs an int and there are no arguments. But I called an int diceCount in the throwDice method, so I don't know what's wrong.
for(int i = 0; i < 100000; i++){
d.throwDice();
if(d.throwDice() == diceScore){
scoreCount += 1;
}
}
There are two things wrong with this code:
It calls throwDice without an int (you have defined it as public int throwDice(int diceCount), so you must give it an int)
It calls throwDice twice each loop
You could fix it like this:
for(int i = 0; i < 100000; i++){
int diceResult = d.throwDice(diceCount); // call it with your "diceCount"
// variable
if(diceResult == diceScore){ // don't call "throwDice()" again here
scoreCount += 1;
}
}
You've defined throwDice as taking an int as follows:
public int throwDice(int diceCount)
But you are calling it without any args which just won't work:
d.throwDice();
throwDice() does require you to pass an int as the parameter:
public int throwDice(int diceCount){..}
And you are providing no arguments:
d.throwDice();
You need to pass an int as the parameter in order to make this work:
int n = 5;
d.throwDice(n);
The variable diceCount on the method declaration of throwDice(int diceCount) only indicates it requires an int as an argument and that the argument will be stored in the variable diceCount, it doesn't actually provide the actual primitive int.
Finally, you are also calling throwDice twice.

string match sequence array

public class sequence {
public static void main(String args[]){
char[] c = {'a','x','c','e'};
char[] t = {'x','b'};
int count = 0,j;
for(int i=0;i<(c.length);i++)
{
int p = i;
int x = 0;
for( j=0;j<(t.length);j++){
if(c[p]!=c[j]){
break;
}
else
x++;
System.out.print(x);
if(x==((t.length))){
count++;
}
p++;
}
System.out.print('a');
}
System.out.println("Number of Occurences " + count);
}
}
My task is to count the number of time the sequence ie t[] occurs in the mother array c[].
I am not able to get the required result even though i tries all the iterations in my mind where it worked well.I am kind of a starter in programming so need some help here.
Thankya!
You should take this piece of code:
if(x==((t.length))){
count++;
}
From the inner loop.
The problem is that your x == t.length check is inside your inner for loop, but your inner for loop will never let x reach t.length. Also, your x variable is redundant and is always equal to j so it can be removed.
To fix this, move your length-check to the outside of the loop.
Edit: Also, you're accessing the wrong array in your inner loop (where the break statement is).
public static void main(String args[]){
char[] c = {'a','x','c','e'};
char[] t = {'x','b'};
int count = 0, j;
for (int i = 0; i < (c.length); i++) {
int p = i;
for (j = 0; j < (t.length); j++){
if (c[p] != t[j]) {
break;
}
p++;
}
if (j == t.length){
count++;
}
}
System.out.println("Number of Occurences " + count);
}
You shouldn't need two for loops:
public static void main(String args[]){
char[] c = {'a','x','b','c','x','b','e'};
char[] t = {'x','b'};
int count = 0;
int tInd = 0;
for(int i=0;i<(c.length);i++)
{
if(tInd < t.length && t[tInd] == c[i]){ // Found a member of t[]
tInd ++;
} else {
tInd = 0; // Didn't find t[]
}
if(tInd == t.length){ // Found full t[] sequence
count++;
tInd = 0;
}
}
System.out.println("Number of Occurences " + count);
}
You don't need to loop on all c elem (you can stop in the position of last possible match). In the inner loop as soon as you find a match you must continue on next c elem:
public static void main(String[] args) {
char[] c = {'c','a','x','b'};
char[] t = {'x','b'};
int count = 0, j;
for(int i=0;i<=(c.length-t.length);i++)
{
for(j=0;j<(t.length);j++){
if(t[j]!=c[i+j]){
break;
}
}
if(j==t.length)
count++;
}
System.out.println("Number of Occurences " + count);
}

non static variable called from static content, java

I know this question was answered before, but I cant still handle it with my code.
Please can someone pointing out how can I fix it on this particular code. Id like to call trace(); but dont know where to call new trace. I tried different stuff from here but it does not work for me. Thank you!
package matr;
import java.util.Scanner;
final public class Matrix {
private final int M;
private final int N;
private double[][] data;
public Matrix(int M, int N) {
this.M = M;
this.N = N;
data = new double[M][N];
}
public Matrix(double[][] data) {
M = data.length;
N = data[0].length;
this.data = new double[M][N];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
this.data[i][j] = data[i][j];
}
private Matrix(Matrix A) {
this(A.data);
}
public static Matrix random(int M, int N, int r) {
Matrix A = new Matrix(M, N);
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
A.data[i][j] = (Math.random() * r);
}
}
return A;
}
public double trace() {
// trace a = new trace();
double t = 0;
for (int i = 0; i < Math.min(M, N); i++) {
t += data[i][i];
}
return t;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("rows: ");
try {
int x = Math.abs(scan.nextInt());
System.out.println("columns: ");
int y = Math.abs(scan.nextInt());
System.out
.println("generate: ");
int r = scan.nextInt();
Matrix A = Matrix.random(x, y, r);
System.out.println("random A");
trace();
} catch (java.util.InputMismatchException e) {
System.out.println("Please enter a valid int");
}
}
}
call A.trace()
use lower-case names for variables and fields
your main method is static. and your trace() method is a non-static method of the Matrix class. That means you have to call trace() on an instance of Matrix.
You are trying to call a non-static method trace() from a static method main(). Since 'main' is static it can only refer to static variables and static methods within the class. You will need to use an instance of Matrix to call trace. for example:
Matrix A = Matrix.random(x,y,r);
A.trace();
You need to call the trace() method on an instance of the type Matrix.
You could do this simply by:
A.trace();

Categories

Resources