Saving local variables - Java - variables

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?

public class Nastaord{
public static int bFinal,cFinal;
Then later on:
bFinal = b;
cFinal = c;

Related

Why doesn't my number sequence print from the 2d arraylist correctly?

I cannot get the loop to work in the buildDimArray method to store the number combinations "11+11", "11+12", "11+21", "11+22", "12+11", "12+12", "12+21", "12+22", "21+11", "21+12", "21+21", "21+22", "22+11", "22+12", "22+21", and "22+22" into the 2d arraylist with each expression going into one column of the index dimBase-1 row. The loop may work for other people, but for some reason mine isn't functioning correctly. The JVM sees the if dimBase==1 condition, but refuses to check the other conditions. The "WTF" not being printed as a result from the buildDimArray method. If dimBase=1, it prints successfully, but doesn't for the other integers. The dimBase==3 condition needs a loop eventually. The "WTF" is for illustrative purposes. I could get away with a 1d arraylist, but in the future I will likely need the 2d arraylist once the program is completed.
package jordanNumberApp;
import java.util.Scanner;
import java.util.ArrayList;
/*
* Dev Wills
* Purpose: This code contains some methods that aren't developed. This program is supposed to
* store all possible number combinations from numbers 1-dimBase for the math expression
* "##+##" into a 2d arraylist at index row dimBase-1 and the columns storing the
* individual combinations. After storing the values in the arraylist, the print method
* pours the contents in order from the arraylist as string values.
*/
public class JordanNumberSystem {
// a-d are digits, assembled as a math expression, stored in outcomeOutput, outcomeAnswer
public static int dimBase, outcomeAnswer, a, b, c, d;
public static String inputOutcome, outcomeOutput;
public static final int NUM_OF_DIMENSIONS = 9; //Eventually # combinations go up to 9
public static ArrayList<ArrayList<String>> dimBaseArray;
public static Scanner keyboard;
/*
* Constructor for JordanNumber System
* accepts no parameters
*/
public JordanNumberSystem() // Defunct constructor
{
// Declare and Initialize public variables
this.dimBase = dimBase;
this.outcomeOutput = outcomeOutput;
this.outcomeAnswer = outcomeAnswer;
}
// Set all values of variable values
public static void setAllValues()
{
// Initialize
dimBase = 1;
outcomeAnswer = 22; // variables not used for now
outcomeOutput = "1"; // variables not used for now
//a = 1;
//b = 1;
//c = 1;
//d = 1;
dimBaseArray = new ArrayList<ArrayList<String>>();
keyboard = new Scanner(System.in);
}
public static void buildDimArray(int dim)
{
dimBase = dim;
try
{
//create first row
dimBaseArray.add(dimBase-1, new ArrayList<String>());
if( dimBase == 1)
{
a = b = c = d = dimBase ;
dimBaseArray.get(0).add(a+""+b+"+"+c+""+d);
System.out.println("WTF"); // SHOWS
}
else if (dimBase == 2)
{ // dim = 2
a = b = c = d = 1 ;
System.out.println("WTF"); // doesn't show
// dimBaseArray.get(dimBase-1).add(a+""+b+"+"+c+""+d);
for( int i = 1 ; i <= dim ; i++)
a=i;
for( int j = 1 ; j <= dim ; j++)
b=j;
for( int k = 1 ; k <= dim ; k++)
c=k;
for( int l = 1 ; l <= dim ; l++)
{
d=l;
dimBaseArray.get(dim-1).add(a+""+b+"+"+c+""+d);
}
}
else if (dimBase == 3)
{
a = b = c = d = dimBase;
dimBaseArray.get(2).add(a+""+b+"+"+c+""+d);
System.out.println("WTF");
}
}catch (IndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
public static void printArray(int num) // Prints the contents of the array
{ // Fixing the printing method
try
{
int i = num-1;
for( String string : dimBaseArray.get(i))
{
System.out.println(string);
System.out.println("");
}
} catch (IndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws java.lang.IndexOutOfBoundsException
{
setAllValues(); // sets the initial a,b,c,d values and dimBase, initializes 2d arraylist
// Get the Dimension Base number
System.out.println("Enter Dimension Base Number. Input an integer: ");
int dimBaseInput = keyboard.nextInt(); // Receives integer
dimBase = dimBaseInput;
if( dimBase != 1 && dimBase != 2 && dimBase != 3)
{// Error checking
System.out.println("invalid Dimension Base Number should be 1 or 2 ");
System.exit(1);
}
// Build the arraylist, print, clear, exit
buildDimArray(dimBase);
printArray(dimBase);
dimBaseArray.clear();
System.exit(1);
}
}// End of class

I can't figure out how to call a variable from another method

I am am trying to call a variable in another method to my array.
var Com = the difficulty for the game. But the method below I'm trying to call the var Com, for: var c = Com.GetChoice();
Not sure why I can not figure out how to call it.
public object SetDiff()
{
Console.WriteLine("Enter difficulty #: (1 = Easy, 2 = Normal, 3 = Impossible)");
var diff = Console.ReadLine();
int mode;
int.TryParse(diff, out mode);
if (mode == 1)
{
Console.Clear();
var Com = new Easy();
return Com;
}
if (mode == 2)
{
Console.Clear();
var Com = new Medium();
return Com;
}
if (mode == 3)
{
Console.Clear();
var Com = new Hard();
return Com;
}
else
{
Console.WriteLine("That is not a valid input.");
return SetDiff();
}
} // Apparently you can't set variables in a switch.
public int[] FaceOff(int num)
{
int PlayerWin = 0;
int ComWin = 0;
int Tie = num + 1;
// TODO : Get rid of TIES!
for (int i = 0; i < num; i++)
{
var p = p1.GetChoice();
var c = Com.GetChoice();
You have many different options:
Pass as parameter
public int[] FaceOff(int num, int Com){...}
make a "global" variable
private int Com;
I would also recommend you to learn OOP (Object Orientated Programming) basics.

How to determine input datatype?

I want to accept two inputs. If both the inputs are integer then add them. If any or both the inputs are string then concatenate them. I want to know the code to determine whether the input is integer or string?
Thanks for reading...
You can use method overloading for this,
Check out Java code given below
public class MethodExample
{
public static void main (String[] args)
{
int a,b;
String string1,string2;
//accept values for all variables...;>>
System.Out.Println("Addtion is "+sum(a,b));
System.Out.Println("Contact is "+sum(string1,string2));
}
int sum(int a,int b)
{
return(a+b);
}
String sum(string a,string b)
{
return(a+b);
}
}
I have used the following logic:
Console.WriteLine("Enter two inputs:");
string s1 = Console.ReadLine();
string s2 = Console.ReadLine();
double num;
int s3;
string s4;
bool isNum1 = double.TryParse(s1, out num);
bool isNum2 = double.TryParse(s2, out num);
if( isNum1==true && isNum2==true)
{
s3 = Convert.ToInt32(s1) + Convert.ToInt32(s2);
Console.WriteLine("Output = {0}", s3);
}
else
{
s4 = s1 + s2;
Console.WriteLine("Output = {0}",s4);
}

How to extract abstraction?

My question is trivial, but i can not find proper solution.
Code (just for example):
public class ToRefact
{
public int Func1(int i)
{
int a = i;
a++;
a++;
a++;
int b = FuncX2(a); //b = a * 2;
b++;
b++;
b++;
return a + b;
}
public int Func2(int i)
{
int a = i;
a++;
a++;
a++;
int b = FuncX3(a); // b = a * 3;
b++;
b++;
b++;
return a + b;
}
private int FuncX2(int b)
{
return b * 2;
}
private int FuncX3(int b)
{
return b * 3;
}
}
We can see, func1 and func2 has same body, except of middle of code: differences is FuncX2 and FuncX3. But, i can not do base abstract class because this code in the middle!
How can i do common abstraction? Please, do not change operations (3 times a++, 3 times b++) and do not change sequence
Thanks
Assuming your language of choice can pass around "pointers" to functions:
public class ToRefact
{
private int Func(int i, Func<int, int> f)
{
int a = i;
a++;
a++;
a++;
int b = f(a); //b = a * 2;
b++;
b++;
b++;
return a + b;
}
public int Func1(int i)
{
return Func(i, FuncX2);
}
public int Func2(int i)
{
return Func(i, FuncX3);
}
private int FuncX2(int b)
{
return b * 2;
}
private int FuncX3(int b)
{
return b * 3;
}
}
You could use template method (or even strategy pattern depending on real scenario) but in this simple case I would do something like this:
public class ToRefact
{
public int Func1(int i)
{
int a = FuncAdd3(i);
int b = FuncX2(a); //b = a * 2;
b = FuncAdd3(b);
return a + b; // Or more compact FuncAdd3(i) + FuncAdd3(FuncX2(FuncAdd3(i)))
}
public int Func2(int i)
{
int a = FuncAdd3(i);
int b = FuncX3(a); //b = a * 2;
b = FuncAdd3(b);
return a + b; // Or more compact FuncAdd3(i) + FuncAdd3(FuncX3(FuncAdd3(i)))
}
private int FuncAdd3(int b)
{
return b + 2;
}
private int FuncX2(int b)
{
return b * 2;
}
private int FuncX3(int b)
{
return b * 3;
}
}
Alternatively you could create a more modular and testable approach.
Create ICalculator interface like:
public interface ICalculator
{
int Calculate(int a);
}
And two concrete implementations
public class CalculatorX : ICalculator
{
public int Calculate(int a)
{
return a * 2;
}
}
public class CalculatorY : ICalculator
{
public int Calculate(int a)
{
return a * 3;
}
}
Then you would accept this as a parameter:
public int Func1(ICalculator calculator)
{
int a = i;
a++;
a++;
a++;
int b = calculator(a);
b++;
b++;
b++;
return a + b;
}
And call it like:
var calculatorX = new CalculatorX();
var result = Func1(calculatorX );
This makes it easy to replace implementations, mock them out, even inject them using your favorite IoC container. You also explicitly specify the contract of your method, so that if you ever have to add a new implementation, you know what to implement thanks to the interface.
public class ToRefact{
public int Func1(int i){
int a = i;
a = addThree(a);
int b = FuncX2(a); //b = a * 2;
b = addThree(b);
return a + b;
}
public int Func2(int i){
int a = i;
a = addThree(a);
int b = FuncX3(a); // b = a * 3;
b = addThree(b);
return a + b;
}
private int FuncX2(int b){
return b * 2;
}
private int FuncX3(int b){
return b * 3;
}
private int addThree(int x){
x++;
x++;
x++;
return x;
}
}
You can create a base class and apply the template method design pattern.
Example
note that I've used Delphi as that's easiest for me to write from memory but the intent is the same in every language that has virtual and abstract methods
TCustomRefact = class(TObject)
protected
function Calculate;
function Multiply(const Value: Integer); virtual; abstract;
end;
TRefact1 = class(TCustomRefact )
protected
function Multiply(const Value: Integer); override;
end;
TRefact2 = class(TCustomRefact )
protected
function Multiply(const Value: Integer); override;
end;

NullPointerException when object is instantiated

This is a homework, I would appreciate any kind of answer.
Im trying to figure out why i keep getting a NullPointerException when i call the equals method. I have instantiated the object if im not mistaken, but it still doesn't work.
Exception in thread "main" 8
java.lang.NullPointerException
at labbfyra.TextBuilder.equals(TextBuilder.java:69)
at labbfyra.SkapaOrd.main(SkapaOrd.java:17)
Is this the stacktrace?
public class TextBuilder {
private static class Node{
public char inChar;
public Node next;
public Node(char c, Node nästa){
inChar = c;
next = nästa;
}
}
private Node first = null;
private Node last = null;
public TextBuilder(){
first = null;
last = null;
}
public void append(String s){
int x = s.length();
for(int i=0;i<x;i++){
Node n = new Node(s.charAt(i),null);
if(first ==null){
first = n;
last = n;
}else{
last.next = n;
last = n;
}
}
}
public int ShowSize(){
int counter = 0;
Node n = first;
while(n!=null){
counter++;
n=n.next;
}
return counter;
}
public boolean equals(String s){
boolean eq = false;
int counter = 0;
char[] cArray = s.toCharArray();
char[] cArrayComp = new char[10];
Node n = first;
cArrayComp[counter] = n.inChar;
while(n!=null){
counter++;
n=n.next;
cArrayComp[counter] = n.inChar; //THIS IS LINE 69
}
if(cArrayComp==cArray){
eq = true;
}
else{
eq=false;
}
return eq;
}
}
In your while loop, you check that n is not null, but then you assign n.next to n just before accessing n. The problem is that you do not ensure that the assigned value (n.next) is not null.
At a quick glance, looks like the counter variable in your while loop is going past the 10 you set your cArrayComp size to. Perhaps the string parameter being passed is longer than 10 chars?
public boolean equals(String s){
boolean eq = false;
int counter = 0;
char[] cArray = s.toCharArray();
char[] cArrayComp = new char[10];
Node n = first;
while(n!=null){
System.out.println(counter);
cArrayComp[counter] = n.inChar;
System.out.println(cArrayComp[counter]);
System.out.println(n.inChar);
n=n.next;
counter++;
}
if(cArrayComp==cArray){
eq = true;
}
else{
eq=false;
}
return eq;
}
This is the corrected version, i found a bug in your loop. Just check my version. Works at 100%