Alright, so in my driver class, I want to call my arraylist from another class and print it out. However, when I attempt to call the method, it says that the variable cannot be resolved to a variable. Does anyone have any idea how I can get it "to be resolved".
Here's my code:
Driver:
public static void showing(){
OtherClass.initializeStrings();
System.out.println(OtherClass.showLists(mouseTypes));
}
Other Class:
static ArrayList <String> mouseTypes;
public static void initializeStrings(){ //initialize the strings outside the main
Strings = new ArrayList <String>();
Strings.add("goodbye");
Strings.add("hello");
Strings.add("hi");
}
public static void main(String[] args) {
OtherClass.initializeStrings();
Driver.showing();
}
public static void showLists(ArrayList list){
for (int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
Any help is appreciated.
Use .showLists(OtherClass.mouseTypes).
However, that breaks both the Single Responsibility Principle, and Encapsulation. Fix it.
Also, you have done a very bad copy-paste job, you have two main methods...
Related
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
ArrayList<String> original = new ArrayList<>(Arrays.asList("afd", "asdf", "aavdd", "sajf", "adnf", "afd", "fjfn"));
String find = "afd";
String replaceWith = "asd";
System.out.println(replaceIt(original, find, replaceWith));
}
public ArrayList<String> replaceIt(ArrayList<String> original, String find, String replaceWith){
ArrayList<String> newList = new ArrayList<String>();
for(int y = 0; y<original.size(); i++){
if(!original.get(y).equals(find))
newList.set(y, original.get(y));
newList.set(y, replaceWith);
}
original = newList;
return original;
}
}
How do i call the replaceIt method? I'm confused and I need to make it so it prints the output of that function. I'm so confused somebody please help.
public ArrayList<String> replaceIt() is an instance method, it is only called from Main instances/objects.
public static void main is a static method of class Main, static methods can’t access instance methods and instance variables directly.
Therefor, to call replaceIt() method from static main method, make replaceIt() static.
public static ArrayList<String> replaceIt(/*arguments*/){
//your code goes here
}
Having non-static method in Main is a little odd. It's not like you are going to construct new instances of Main (say, the same way you would construct new instances of a Person class).
These type of generic helpers/utils functions usually go into some sort Utils.java or Helpers.java class, and are declared as static in these files. This way you would be able to invoke: Utils.replaceIt(original, find, replaceWith));
Because replaceIt() is an instance method, you simply need to create an instance of the Main class to call it -
public static void main(String[] args) {
...
Main m = new Main();
System.out.println(m.replaceIt(original, find, replaceWith));
}
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.
This might be a really elementary question but it puzzles me at this stage of my Java learning.
I have got the following piece of code:
package com.soti84;
import java.util.ArrayList;
public class InvokeMethod {
public static void main(String[] args) {
ArrayList<String> exams= new ArrayList<String>();
exams.add("Java");
exams.add("C#");
}
}
If I move the line that instantiates the ArrayList object and the calls on that object outside the method, the line that creates the object is fine but the add() method calls on the object are not allowed. Why is that?
package com.soti84;
import java.util.ArrayList;
public class InvokeMethod {
ArrayList<String> exams= new ArrayList<String>();
exams.add("Java");
exams.add("C#");
public static void main(String[] args) {
}
}
Thanks.
You simply can't do that code outside of methods. If you wanted to do this you would need initializer block or static block.
public class InvokeMethod {
ArrayList<String> exams= new ArrayList<String>();
{
exams.add("Java");
exams.add("C#");
}
Now that block is gonna execute when you create an instance. If your variable was static, you could make that block static (just add static before that block). Static block is gonna execute when your class is initialized. Those blocks can be quite convenient when you need a populated static list/map. Ofcourse, everything that is convenient in programming is probably a bad practice, and same here, those blocks are frowned upon by some people, they can be quite dangerous and lead to hard-to-find bugs (mostly about the order of execution).
In the two examples you are trying to achieve two totally different things.
In the first example you declare the ArrayList inside the main method, therefore the scope of the list will be just this method. The enclosing class has absolutely no connection with that ArrayList.
In the second one you try to create a data member called exams in the class InvokeMethod. That means, every instance of this class will have its own list.
The addition of the elements does not work, because "out of the methods" only declaration and initialization can happen. To fix that, you can use an initialization block:
public class InvokeMethod {
ArrayList<String> exams = new ArrayList<String>();
{
exams.add("Java");
exams.add("C#");
}
public static void main(String[] args) {
}
}
or, the constructor of the class:
public class InvokeMethod {
ArrayList<String> exams = new ArrayList<String>();
public InvokeMethod() {
exams.add("Java");
exams.add("C#");
}
public static void main(String[] args) {
}
}
Note: You can also retrieve this list from main method via an instance of the InvokeMethod class:
public class InvokeMethod {
ArrayList<String> exams = new ArrayList<String>();
public InvokeMethod() {
exams.add("Java");
exams.add("C#");
}
public static void main(String[] args) {
InvokeMethod invokeMethod = new InvokeMethod();
System.out.println(invokeMethod.exams.toString());
invokeMethod.exams.add("Delphi");
System.out.println(invokeMethod.exams.toString());
}
}
will print
[Java, C#]
[Java, C#, Delphi]
That's because "you're calling it from outside the function/method"
ArrayList<String> exams= new ArrayList<String>();
The line above means you're declaring it as the property of an Object. which means you can only access it inside a Method.
If you're going to place the following in your Main
exams.add("Java");
exams.add("C#");
This should work just fine, although you declared the "exams" outside the method.
As per Java language specification, class body declaration has Instance Initializer but don't has method invocation. So in your example ArrayList<String> exams= new ArrayList<String>(); is allowed inside class body but not exams.add("Java");
JLS excerpt :
ClassBody:
{ ClassBodyDeclarationsopt }
ClassBodyDeclarations:
ClassBodyDeclaration
ClassBodyDeclarations ClassBodyDeclaration
ClassBodyDeclaration:
ClassMemberDeclaration
InstanceInitializer
StaticInitializer
ConstructorDeclaration
ClassMemberDeclaration:
FieldDeclaration
MethodDeclaration
ClassDeclaration
InterfaceDeclaration
;
I'm beginning at Java, so the thinking behind organizing my code so it's cohesive isn't really coming naturally yet. Essentially, I have an ArrayList that has a method that populates it, another that shuffles it, and then a tester program to see if that even worked. My problem is organizing it. From my experience methods can't really see what's in each other, so I have it organized like so:
Class
ArrayList (named al)
Tester Method
Shuffle Method
ArrayList Population Method
My trouble is thusly; how do I, in the tester method, make the ArrayList undergo the actions defined for it in the methods. I've worked with Constructors and Objects, but they don't really seem to apply at least is what I've done so far. I thought it would be something like
al.Shuffle();
But it threw errors all over the place. Does anyone have any insight?
EDIT: as requested, here's the code
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Deck{
ArrayList<String> al = new ArrayList<String>();
//test method
public void main(String[] args){
Scanner input = new Scanner(System.in);
al.Deck();
//didn't get any further, that threw a "cannot find symbol" error
}
}
private void Shuffle(){
Collections.shuffle(al);
}
private void Deck(){
al.add(0, "Ace of Spades");
//and this goes on for a deck of cards
}
}
In Your components, the class is the main component that holds the rest of your component, then the methods is a task or action that the class can do.
ArrayList is a data structure that holds a data with a specific structure. which the class can use it.
so you orginization could look like this:
class MyClass {
private ArrayList<String> list = new ArrayList<String>();
public static void main(String[] args) {//Tester Method is the main method, because the execution began from here
}
private void populate() {
//
}
private void shuffle() {
//
}
}
Define another class that extends ArrayList
public class MyArrayList extends ArrayList<Object> {
public MyArrayList(){
super();
}
public MyArrayList shuffle(MyArrayList mal){
Collections.shuffle(mal);
return mal;
}
}
And then define everything as MyArrayList. This will basically be the exact same class as ArrayList with extra functionality you want.
public class Deck {
static MyArrayList al = new MyArrayList();
//test method
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Deck();
al = al.shuffle(al);
//didn't get any further, that threw a "cannot find symbol" error
for(Object i : al)
System.out.println(i);
}
private static void Deck(){
al.add(0, "Ace of Spades");
al.add(1, "1");
al.add(2, "2");
al.add(3, "3");
//and this goes on for a deck of cards
}
}
This question already has answers here:
Is this a valid way to count instances of objects?
(2 answers)
Closed 9 years ago.
class Clasa {...}
class Test {
public static void main(String[] args){
Clasa x = new Clasa();
System.out.println(x.getNo());//displays 1
Clasa[] y = new Clasa[10];
for(int i = 0; i<4; i++)
y[i]=new Clasa();
System.out.println(y[0].getNo()); //displays 5
}
}
How can I replace those three dots, so GetNo() method call to return the number of instantiated objects of class Clasa. Test class should not be changed.
Add a static variable which acts as a counter and increment it inside the constructor and getNo returns the value of the static variable.
Static variable have their values kept across all instances of a class
class Clasa {
private static int nbInstances = 0;
public Clasa () {
nbInstances++;
}
public int getNo() {
return nbInstances;
}
}
I agree with Brian , on that the above code is not considering the GC. So I would like to replace your code with the below code snippet
package com.instance.main;
import com.instance.target.Clasa;
public class Test{
public static void main(String[] args) {
Clasa targetClass;
Object[] object=new Object[10];
for(int i=0;i<object.length;i++){
object[i]=new Clasa();
}
System.out.println("Number of Instantiate Object {Before Calling GC}: "+Clasa .getNumberOfInstatiateObj());
/* Here I am trying to deallocate the memory of Object at index no 9, so that GC called this unused object to deallocate it from memory*/
for(int i=0;i<object.length;i++){
if(i==8){
object[i]=object[i+1];
object[i+1]=null;
System.runFinalization();
System.gc();
}
}
}
}
just put the above code beneath the main method and also you have to modify your Clasa code from the below code
package com.instance.target;
class Clasa {
private static int nbInstances = 0;
public Clasa () {
nbInstances++;
}
public int getNo() {
return nbInstances;
}
public void finalize(){
nbInstances --;
System.out.println("Number of Instantiate Object {After Calling GC}: "+nbInstances );
}
}
After modifying your code by following the above steps , your code will give you your desired output.
Please let me correct if I am wrong some where.
Hi Dany I modified my code , so according to the above code ,you have to create your class under different package which written in the class code . And let me know if you are getting problem still.