Code seems out-of-scope, How to fix? (Simple Queue-ADT program) - java

Im not sure how to exactly explain this problem, but Im pretty sure Im making a very simple mistake that can be corrected quite quickly.
Also, I thought it would be more convenient if this was shown off as a screenshot. The first two tabs are my interface and error catching classes.
As you can see, the code for methods to use in my Queue ADT seems to be out of scope. So I can move on and complete this bit of coursework, can someone explain to me why it is out of scope?
Thanks for any help!

You declare those variables in main method, so only main local scope know them. Move the declaration to class level
public class QueueProgram {
private static int queuesize = 10;
public static void main(String[] args) {
}
}
Note I declared queuesize as static since the main uses it. Another option is to create getters and setters and call them with an instance of QueueProgram
public class QueueProgram {
private int queuesize = 10;
public int getQueuesize() {
return queuesize;
}
public void setQueuesize(int size) {
queuesize = size;
}
public static void main(String[] args) {
QueueProgram program = new QueueProgram();
program.getQueuesize(); // return 10;
program.setQueuesize(5);
program.getQueuesize(); // now it is 5;
}
}

Related

How can I avoid having to rely on an object of another class to make the methods in a different class work?

Maybe the title was confusing, so here's a snippet of what I'm trying to avoid:
public class Generator{
private static GUI userInterface;
public static boolean specialValidator(String specialEntryText)
{
if(entryValidator(specialEntryText))
{
int specialChars = Integer.parseInt(specialEntryText);
int maxPossible = Integer.parseInt(userInterface.getLength())-3;
if(specialChars < 1 || specialChars > maxPossible)
{
return false;
}
return true;
}
return false;
}
public static void main(String[] args) {
userInterface = new GUI();
}
}
My program runs and functions as intended (keep in mind there is more to it than this), but I don't know if what I've done here is considered bad practice or what the downsides of doing it this way are. If my main method was not in the Generator class, this would not work, which seems like a problem to me.
Also, is there a specific name for what I did here, too?
The main method is the entry point of the program, and it needs to be in a class. It does not need to be in the Generator class.
As long as there is access to the class that you want to use, you can call it from another class. In you case it is public so it should be OK.
If it is in another class it could be something like
package yourPackage;
public class Main {
public static void main (String[] args) {
Generator gen = new Generator ();
//
gen.specialValidator(..);
}
}
Many things jump out at me.
There seems to be a dependency on GUI in specialValidator which is producing a "tight coupling" - you can't use the method without GUI.
This doesn't seem to make sense to me. You want to focus on reducing this coupling/dependency by passing all the required information into the method directly, for example...
public class Generator {
public static boolean specialValidator(String specialEntryText, int length) {
if (entryValidator(specialEntryText)) {
int specialChars = Integer.parseInt(specialEntryText);
// Any resason we're not using the specialEntryText length?
int maxPossible = length - 3;
if (specialChars < 1 || specialChars > maxPossible) {
return false;
}
return true;
}
return false;
}
}
Now specialValidator doesn't care "how" the information is generated, only that the information is made available to it. This "decouples" the method and makes it more independent, meaning you can call it any way you like (it also supports "dependence injection" making it more testable 😝)
And now you can call it anyway you like, for example...
public class Main {
public static void main(String[] args) {
Generator.specialValidator("some text", 8);
}
}

A class with no modifier (default) cannot access a subclass declared as public? Java

I was just doing practice on Hackerrank since I'm still pretty new to Java (I'm only experienced with C and C++, with minimal Python/Matlab/C#). Basically we only had to write the "Checker class" below from scratch. However, I noticed that when I add public to the Checker class it results in runtime error. Does anyone know why? I couldn't find any answers on this online.
Also, yes, I know access modifiers restrictions on how much they can have access to the scope of classes, but it does not make sense to me on how a default class cannot access a public class's method. I'm assuming it is perhaps I'm implementing a parent class that's causing the problem? Here is the RE message I receive on Hackerrank:
Error: Main method not found in class Checker, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
If interested, link to the practice problem for reference: https://www.hackerrank.com/challenges/java-comparator/problem
import java.util.*;
// Write your Checker class here
class Checker implements Comparator<Player>{ //If I add "public" in front I get RE
#Override
public int compare(Player A, Player B){
if(A.score == B.score)
return A.name.compareTo(B.name);
else
return B.score - A.score;
// return A.compareTo(B);
}
}
class Player{
String name;
int score;
Player(String name, int score){
this.name = name;
this.score = score;
}
}
class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Player[] player = new Player[n];
Checker checker = new Checker();
for(int i = 0; i < n; i++){
player[i] = new Player(scan.next(), scan.nextInt());
}
scan.close();
Arrays.sort(player, checker);
for(int i = 0; i < player.length; i++){
System.out.printf("%s %s\n", player[i].name, player[i].score);
}
}
}
Interesting question but I've never used this in my whole career.
If there is no public class in the source file then main method can
lie in any class and we can give any name to the source file.
Source: https://dzone.com/articles/why-single-java-source-file-can-not-have-more-than
Because of the remark of #Andy Turner, I tested it a little bit further and indeed you can have a main method in other classes (other than the public one). It all depends on how you call it:
package sample;
class Problem {
public static void main(String[] args) {
System.out.println("main of Problem");
}
}
public class Solution {
public static void main(String[] args) {
System.out.println("main of Solution");
}
}
The source file name must be Solution.java as this is the public class but you can call both main methods:
> java sample.Solution
main of Solution
> java sample.Problem
main of Problem
You can still call sample.Problem when you remove the main method from Solution.
While it's against "customs", it is possible to do what you tried. However the main() method is present in the Solution class, so that's the one you have to run.
From command line you can do that easily:
javac Checker.java
java Solution
as Solution.class will be generated properly.
However if you use an IDE, which you are not very familiar with, you may encounter difficulties when trying to tell them to run a different .class file from the .java they have just compiled. In short: name the file as Solution.java.

