I am making a code that only prints the even numbers of an array. But I am having a problem sending evenNum variable from countEm to getAllEvens.
private static int countEm(int[] array)
{
int evenNum = 0;
for (int i = 0; i <array.length; i++)
{
if (i%2 == 0)
{
evenNum++;
}
}
return evenNum;
}
public static int[] getAllEvens(int[] array)
{
int[] evens = new int [evenNum];
int c = 0;
for(int i = 0; i < array.length; i++)
{
if(array[i]%2==0)
{
evens[c] = array[i];
c++;
}
}
return evens;
}
How do I use a variable from another method?
In that way, gettAllEvents will never get acces to evenNum.
You should declare it outside the function countEm
My code is checking if a given string is in a certain format. The first char of the string has to be an uppercase letter and the rest of the string has to be any number that is from 1 to given dimension.
If the first char of the string contains a string from the alphabet array, then the code checks if the rest of the string contains a number from the numbers array. To be a valid coordinate both conditions must be true, if one of them is false it is not a valid coordinate. I want to return the boolean isValidCoordinate but however IntelliJ is telling me that I have to initialise isValid coordinate. Why do I have to initialise it, the boolean expression depends on the 'if' conditions.
Thanks.
public static boolean validCoordinate(String coordinate, int dimension) {
boolean isValidCoordinate;
String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int [] numbers = new int [dimension];
int one = 1;
for(int i = 0; i < dimension; i++){
numbers[i] = one + i;
}
for(int i = 0; i < dimension; i++){
if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
for(int j = 0; j < dimension; j++) {
if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
isValidCoordinate = true;
}
else {
isValidCoordinate = false;
}
}
}
else {
isValidCoordinate = false;
}
}
return isValidCoordinate;
}
This is my final code:
public static boolean validCoordinate(String coordinate, int dimension) {
boolean isValidCoordinate;
String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int [] numbers = new int [dimension];
int one = 1;
for(int i = 0; i < dimension; i++){
numbers[i] = one + i;
}
for(int i = 0; i < dimension; i++){
if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
for(int j = 0; j < dimension; j++) {
if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
isValidCoordinate = true;
}
else {
isValidCoordinate = false;
}
}
}
else {
isValidCoordinate = false;
}
}
return true;
}
All the cases inside the for loop are covered, but not the case when dimension is 0.
The method will go straight to return isValidCoordinate;, where the variable isn't initialized yet.
It is possible that your for loop will never be entered (for example, if dimension == 0). In that case, you will never assign a value to isValidCoordinate, but you will attempt to return the value of that variable in the last statement of your method.
What would be the value of isValidCoordinate in such case?
It wouldn't have any value.
Therefore, you are forced by the compiler to assign an initial value to isValidCoordinate, to make sure that it has a value before it is accessed.
EDIT:
Following your comments, I suggest you eliminate the boolean variable, and use return statements instead:
public static boolean validCoordinate(String coordinate, int dimension) {
String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int [] numbers = new int [dimension];
int one = 1;
for(int i = 0; i < dimension; i++){
numbers[i] = one + i;
}
for(int i = 0; i < dimension; i++){
if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
for(int j = 0; j < dimension; j++) {
if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
return true;
}
}
}
}
return false;
}
This way you don't have to worry about breaking out of nested loops when the boolean variable is set to true.
import java.util.regex.*;
public static boolean validCoordinate(String coordinate, int dimension)
{
Pattern p = Pattern.compile("[A-Z]+");
Matcher m = p.matcher(coordinate);
return m.matches();
}
How can I make the second iteration use the first array "poqet" to switch their positions from true to false, but without changing their state when the first iteration made them all true?
public class Dhoma {
public static void main(String[] args) {
boolean poqet[] = new boolean[100];
int njerezit[] = new int[100];
int count = 0;
int nrRendorP = 0;
int nrRendorN = 0;
for (int i = 0; i < njerezit.length; i++) {
nrRendorN++;
for (int k = 0; k < poqet.length; k++) {
nrRendorP++;
if (nrRendorP == 100) {
nrRendorP = 0;
}
poqet[i] = Switch(nrRendorN, nrRendorP);
System.out.println(k + " " + poqet[i]);
}
}
// System.out.println("Jane te ndezura "+ count);
}
private static boolean Switch(int nr, int n) {
if (n % nr == 0) {
return true;
}
return false;
}
}
I made a program that makes an array of random ints and doubles in size if the user tries to add an int. Example: 1|2|3|4 if they were to add another int it would look like 1|2|3|4|5|0|0|0. I have made a method to add an int which works but now I am trying to make methods that remove one of a certain int and another that removes all of a certain int. for example removeInt(3) would give me 1|2|0|4|5|0|0|0. I have the first part working so that it shifts the zero to the end like this 1|2|4|5|0|0|0|0 but cannot get it to work for more than one of the same value. Any suggestions?
// ****************************************************************
// IntegerList.java
//
// Define an IntegerList class with methods to create & fill
// a list of integers.
//
// ****************************************************************
public class IntegerList
{
int[] list; //values in the list
//-------------------------------------------------------
//create a list of the given size
//-------------------------------------------------------
public IntegerList(int size)
{
list = new int[size];
}
//-------------------------------------------------------
//fill array with integers between 1 and 100, inclusive
//-------------------------------------------------------
public void randomize()
{
for (int i=0; i<list.length; i++)
list[i] = (int)(Math.random() * 100) + 1;
}
//-------------------------------------------==----------
//print array elements with indices
//-------------------------------------------------------
public void print()
{
for (int i=0; i<list.length; i++)
System.out.println(i + ":\t" + list[i]);
}
public void addElement(int newVal){
boolean full = true;
System.out.println(list.length);
int position = 0;
int place;
while(position < list.length){
System.out.println("HERE");
if(list[position]==0){
System.out.println("here");
full = false;
place = position;
System.out.println(place);
}
position = position+1;
}
if(full == true){
list = increaseSize(list);
System.out.println("L"+list.length);
full = false;
}
for(int i = 0;i<list.length;i++){
if(list[i]==0){
if(i<position){
position = i;
System.out.println(list.length);
}
}
}
list[position] = newVal;
}
public void removeFirst(int newVal){
int position = 0;
boolean removed = false;
for(int i = 0; i<list.length;i++){
if(list[i] == newVal){
list[i]=0;
position = i;
removed = true;
break;
}
}
if(removed==true){
for(int i = position;i<list.length;i++){
if(i!=list.length-1){
list[i]=list[i+1];
}
}
list[list.length-1]= 0;
}
}
public void removeAll(int newVal){
int position = 0;
boolean removed = false;
for(int i = 0; i<list.length;i++){
if(list[i] == newVal){
list[i]=0;
position = i;
removed = true;
}
}
if(removed==true){
for(int i = 0;i<list.length;i++){
if(i!=list.length-1 && list[i+1]==newVal){
list[i]=0;
}
if(list[i]==newVal){
list[i]=0;
}
}
}
}
public static int[] increaseSize(int[] x){
int newLength = x.length *2;
int[] newx = new int[newLength];
for(int i = 0; i<x.length; i++){
newx[i] = x[i];
}
return newx;
}
public static int[] halfSize(int[] x){
int[] newx = new int[x.length / 2];
for(int i = 0; i<x.length; i++){
newx[i] = x[i];
}
return newx;
}
}
I believe there's an easier way to implement your removeAll method. Move 2 (rather than 1) indices through your array constantly shifting the values over the items you are removing;
int dest = 0;
int source = 0;
while (source < array.length) {
if (array[dest] != valueToRemove)
dest++;
array[dest] = array[source++];
}
while (dest < array.length) {
array[dest++] = 0;
}
I executed your code and found out that the problem is in this piece, under removeAll()...
if(removed){
for(int i = 0;i<list.length;i++){
if(i!=list.length-1 && list[i+1]==newVal){
list[i]=0;
}
if(list[i]==newVal){
list[i]=0;
}
}
}
If you comment out and try once, you will see the removeAll() is working and your desired number is replaced with 0s. Now why you don't simply check your numbers and shift(sorting), if they are greater than 0 to the left?
I have some problems with getting inheritance to work. In the parent class, the array Coefficients is private. I have some access methods but I still can't get it to work.
import java.util.ArrayList;
public class Poly {
private float[] coefficients;
public static void main (String[] args){
float[] fa = {3, 2, 4};
Poly test = new Poly(fa);
}
public Poly() {
coefficients = new float[1];
coefficients[0] = 0;
}
public Poly(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}
public Poly(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}
public int getDegree() {
return coefficients.length-1;
}
public float getCoefficient(int i) {
return coefficients[i];
}
public void setCoefficient(int i, float value) {
coefficients[i] = value;
}
public Poly add(Poly p) {
int n = getDegree();
int m = p.getDegree();
Poly result = new Poly(Poly.max(n, m));
int i;
for (i = 0; i <= Poly.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}
public void displayPoly () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}
private static int max (int n, int m) {
if (n > m)
return n;
return m;
}
private static int min (int n, int m) {
if (n > m)
return m;
return n;
}
public Poly multiplyCon (double c){
int n = getDegree();
Poly results = new Poly(n);
for (int i =0; i <= n; i++){ // can work when multiplying only 1 coefficient
results.setCoefficient(i, (float)(coefficients[i] * c)); // errors ArrayIndexOutOfBounds for setCoefficient
}
return results;
}
public Poly multiplyPoly (Poly p){
int n = getDegree();
int m = p.getDegree();
Poly result = null;
for (int i = 0; i <= n; i++){
Poly tmpResult = p.multiByConstantWithDegree(coefficients[i], i); //Calls new method
if (result == null){
result = tmpResult;
} else {
result = result.add(tmpResult);
}
}
return result;
}
public void leadingZero() {
int degree = getDegree();
if ( degree == 0 ) return;
if ( coefficients[degree] != 0 ) return;
// find the last highest degree with non-zero cofficient
int highestDegree = degree;
for ( int i = degree; i <= 0; i--) {
if ( coefficients[i] == 0 ) {
highestDegree = i -1;
} else {
// if the value is non-zero
break;
}
}
float[] newCoefficients = new float[highestDegree + 1];
for ( int i=0; i<= highestDegree; i++ ) {
newCoefficients[i] = coefficients[i];
}
coefficients = newCoefficients;
}
public Poly differentiate(){
int n = getDegree();
Poly newResult = new Poly(n);
if (n>0){ //checking if it has a degree
for (int i = 1; i<= n; i++){
newResult.coefficients[i-1]= coefficients[i] * (i); // shift degree by 1 and multiplies
}
return newResult;
} else {
return new Poly(); //empty
}
}
public Poly multiByConstantWithDegree(double c, int degree){ //used specifically for multiply poly
int oldPolyDegree = this.getDegree();
int newPolyDegree = oldPolyDegree + degree;
Poly newResult = new Poly(newPolyDegree);
//set all coeff to zero
for (int i = 0; i<= newPolyDegree; i++){
newResult.coefficients[i] = 0;
}
//shift by n degree
for (int j = 0; j <= oldPolyDegree; j++){
newResult.coefficients[j+degree] = coefficients[j] * (float)c;
}
return newResult;
}
}
Can anyone help me fix my Second class that inherits from the one above? I cant seem to get my multiply and add methods for the second class to work properly.
public class QuadPoly extends Poly
{
private float [] quadcoefficients;
public QuadPoly() {
super(2);
}
public QuadPoly(int degree) {
super(2);
}
public QuadPoly(float [] f) {
super(f);
if (getDegree() > 2){
throw new IllegalArgumentException ("Must be Quadratic");
}
}
public QuadPoly(Poly p){
super(p.coefficients);
for (int i = 0; i < coefficients.length; i++){
if (coefficients[i] < 0){
throw new Exception("Expecting positive coefficients!");
}
}
}
// public QuadPoly(Poly p){
// super(p.coefficients);
//}
public QuadPoly addQuad (QuadPoly p){
return new QuadPoly(super.add(p));
}
public QuadPoly multiplyQuadPoly (QuadPoly f){
if (quadcoefficients.length > 2){
throw new IllegalArgumentException ("Must be Quadratic");
}
return new QuadPoly(super.multiplyPoly(f));
}
I would make the coefficients protected or use an accessor method.
I wouldn't throw a plain checked Exception. An IllegalArgumentException would be a better choice.
What is quadcoefficients? They don't appear to be set anywhere.
You put coefficients private. I wouldn't change this but I would add a getter method into Poly class:
public class Poly {
//somecode here
public float[] getCoefficients(){
return this.coefficients;
}
}
Then I would use it by the getter method in other code;
public QuadPoly(Poly p){
super(p.getCoefficients);
//some more code here
}
Even if you make coefficient protected, you are trying to reach coefficients field of another Object, which is a parameter. So it is not related to inheritance and the problem.