I have a program to find pythagorean triples. in it, i have an object that needs to be used to call methods. Said object is broken. Errors are " The method Triples(int) is undefined for the type Triples" and "The method greatesCommonFactor() is undefined for the type Triples" mind you, not everything in Triples does useful stuff atm. It isn't completely finished yet.
public class TriplesRunner
{
public static void main(String args[])
{
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the natural number :: ");
number=keyboard.nextInt();
Triples test = new Triples();
test.Triples(number);
test.greatestCommonFactor(number);
System.out.println(test.toString());
}
}
public class Triples
{
public int number;
public Triples(int num)
{
setNum(number);
}
public void setNum(int num)
{
int a = 0;
int b = 0;
int c = 0;
}
public int greatestCommonFactor(int a, int b, int c)
{
int max = 0;
for(a=1; a<=number-2; a++)
{
for(b=a+1; b<=number-1; b++)
{
for(c=b+1; c<=number; c++)
{
if(a*a + b*b == c*c);
}
}
}
return 1;
}
public String toString()
{
String output="";
output+="a + b + c";
return output+"\n";
}
}
you are trying to call the constructor as a method,
Change this part:
Triples test = new Triples();
test.Triples(number);
to
Triples.test = new Triples(number);
Triples isn't a method - it's your constructor, meaning it's invoked with the new operator:
Triples test = new Triples(number);
greatestCommonFactor is not defined properly. It currently takes three int arguments, instead of taking none and using Triples' data members:
public int greatestCommonFactor()
Related
I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to call the toh method from my main class(Driver). When I make the call it gives me a null pointer exception. How can I call the toh method in Hanoi from the driver class? When I combine the classes into one it works fine but I need them to be two separate classes. Also, I included the global variables I am using in both classes is that necessary? Any help is welcome. Thanks!
public class Hanoi {
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
public static void display()
{
System.out.println("T"+cycle + " Pillar 1 | Pillar 2 | Pillar 3");
System.out.println("-------------------------------------");
for(int i = N - 1; i >= 0; i--)
{
String d1 = " ", d2 = " ", d3 = " ";
try
{
d1 = String.valueOf(tower[1].get(i));
}
catch (Exception e){
}
try
{
d2 = String.valueOf(tower[2].get(i));
}
catch(Exception e){
}
try
{
d3 = String.valueOf(tower[3].get(i));
}
catch (Exception e){
}
System.out.println(" "+d1+" | "+d2+" | "+d3);
}
System.out.println("\n");
cycle++;
}
}
Main class(driver):
public class Driver{
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
int num = 0;
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<>();
tower[2] = new Stack<>();
tower[3] = new Stack<>();
/* Accepting number of disks */
while(num <=0){
System.out.println("Enter number of disks(greater than 0):");
num = scan.nextInt();
}
N = num;
Hanoi.toh(num);
}
}
You are initializing your tower array inside your Driver class, however, you have not initialized it in your Hanoi class.
As I said in my comment, please do not write global variables twice, in different classes. This is because the different classes DO NOT share the same global variables. (when we say global variable, we mean that they are global to the Driver class only. To access those variables, use the dot operator)
For example, get rid of the N cycle and tower declarations from your Hanoi class
Then access those variables using the dot operator.
tower would become Driver.tower and N would become Driver.N and so forth.
Note: this only works if your Driver class is static, otherwise you would need to access it as an object attribute.
Try to initialize the tower array, something like this:
public static Stack<Integer>[] tower;
public static void toh( int n )
{
tower = new Stack[n];
for ( int d = 0 ; d < n ; d++ )
{
tower[d]=new Stack<>();
}
delete duplicated static values in a class (either Driver or Hanoi)
then in the class that no longer has the static values and add that class to the beginning of all the missing classes.
Ex:
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public static int MyVar;
public void bMethod(){
++MyVar;
}
}
↓ to ↓
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public void bMethod(){
++A.MyVar;
}
}
package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}
Is there a way I can sort my teams arraylist by the number of points that team has, so whichever team has the highest points is first, and so on, please dont use comperator, because I don't understand how to use that, here is my code:
import java.util.*;
import java.io.*;
class team {
public int teamNum;
public int points = 0;
public team(int x) {
this.teamNum = x;
}
public team(int x,int y) {
this.teamNum = x;
this.points = y;
}
}
public class Problem9 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("Test9.txt"));
ArrayList<team> teams = new ArrayList<>();
int counter=0;
while(in.hasNextLine()) {
boolean found = false;
String[] split = in.nextLine().split(" ");
int n1 = Integer.parseInt(split[0]);
int n2 = Integer.parseInt(split[1]);
if (!(n1 == 0 && n2 == 0)) {
if (counter<1) teams.add(new team(n1));
for (int i=0; i<teams.size(); i++) {
if (teams.get(i).teamNum == n1) {
teams.get(i).points+=n2;
found = true;
}
}
if (!found) {
teams.add(new team(n1, n2));
}
}
counter++;
}
for (int k=0; k<teams.size(); k++)
System.out.println(teams.get(k).teamNum + " " + teams.get(k).points);
}
}
There are 2 ways to do sorting on a custom data type :
use Comparator
use Comparable
Using Comparable
class team implements Comparable<team> {
public int teamNum;
public int points = 0;
public team(int x) {
this.teamNum = x;
}
public team(int x,int y) {
this.teamNum = x;
this.points = y;
}
public int compareTo(team t1){
return t1.points - this.points;
}
}
Now use Collections.sort() on the arraylist, which would sort it for you.
Agreed with #sschale, you can't run away from certain methods or libraries just because you do not know how to use it and hence do not want to use it. To help you out I will give you a much simplified form of comparator implementation here:
//Place this between class team and public class Problem9
static class rankcomparator implements Comparator<Team> {
#Override //need to override
public int compare(Team lhs, Team rhs) {
return -compare(lhs.points, rhs.points); //if descending order
//return compare(lhs.points, rhs.points); //if ascending order
}
}
public static void main(String[] args) throws IOException {
//Add this code inside public class Problem9 ...
Collections.sort(teams, new rankcomparator());
}
You really need to learn how a Comparator and the Comparable interface work. I recommend this tutorial on Comparator usage and this tutorial on using natural ordering through the Comparable interface.
Concerning the issue at hand: just add a getScore method to your Team class:
int getScore(){ return this.score;}
Then call:
teams.sort(Comparator.comparing(Team::getScore));
You can reverse the order using:
teams.sort(Comparator.comparing(Team::getScore).reversed());
One last thing: it is convention that class names begin with a capital letter. You should refactor your team class to be Team.
You can also just do that without a comparator because you just have Integers to compare to each other:
teams.sort((Team t1, Team t2) -> (Integer.compare(t1.getScore(), t2.getScore())));
Collections.reverse(teams);
import java.util.*;
class Series {
public static void main(String args[]) {
int a, d, n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first term of A.P");
a = sc.nextInt();
System.out.println("Enter difference");
d = sc.nextInt();
System.out.println("Enter the number of terms");
n = sc.nextInt();
Series s1 = new Series();
s1.lastTerm();
}
public int lastTerm(int s) {
int a, d, n;
s = a + (n - 1) * d;
return s;
}
}
The error I'm getting is:
Series.java:15: error: method lastTerm in class Series cannot be applied to given types;
s1.lastTerm();
^
required: int
found: no arguments
reason: actual and formal argument lists differ in length
How can I fix this?
In your code:
Series s1 = new Series();
s1.lastTerm();
You're calling the lastTerm() function. You declared your function to pass an int but in your s1.lastTerm() you're not passing any integer value to it. That's why the compiler is complaining.
This should be how you solve your problem:
public int lastTerm(int a, int d, int n)
{
return a+(n-1)*d;
}
and call it as follows:
s1.lastTerm(a, d, n);
Pass all required parameters to the method
public int lastTerm(int firstTerm, int difference, int termCount) {
return firstTerm + (termCount - 1) * difference;
}