Java program not sure where and how to execute main method whilst using static boolean

I've recently started using java and I am trying to make a program that checks to see if an array can be changed to ascending order by returning true/false.
That is the gist of it however I am having problems with the main class. The error I am getting is that the main method is not found in class.
public static boolean solution (int[] A){
int count = 0;
.......
.......
.......
for(int i=0; i<A.length; i++)
{
if(A[i] != B[i]) count++;
}
if(count > 2) return false;
return true;
}
}
Since I am doing this as my java summer homework I am abit confused as to where I should add the main method. I know it is supposed to be
public static void main (String args[])
However if I were to add that from the start of the code after the class I get errors. Is it because I cannot have
public static boolean and public static void main
in the same class?
Thanks.
You can have public static boolean and public static void main in the same class. A main method can be added anywhere within a class as long as you define it as its own standalone method, don't declare inside another method. For Example:
public class Example{
public void method1(){
....
}
public void method2(){
....
}
public static void main(String[] args){
....
}
}
oke if you are using an ide like intellij you must also configure which class has the main method in you project.
You CAN have a main method and other static methods in the same class. In fact you can have any type of method in the class. The reason your program cannot "find a main method" is because there either isn't one there, or your run configuration is off.
A java program starts, with some exceptions of the initializer blocks, at the main method. So you MUST have it in at least one class in your program.
From what it sounds like you want to test if the array is already in ascending order. Since all arrays that are not empty, can be sorted.
public class Example{
public static void main(String[] args){
int[] test = {1,2,3,4,5};
System.out.println(solution(test));
}
public static boolean solution (int[] a){
//returns true if in a
for (int i = 0; i < a.length-2; i++) {
if (a[i] > a[i + 1])
return false;
}
return true;
}
}
If your cannot find main method error continues. It is probably your run configuration
If you are getting an error, based on the way you phrased your question, it sounds like you have a method with the exact same method signature.
You can not have:
public static void main(String[] args)
{
}
public static boolean main(String[] args)
{
return false;
}
If this is what you have, you should probably rename the second method.

Return a Reference to a Class with Static Methods and Static Fields Without Instantiation

I want to create a wrapper class that calls static methods and member fields from a class that is provided by a library I am unable to view the code.
This is to avoid boilerplate setting code of the global member fields when I need to use a static method in a specific context.
I want to try to avoid creating wrapper methods for each static method.
My question:
Is it possible to return a class with static methods from a method to access just the static methods without instantiating it?
Code is below with comments in-line.
The code is used to demonstrate a change in a static value when the method getMath() is invoked.
I want to avoid the setting of the value before calling the static method.
StaticMath.setFirstNumber(1);
StaticMath.calc(1);
StaticMath.setFirstNumber(2);
StaticMath.calc(1);
I am using the Eclipse IDE and it comes up with Warnings, which I understand, but want to avoid.
I tried searching for something on this subject, so if anyone can provide a link I can close this.
public class Demo {
// Static Methods in a class library I don't have access to.
static class StaticMath {
private static int firstNum;
private StaticMath() {
}
public static int calc(int secondNum) {
return firstNum + secondNum;
}
public static void setFirstNumber(int firstNum) {
StaticMath.firstNum = firstNum;
}
}
// Concrete Class
static class MathBook {
private int firstNum;
public MathBook(int firstNum) {
this.firstNum = firstNum;
}
// Non-static method that gets the class with the static methods.
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
// I don't want to instantiate the class.
return new StaticMath();
}
}
public static void main(String... args) {
MathBook m1 = new MathBook(1);
MathBook m2 = new MathBook(2);
// I want to avoid the "static-access" warning.
// Answer is 2
System.out.println(String.valueOf(m1.getMath().calc(1)));
// Answer is 3
System.out.println(String.valueOf(m2.getMath().calc(1)));
}
}
I'd just wrap it to make for an atomic operation:
public static class MyMath{
public static synchronized int myCalc( int num1 , int num2 ){
StaticMath.setFirstNum(num1);
return StaticMath.calc(num2);
}
}
Drawback: You'll have to make sure, StaticMath is not used avoiding this "bridging" class.
Usage:
int result1 = MyMath.myCalc( 1, 1 );
int result1 = MyMath.myCalc( 2, 1 );
You shouldnt call a static method through an object reference. You should directly use class reference to call a static method like this:
StaticMath.calc(1)
But if you still need it for some reason, you can return null in getMath method, but you will still get warning in Eclipse:
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
return null;
}
I infer that question is not properly asked if the answer is not
StaticMath.calc(1)
Other issue you may be facing due to package visibility to static inner classes. Which is a design choice by the writer of Demo class. If you can mark your classes MathBook and StaticMath public then you can access them like below:
Demo.StaticMath.calc(1);

Making a static duplicate of non-static integer

For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.

Categories

Resources