How do I call a private method with arguments - java

I'm having an extremely difficult time getting a private method with arguments to be usable in my toString method but have no idea how to get the two methods to cooperate.
main class:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
//this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
int max = number;
for(int n = 1; n <= max; n++)
{
for(a = n; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
String last = a + "" + b + c;
}
}
}
}
}
}
}
return 1;
}
public String toString()
{
String output="";
output = output + this.greatestCommonFactor( ) + " \n";
return output;
}
}
and for cross-referencing my runner class:
import static java.lang.System.*;
import java.util.Scanner;
public class Lab11j
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String choice="";
do{
out.print("Enter the max number to use : ");
int big = keyboard.nextInt();
//instantiate a TriangleThree object
Triples triple = new Triples(big);
//call the toString method to print the triangle
out.println( triple );
System.out.print("Do you want to enter more data? ");
choice=keyboard.next();
}while(choice.equals("Y")||choice.equals("y"));
}
}
if you find you need clarification of this lab, here's a Google docs of the labsheet: https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM

The variables a, b & c can be used as local variables here. This would allow you to remove them from the argument list of greatestCommonFactor:
private int greatestCommonFactor() {
int a = 0;
int b = 0;
int c = 0;
...
as they are only required within the scope of the method.

Well, yeah. You're not passing anything to greatestCommonFactor. I'm not sure what you expected to happen in your toString() method when you didn't pass enough arguments to a method.

you need to pass them like
output = output + this.greatestCommonFactor(1,2,3) + " \n";
the thing is, unless you are passing parameters to toString, without this, this code seems very limited. Alternatively you need to set some fields on the class with what will be passed into your function.

Related

Finite State Machine Program invalid output

I am working on a project and my code isn't working not sure why. Given the test program and general class I need a program that satisfies the following logical regular epxression:
L1: For alphabet {a,b}, all strings that contain an odd number of a's and exactly one b.
Test input: aabaaaa, aaabaaaa, aabaaaab, baaaaaa, aaaaabaa
What it should be:
aabaaaa False
aaabaaaa True
aabaaaab false
baaaaaa false
aaaaabaa True
Program output:
(ture, true, true, false, true)
My Test program:
import java.util.Scanner;
// Test Finite State Machine Class
public class TestFSML1
{
public static void main(String[] args){
String A = "ab";
int[][] ST = {{1,3,0},
{1,2,1},
{2,2,2},
{3,3,3}};
int[] AS = {0,0,1,0};
Scanner in = new Scanner(System.in);
String inString;
boolean accept1 = false;
FSM FSM1 = new FSM(A, ST, AS);
// Input string is command line parameter
System.out.println(" Input Accepted:");
for(int i=0;i<args.length;i++) {
inString = args[i];
accept1 = FSM1.validString(inString);
System.out.printf("%10s%13s\n",inString, accept1);
}
} // end main
} // end class
FSM Class
// Finite State Machine Class
public class FSM
{
// Instance variables
public String alphabet;
public int stateTrans[][];
public int acceptState[];
private int cstate;
// Constructor function
public FSM(String A, int[][] ST, int[] AS)
{
int NSYMBOLS = A.length();
int NSTATES = AS.length;
// Alphabet
alphabet = "" + A;
// State transition table
stateTrans = new int[NSTATES][NSYMBOLS];
for(int r = 0; r < NSTATES; r++)
for(int c = 0; c < NSYMBOLS; c++)
stateTrans[r][c] = ST[r][c];
// Accept states
acceptState = new int[NSTATES];
for(int r = 0; r < NSTATES; r++)
acceptState[r] = AS[r];
// Start state
cstate = 0;
}
// Methods
public int getState()
{
return cstate;
}
public void setState(int state)
{
cstate = state;
return;
}
public int nextState(char symbol)
{
int nstate = -1;
int col = alphabet.indexOf(symbol);
if(col >= 0)
nstate = stateTrans[cstate][col];
return nstate;
}
public boolean accept(int state)
{
if(state < 0)
return false;
return (acceptState[state] != 0);
}
public boolean validString(String word)
{
cstate = 0;
for(int k = 0; k < word.length(); k++){
cstate = nextState(word.charAt(k));
System.out.print(cstate);
System.out.println(" " + word.charAt(k));
if(cstate < 0)
return false;
}
return accept(cstate);
}
} // end class
Thanks!
Here's a simple method I typed up to perform the task you wanted.
public static boolean validWord(String s) {
int aCounter = 0;
int bCounter = 0;
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if ((int) c == (int) 'a') {
aCounter++;
} else {
bCounter++;
}
}
return (aCounter % 2 == 1 && bCounter == 1);
}
I had trouble understanding how you were implementing your method, and I think it could be much simpler. I'm sure the instance variables you included in the FSM class serve some other use, but I you don't really need any of them to analyze the string. Just use something like this, it should be easy enough to integrate into your code as all it takes is the string. Hope this helps!

