Importing ArrayList without IDE package - java

How can I count my messages? I have both classes in the same folder and I compile them in the terminal. I don't want to install an IDE and create a package.
My counting class:
import java.util.ArrayList;
public class countMessages{
public static void main(String args[]){
int count = messages.size();
}
}
My message containing class:
import java.util.ArrayList;
public class SampleDataBase {
public static ArrayList<String> messages;
static {
messages = new ArrayList<String>(12);
messages.add("A "+"message "+"with "+"pineapples.");
messages.add("A "+"message "+"with "+"grapes.");
messages.add("A "+"message "+"with "+"watermelons.");
}
}

To create a package just create a folder (name it for example myPackage) and put both classes in it. Also include a first line in both class files: package myPackage;. Remember to name the class files with the names of the classes.
To make your example work just change messages.size(); to SampleDataBase.messages.size();.
And you really should name the class CountMessages with a capital letter.

It's unclear what you are trying to do but what I think you are looking for is a main static method(?)
import java.util.ArrayList;
public class SampleDataBase
{
public static void main(String[] args)
{
ArrayList<String> messages = new ArrayList<>();
messages.Add("things...");
for(String message : messages)
{
System.out.println(message);
}
System.out.println("The number of messages is : " + messages.size());
}
}
in the terminal, to use:
Compile javac *.java
Execute java SampleDataBase

If you want to keep two classes, use this on your test class(that contains main method).
public class countMessages{
public static void main(String args[]){
// You must instantiate the other class
SampleDataBase sdb = new SampleDataBase();
// here you will get the total messages in your arrayList
int count = sdb.messages.size();
}

Related

Comparing an array to a single string output using assertEquals in Java

So I would like to create a simple code that greets people according to the input.
The difficulity I have that I have no idea how to compare a simple string with an array, using arrayEquals (or any equivalent).
This is the way I have created the code - according to a previous project:
Test file:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class test {
#Test
public void ShouldGreet() {
assertEquals("Hello, my friend.", new GreetPeople().greeter(""));
assertEquals("Hello, Bob.", new GreetPeople().greeter("Bob"));
}
}
Actual code:
import java.util.Arrays;
public class GreetPeople {
public String greeter(String[] names) {
if (Arrays.stream(names).count() == 1) {
return("Hello, " + names + ".");
}
return("Hello, my friend.");
}
}
Any kind of help is well appreciated!
The first patameter of greeter is an array:
assertEquals("Hello, my friend.", new GreetPeople().greeter(new String[]{""}));
assertEquals("Hello, Bob.", new GreetPeople().greeter(new String[]{"Bob"}));

How would I go about using getters and setters for an ArrayList in Java? Here is what I have. This code is not working. what is the reason?

I need to set some items into the array via setters and also I need to get those details by using getters to another. Problem is it is gives me a Null. What is the problem here? Can some one help me?
import java.util.ArrayList;
public class arrayClass {
private ArrayList<String> sampleArrays;
public ArrayList<String> getSampleArrays() {
return sampleArrays;
}
public void setSampleArrays(ArrayList<String> sampleArrays) {
this.sampleArrays = sampleArrays;
}
}
Second Class
import java.lang.reflect.Array;
import java.util.ArrayList;
public class FirstPage {
public static void main(String args[]) {
arrayClass ac = new arrayClass();
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("First");
arrayList.add("Second");
arrayList.add("Thired");
arrayList.add("Fourth");
ac.setSampleArrays(arrayList);
Second second = new Second();
second.testMeth();
}
}
Third Class
import java.util.ArrayList;
public class Second {
public void testMeth() {
arrayClass ar = new arrayClass();
ArrayList<String> secondArray = ar.getSampleArrays();
System.out.println(secondArray.get(0));
}
}
In main your arrayClass ac = new arrayClass(); is limited in scope to this method. It is not a field. In testMeth arrayClass ar = new arrayClass(); is also a local variable, not a field. They are not at all related to each other.
Furthermore, just because you declare a variable in one class, does not mean that another completely different class will be able to see it.
FirstPage::arrayClass
is not automatically accessible as
Second::arrayClass
To fix
You could create a constrcutor Second second = new Second(ar); and set this value to the field in Second
A valid solution has been shown by Scary Wombat. Another way you can get around this is to make testMeth take an ArrayList<String> as a parameter:
import java.util.ArrayList;
public class Second {
public void testMeth(ArrayList<String> array) {
ArrayList<String> secondArray = array;
System.out.println(secondArray.get(0));
}
}
Accordingly, the main function should become:
public static void main(String args[]) {
arrayClass ac = new arrayClass();
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("First");
arrayList.add("Second");
arrayList.add("Thired");
arrayList.add("Fourth");
ac.setSampleArrays(arrayList);
Second second = new Second();
second.testMeth(ac.getSampleArrays());
}

java : Identifier expected error when calling a void method from another class

So I've been trying to create a set of cards by defining them through their value then create one class per color. I have a method for creating a list of 13 cards from 2 to ace:
package test;
import java.util.*;
public class Cartes {
void liste_cartes(){
ArrayList liste_cartes = new ArrayList();
for(int i=2; i<15; i++) {
liste_cartes.add(i);
}
}
}
I've tried using this method in my color class !
package test;
import java.util.*;
public class Coeur {
Cartes cartes = new Cartes();
cartes.liste_cartes();
}
However I'm getting an <identifier expected> error on cartes.liste_cartes();. Relatively new to Java here, so any help is much appreciated.
For Java program,JVM first looks for main() to run the program. Try writing this:-
public class Coeur {
public static void main(String[] args) {
Cartes cartes = new Cartes();
cartes.liste_cartes();
}
}
Wrap cartes.liste_cartes(); in a method, like
public void dummyMethod(){ //should probably be your main method, if in your main class
cartes.liste_cartes();
}
Also, your ArrayList is of raw type. Make use of generics.
ArrayList<Integer> liste_cartes = new ArrayList<Integer>();

Error: Main method not found in class MovieDatabase [duplicate]

This question already has answers here:
Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) [duplicate]
(5 answers)
Closed 8 years ago.
Error: Main method not found in class MovieDatabase, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
import java.io.FileInputStream;
import java.util.Scanner;
import java.util.Arrays;
public class MovieDatabase {
private int[] analysis;
//creating the contructor
public MovieDatabase(String file){
analysis = new int[2015];
this.load(file);
}
//uses the load(String file) method from downstairs to do all of the work
public void load(String file){
Scanner theScanner = null;
try{
//inputing the into the scanner
theScanner = new Scanner(new FileInputStream(file));
}
catch(Exception ex){
ex.printStackTrace();
}
// as long as the scanner has another line
while(theScanner.hasNextLine())
{
String Line = theScanner.nextLine();
//make an array called split and allocated different elements based on a seperation of ##
String split[] = Line.split("##");
int year = Integer.valueOf(split[1]);
analysis[year] ++;
}
}
//print out the array in the synchronous format
public void print(){
System.out.printf("%1$-30s %2$10s %3$10s %4$10s ", "Year", "Occurances", "", "");
//go through the array
for (int i =0;i < analysis.length ;i++ ) {
if(analysis[i] >0){
for (int j =i;j < analysis.length ;i++ ){
System.out.printf("%1$-30s %2$10s %3$10s %4$10s ", j, analysis[j], "", "");
}
}
}
}
}
How do I fix this error message?
Ive read other similar questions but just say to make the classes public. Mine are public.
main() method in Java is an standard method which is used by JVM to start execution of any Java program. main method is referred as entry point of Java application which is true in case of core java application
You have missed it. Add following main() method
public static void main(String[] args) {
MovieDatabase db = new MovieDatabase("file/path/goes/here");
db.print();
}
In the Java programming language, every application must contain a
main method whose signature is:
public static void main(String[] args)
As the error suggests, if its non FX project, just define something like:
public static void main(String args[]) {
...
}
Or else change you class definition so it extends Application, something like:
public class MovieDatabase extends Application
To invoke any application JVM need main() method, and which should have following access specifiers and modifiers,
public static void main(String args[])
public - It should be accessible to all
static - JVM not able to create instance of your class so method should be static
void - method not returning anything
For each java application main method is entry point, so your application should have atleast one main method to start execution of application.
It's because you have forgot to add the main method. The error clearly says:
please define the main method as: public static void main(String[]
args)
So add the main:
public static void main(String[] args) {
MovieDatabase m = new MovieDatabase("Your File Path");
m.print();
}

