Search code examples
variablesmethodssavelocalnumerical

Saving local variables - Java


Here is a program that is supposed to find out whether a sequence of numbers match the mathematical formula a[n+1] = a[n]*b+c for any combination of b and c in the integer range -9:9.

import java.util.Scanner;


public class Nastaord{

    private static int[] lasTal(){
        int[] tallista; //Det vi ska ha talföljden i

        int i = 0;  //räknare för tallista
        while(true){
            System.out.print("Ange tal, eller tryck enter om du är klar: ");
            int nytt_tal = scanner.nextLine();
            if(nytt_tal == ""){
                return tallista;}
            tallista[i] = nytt_tal;
            i++;
        }

    }
    private static boolean bcFinns(int[] tallista){
        boolean OK = true;
        for(int b = -9; b <= 9; b++){
            for(int c = -9; c <= 9; c++){
                for(int i = tallista.length; i > 0;i--){
                    OK = tallista[i] == tallista[i-1]*b+c;
                    if(OK == false){
                        break;}

                    }
                if(OK == true){
                    public int b = b;
                    public int c = c;
                    return true;}
                }
            }
        return false;
        }

    public static void main(String[] args){
        boolean OK = bcFinns(lasTal());
        if (OK == true){
            System.out.print(tallista[tallista.length-1]*b+c);
        }
        if (OK == false){
            System.out.print("No");
        }
    }
}

The program, on a principal level, works. The only thing is that I do not know how to save the correct numbers b and c for the sequence once they are found. I tried creating two public variables so that I can access them in the main method, but I get the following error:

Nastaord.java:30: error: illegal start of expression
                    public int b = b;
                    ^
Nastaord.java:31: error: illegal start of expression
                    public int c = c;

Could you help me save these variables b and c in some way?


Solution

  • public class Nastaord{
        public static int bFinal,cFinal;
    

    Then later on:

    bFinal = b;
    cFinal = c;