calculating fibonacci numbers in java

I am trying to display the first 20 fibbonacci numbers using the model view controller method in java. However the output that I am getting is only the last number(the first 19 are not displaying) if anyone is able to look through my code and point out where im going wrong that would be awesome :)
public class FibonacciModel {
public String fibModel(int a, int b, int c, int count){
String result = "";
//int c;
while(count!=20) // if you want first 100 fibonacci numbers then change 20 to 100 accordingly
{
c=a+b;
count++;
result = c + " ";
a=b;
b=c;
}
return result;
}
}
public class FibonacciController {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 1;
int b = 1;
int count = 2;
int c = 0;
FibonacciModel Model = new FibonacciModel();
FibonacciView View = new FibonacciView();
View.say(Model.fibModel(a, b, c, count));
}
}
public class FibonacciView {
public < T > void say( T word ){
System.out.print(word);
}
}
You're overwriting your result variable. Try result = result + c + " "; or result += c + " ";
Check this out :)
public static void getFibbonacci(int n){
int total = 0;
int prev = 1;
for (int x=1; x<n; x++){
total = total + prev;
prev = total - prev;
System.out.println(total);
}
}
public class fibbo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a;
System.out.println("Enter the number");
a = sc.nextInt();
int first = 0;
int second = 1;
int third;
System.out.print("Fibbonacci series is= ");
System.out.print("\t" + first + "\t" + second + "\t");
for (int i = 0; i < a - 2; i++) {
third = first + second;
first = second;
second = third;
System.out.print(third + "\t");
}
}

how to use recursion for converting String to int