Package that calls different classes when given input to?

I have taken all of my classes from my intro to java college in highschool class, and put them into a package called gameChoices. I then made a class that would call these classes when the user asks for them, this is called whichGame. I've imported the classes I want called using import gameChoices."whatever game it is";. How do I call these classes in whichGame? I also have them all as public static main(string [] args), which ones shouldn't have that(I think it's just whichGame that should..)? And what would I put instead? Thanks for helping a newbie out :)
The simplest way to do it is probably to set up a big if/then statement.
if(input.equals("t"))
thisOne.start();
else if(input.equals("a"))
anotherOne.start();
else if(input.equals("y"))
yetAnotherOne.start();
And so on. Might be a pain if you have a lot of classes, or if they start with the same letter.
Not sure exactly what you want to achieve, but if you need to access a class by its name you can try Class.forName() and check for exceptions thrown (particularly, ClassNotFoundException).
Using case-insensitive String equality for the name check, if would allow you to access any existing class of your ClassLoader through reflection.
Edit
Here's your main class:
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Main {
// initializes your map of letter->game class
private static final Map<String, Class<?>> GAMES = new HashMap<String, Class<?>>();
// constant name of main method for your games
private static final String MAIN_METHOD_NAME = "main";
// add your games
static {
GAMES.put("c", Chess.class);
GAMES.put("d", Doom.class);
// TODO moar gamez
}
public static void main(String[] args) {
try {
// prompts the user
System.out.println("Enter the game's name or starting letter: ");
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
// gets the response
String input = br.readLine();
br.close();
// iterates over your games' first letters
for (String gameName : GAMES.keySet()) {
// the input starts with one game's first letter...
if (gameName.startsWith(input.toLowerCase())) {
// gets the class
GAMES.get(gameName)
// gets its main method (typical signature is String[] args)
.getMethod(MAIN_METHOD_NAME, String[].class)
// invokes its main method with no arguments
.invoke((Object) null, (Object) null);
}
}
// handles any disaster
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Now here are two "game" classes:
package test;
public class Chess {
public static void main(String[] args) {
System.out.println("You've chosen Chess!");
}
}
... and...
package test;
public class Doom {
public static void main(String[] args) {
System.out.println("You've chosen Doom!");
}
}
Now set your "Main" class as your... main class.
When you launch the application, it will query you for an initial letter.
If you choose "c" or "d", it will print out: "You've chosen [Chess/Doom]!"
I hope this helps you getting started.

Categories