I want to convert String input into int using recursion. This is the code I came up with but if my input is 123456 it only returns 124. If I enter 1234567, it gives an error.
import java.util.*;
public class Problem1 {
static int x =0;
static int counter = 0;
//input
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String s= scan.nextLine();
System.out.println(recursive(s));
}
//recursive method
public static int recursive(String s){
if(s.length()==1){
x=(x*10)+ Integer.parseInt(s.substring(0,1));
return x;
}
else{
x = (x*10)+Integer.parseInt(s.substring(0,1));
counter++;
return recursive(s.substring(counter,s.length()-1));
}
}
}
import java.util.Scanner;
public class Problem1 {
static int x = 0;
static int counter = 0;
// input
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println(recursive(s));
}
// recursive method
public static int recursive(String s) {
if (s.length() == 1) {
x = (x * 10) + Integer.parseInt(s.substring(0, 1));
return x;
} else {
x = (x * 10) + Integer.parseInt(s.substring(0, 1));
counter++;
return recursive(s.substring(1, s.length()));
}
}
}
Look at your static counter variable. You are incrementing it every time. But you only want to have the substring starting at 1 (so cut off the first "letter").
So instead of using:
counter++;
return recursive(s.substring(counter,s.length()-1));
consider using:
return recursive(s.substring(1)); // you even don't really need the length
Because the String s parameter is as follows:
1st call: 1234567
2nd call: 234567
3rd call: 34567
4th call: 4567
...
So, you only have to cut off the first letter.
Btw: your sample "project" is a really funny one ;)
A few notes to start:
If you're doing recursion, you probably don't want to use a member variable. It's not wrong to do so, but not really typical of the pattern (your x variable).
It's often handy to pass in state through the recursion, although you wouldn't have to (that is, current value of x).
Your case is a little odd because you have to change your current parse value for every sub-parse (shifting by 10 each time); makes it a little more complicated.
If you are going to keep x as a member variable (which does seem to make sense in this case), you don't need to return anything from recursive.
Can you really not just use Integer.parseInt()?
Code could be much more simple, something like:
void recursive (String s)
{
if (s.length() == 0) return 0;
x = x * 10 + Integer.parseInt(s.substring(0, 1));
recursive(s.substring(1));
}
recursion("1234567", 0, 1)
The above code will turn the string "1234567" into an int using recursion. You must pass the string you want to convert, and then 0 and 1.
public static int recursion(String s, int result, int place) {
result += place * Integer.parseInt(s.charAt(s.length() - 1) + "");
if(s.length() == 1) {
return result;
}
else {
return recursion(s.substring(0, s.length() - 1), result, place * 10);
}
}
public static int computeStr(String str) {
if (str.equals("")) {
return 0;
}
int x = 1;
for (int i = 0; i < str.length() - 1; i++) {
x = x * 10;
}
x = x * Integer.parseInt(str.substring(0, 1));
return x + computeStr(str.substring(1));
}
For example: "2432" is (2 * 1000) + (4 * 100) + (3*10) + (2*1) = 2432
this algorithm begins at first position (2) from 2432
I know its kind of a late response but you could try something like this :-
private static int stringToInt(String string) {
if (string.length() == 0) {
return 0;
}
int rv;
int num = string.charAt(string.length() - 1) - '0';
String restOfTheString = string.substring(0, string.length() - 1);
rv = stringToInt(restOfTheString) * 10 + num;
return rv;
}
Try something like this:
Subtracting the ASCII code of the '0' character from your character returns an integer:
public class StringRecursion {
static int counter = 0;
public static void main(String[] args) {
System.out.println(convertStringToInt("123456"));
}
public static int convertStringToInt(String input) {
if (input.length() == 1)
return input.charAt(0) - '0';
int value = convertStringToInt(input.substring(0, input.length() - 1));
counter++;
return value * 10 + input.charAt(counter) - '0';
}
}
Try it like this :
public static int conStrToInt(String str) {
if(str.length()==0)
{
return 0;
}
char cc = str.charAt(0);
String ros = str.substring(1);
int factor=1;
for(int i=0;i<str.length()-1;i++)
factor*=10;
factor=factor*(cc-'0');
return factor+conStrToInt(ros);
}

Method not working?

Updated code:
import java.util.*;
public class Main {
/**
* #param args
*/
static int[] C;
static int[] D;
static String P;
public static void main(String[] args) {
C = new int[10];
D = new int[10];
getNumber();
}
private static void getNumber() {
System.out
.println("Enter your first number with spaces in between digits.");
Scanner S = new Scanner(System.in);
String O = S.nextLine();
String[] A = new String[10];
A = O.split(" ");
for (int X = 0; A.length > X; X++) {
C[X] = toNumber(A[X]);
}
String P = S.nextLine();
String[] B = new String[10];
B = P.split(" ");
for (int Y = 0; B.length > Y; Y++) {
C[Y] = toNumber(A[Y]);
}
System.out.print(C[0]);
remainders();
}
private static void remainders() {
for (int A = 0; C.length > A; A++) {
if (D[1] * C[A] >= 10) {
Integer B = new Integer(D[1] * C[A]);
Character E = B.toString().charAt(0);
P.concat(E.toString());
}
}
for (int A = 0; C.length > A; A++) {
if (D[0] * C[A] >= 10) {
Integer B = new Integer(D[1] * C[A]);
Character E = B.toString().charAt(0);
P.concat(E.toString());
}
}
System.out.print(P);
}
private static int toNumber(String string) {
if (string.equals("0")) {
return 0;
} else if (string.equals("1")) {
return 1;
} else if (string.equals("2")) {
return 2;
} else if (string.equals("3")) {
return 3;
} else if (string.equals("4")) {
return 4;
} else if (string.equals("5")) {
return 5;
} else if (string.equals("6")) {
return 6;
} else if (string.equals("7")) {
return 7;
} else if (string.equals("8")) {
return 8;
} else if (string.equals("9")) {
return 9;
} else {
return 0;
}
}
}
For some reason, the last thing it prints is null. I am pretty sure the problem is the toNumber method, but I can't figure out what's wrong. If there are other problems with the code other than this, please let me know. Please help.
Edit: Problem seems to be with remainder method, please help
Use the string.equals(n) method to test if string is n
String constants are compared this way: "0".equals(string). String literals are actual String objects and You can call any String method on them. And you should prefer to call methods on constants, because it's guaranteed they exists, whereas variables can be null.
You don't need to reinvent the wheel. Java has rich SDK.
Simply use
int x = Integer.valueOf(a[X]);
If you want only numbers 0-9, then simply test
if (0 <= x && x <= 9) {
//valid continue
} else {
//invalid state handling
}

How to turn static methods into non-static. Small explanation/examples related to java oop

I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code.
The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.)
The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code.
Thanks in advance for any hints.
import java.util.Scanner;
/**
*
* #author
*/
public class NumberArray2{
public static int[] table() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
int[] tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
return tab;
}
static public void output(int [] tab){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void max(int [] tab){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
//return maxNum;
System.out.println(maxNum);
}
static public void divide(int [] tab){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void average(int [] tab){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int[] inputTable = table();
//int s = table();
System.out.println("Written numbers:");
output(inputTable);
System.out.println("Largest number: ");
max(inputTable);
System.out.println("All numbers that can be divided by three: ");
divide(inputTable);
System.out.println("Average value: ");
average(inputTable);
System.out.println("Prime numbers: ");
isPrime(inputTable);
}
}
Second code
public class Complex {
// datové složky
public double re;
public double im;
// konstruktory
public Complex() {
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public double abs() {
return Math.sqrt(re * re + im * im);
}
public Complex plus(Complex c) {
return new Complex(re + c.re, im + c.im);
}
public Complex minus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public String toString() {
return "[" + re + ", " + im + "]";
}
}
Let's start with a simple example:
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(personA.getFullName());
System.out.println(personB.getFullName());
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public String getFullName()
{
return (lastName + ", " + firstName);
}
}
I am going to make a minor change to the getFullName method now:
public String getFullName()
{
return (this.lastName + ", " + this.firstName);
}
Notice the "this." that I now use.
The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(Person.getFullName(personA));
System.out.println(Person.getFullName(personB));
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public static String getFullName(final Person thisx)
{
return (thisx.lastName + ", " + thisx.firstName);
}
}
So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.
Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.
First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:
Car
properties - engine, gearbox, chasis
methods - ignite, run, brake
The ignite method depends on the engine field.
Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations.
Take a look at java.lang.Math - it's methods are static for that precise reason.
The program below has been coded by making the methods non-static.
import java.util.Scanner;
public class NumberArray2{
private int tab[]; // Now table becomes an instance variable.
// allocation and initilization of the table now happens in the constructor.
public NumberArray2() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
}
public void output(){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
public void max(){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
System.out.println(maxNum);
}
public void divide(){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
public void average(){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public void isPrime() {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// instatiate the class.
NumberArray2 obj = new NumberArray2();
System.out.println("Written numbers:");
obj.output(); // call the methods on the object..no need to pass table anymore.
System.out.println("Largest number: ");
obj.max();
System.out.println("All numbers that can be divided by three: ");
obj.divide();
System.out.println("Average value: ");
obj.average();
System.out.println("Prime numbers: ");
obj.isPrime();
}
}
Changes made:
int tab[] has now been made an
instance variable.
allocation and initialization of the
table happens in the constructor.
Since this must happen for every
instantiated object, it is better to
keep this in a constructor.
The methods need not be called with
table as an argument as all methods
have full access to the instance
variable(table in this case)
The methods have now been made
non-static, so they cannot be called
using the class name, instead we need
to instantiate the class to create an
object and then call the methods on
that object using the obj.method()
syntax.
It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)
Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {
In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.
Before:
NumberArray2.isPrimeNum(11);
After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class
numberarray2.isPrimeNum(11); // Call a method of the given object
In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object).
When you deside to not include a constructor the java compilator will add on for you. It would look like this:
public NumberArray2(){};
Hope this helps. And you are right, this looks like homework :D
I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).
The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.
I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.
Person john = new Person("John",18);
Person alice = new Person("Alice",17);
if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"
static is used when you want to retain a value of something across all objects of the same class.
class Person{
static int amountOfPeopleCreated;
public Person(string name, int age){
amountOfPeopleCreated++;
setName(name);
setAge(age);
}
...
}
so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.

Categories