Testing a Java Applet with JUnit - java

I'm completely new to Java and I'm trying to set up a test for it. But how do I call a method from the test class?
Right now I'm trying with a public method, and making a new instance of the class Hangman, but the call to the method doesn't work.
Hangman.java:
public class Hangman extends Applet implements ActionListener{
public String[] getWordArray(){
/* Enter the wordslist, separated by a | here: */
String str = "computer|"
+ "radio|"
+ "calculator|"
+ "teacher|"
+ "bureau|"
+ "police|"
+ "geometry|"
+ "president";
String[] temp;
/* delimiter */
String delimiter = "\\|";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
return temp;
}
}
HangmanTest.java:
public class HangmanTest {
Hangman hangman = new Hangman();
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public void testGetWordArray() {
int expected = 8;
int actual = hangman.getWordArray().length();
Assert.assertEquals(expected, actual);
}
}

You have a syntax error. It is int actual = hangman.getWordArray().length;, not int actual = hangman.getWordArray().length();. The length of array is an attribute, not a method. All other datastructures (like ArrayList) have a method for this.

Related

Java For each loop every instance from class

I start with OOP
And i have following problem:
I made a new class
Then I made ainstance from this class
Now, for every instance I want to do something
I tried it with a for each loop but it doesn't work...
There are some syntax problems
This is the class:
package main;
public class command
{
String call;
String execute;
}
And this from the Main class:
private static void load() {
command greeting = new command();
greeting.call = "hello";
greeting.execute = "Hello Sir";
for (command c: command) {
System.out.println("Another command...");
}
}
I don't know how to make the loop or is there another way to do it?
You can create a static list inside class command that the instances get added to in the constructor(s). Then you'll always have references to whatever instances are created.
Here's an example:
import java.util.List;
import java.util.ArrayList;
public class command
{
String call;
String execute;
public static List<command> commands = new ArrayList<>();
public command() {
commands.add(this);
}
public command(String call, String execute)
{
this.call = call;
this.execute = execute;
commands.add(this);
}
public String toString()
{
return "call: " + call + " | execute: " + execute;
}
}
Driver class:
public class driver
{
public static void main(String[] args)
{
for(int i = 1; i <=10; i++)
{
command c = new command("call" + i, "execute" + i);
}
for(command cmd: command.commands)
{
System.out.println(cmd);
}
}
}
Output:
The syntax you are using in your for loop must use a instance of a class that implements the Iterable interface. For example you can use implementations of the List interface.
For example, you can try:
private static void load() {
command greeting = new command();
greeting.call = "hello";
greeting.execute = "Hello Sir";
List<command> listOfCommands = new ArrayList<>();
listOfCommands.add(greeting);
for (command c: listOfCommands) {
System.out.println("Another command...");
}
}

How do I use value from one class for another class Calling from main method

One.java
public class One {
String asd;
public class() {
asd="2d6"
}
public static void main(String args[]) {
Two a = new Two();
}
}
Two.java
public class Two {
ArrayList<String>data;
String asd;
public Two(String asd){
this.asd=asd;
data.add(this.asd);
}
}
How do I use this asd value of second for third class calling from first class's main method.
**Third class**
Per comments of #Maroun Maroun and #Bennyz, you can create a getter and setter method in your Two class:
import java.util.ArrayList;
public class Two {
ArrayList<String> data;
String asd;
public Two(String asd) {
this.asd = asd;
data = new ArrayList<>(); //<-- You needed to initialize the arraylist.
data.add(this.asd);
}
// Get value of 'asd',
public String getAsd() {
return asd;
}
// Set value of 'asd' to the argument given.
public void setAsd(String asd) {
this.asd = asd;
}
}
A great site to learn about this while coding (so not only reading), is CodeAcademy.
To use it in a third class, you can do this:
public class Third {
public static void main(String[] args) {
Two two = new Two("test");
String asd = two.getAsd(); //This hold now "test".
System.out.println("Value of asd: " + asd);
two.setAsd("something else"); //Set asd to "something else".
System.out.println(two.getAsd()); //Hey, it changed!
}
}
There are also some things not right about your code:
public class One {
String asd;
/**
* The name 'class' cannot be used for a method name, it is a reserved
* keyword.
* Also, this method is missing a return value.
* Last, you forgot a ";" after asd="2d6". */
public class() {
asd="2d6"
}
/** This is better. Best would be to create a setter method for this, or
* initialize 'asd' in your constructor. */
public void initializeAsd(){
asd = "2d6";
}
public static void main(String args[]) {
/**
* You haven't made a constructor without arguments.
* Either you make this in you Two class or use arguments in your call.
*/
Two a = new Two();
}
}
Per comment of #cricket_007, a better solution for the public class() method would be:
public class One {
String asd;
public One(){
asd = "2d6";
}
}
This way, when an One object is made (One one = new One), it has a asd field with "2d6" already.

Simple caching in Java using hashmap

Just want to use java hashmap to cache a simple pair into memory and want to get the cached data in another instance.
I am using the below code to put some datas into cache consider the below ProcessDefinitionJavaCode.java code.
package Folder.ProcessDefinition;
import java.util.*;
import java.io.*;
public class ProcessDefinitionJavaCode{
/****** START SET/GET METHOD, DO NOT MODIFY *****/
protected String string_1 = "";
protected String string_2 = "";
public String getstring_1() {
return string_1;
}
public void setstring_1(String val) {
string_1 = val;
}
public String getstring_2() {
return string_2;
}
public void setstring_2(String val) {
string_2 = val;
}
/****** END SET/GET METHOD, DO NOT MODIFY *****/
public ProcessDefinitionJavaCode() {
}
public void invoke() throws Exception {
/* Available Variables: DO NOT MODIFY
In : String string_1
In : String string_2
* Available Variables: DO NOT MODIFY *****/
HashMap<Integer,String> cache = new HashMap<Integer,String>();
cache.put(21, "Twenty One");
cache.put(31, "Thirty One");
}
}
What should I be doing If I want to get the datas I added just now in cache
in another java class temp.java.
I am sorry if it is very silly, I am not a Java expert..
You pass the cache Hashmap to the other class in a constructor or a setter method.
HashMap<Integer,String> cache = new HashMap<Integer,String>();
cache.put(21, "Twenty One");
cache.put(31, "Thirty One");
NewClass newClass = new newClass(cache);
or
NewClass newClass = new newClass();
newClass.setCache(cache);
How about this simple approach (it may be not exactly what you want, but you may get an useful idea):
class PairOfStrings {
final String a, b;
PairOfStrings(String a, String b) {
this.a = a;
this.b = b;
}
#Override
public String toString() {
return "PairOfStrings{" +
"a='" + a + '\'' +
", b='" + b + '\'' +
'}';
}
}
class Sample {
public static void main(String[] args) {
HashMap<Integer, PairOfStrings> pairs = new HashMap<Integer, PairOfStrings>();
pairs.put(1, new PairOfStrings("first", "second"));
pairs.put(2, new PairOfStrings("third", "fourth"));
System.out.println(pairs.get(1));
}
}
The only method I know to retrieve the values from a map is creating a function to do so.
That way you can create a function like this:
String[] getValues(){
String[] aux=new String[cache.size()];
int i=0;
for (Integer integer : cache.keySet()) {
aux[i++]=cache.get(integer);
}
System.out.println(Arrays.toString(aux));
return aux;
}

How do I pass an array of strings into another method?

My code is like this:
public class Test() {
String [] ArrayA = new String [5]
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0])
}
}
I've tried various methods (No pun intended) but none worked. Thanks for any help I can get!
public class Test {
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
public Test(){ // Your Constructor
method1(arrayA[0]); // Calling the Method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, you can just call new Test();
OR if you want the method to be called from your main class by creating an instance of Test you may write:
public class Test {
public Test(){ // Your Constructor
// method1(arrayA[0]); // Calling the Method // Commenting the method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, create an instance of test in your main class.
Test test = new Test();
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
test.method1(arrayA[0]); // Calling the method
And call your method.
EDIT:
Tip: There's a coding standard that says never start your method and variable in uppercase.
Also, declaring classes doesn't need ().
If we're talking about passing arrays around, why not be neat about it and use the varargs :) You can pass in a single String, multiple String's, or a String[].
// All 3 of the following work!
method1("myText");
method1("myText","more of my text?", "keep going!");
method1(ArrayA);
public void method1(String... myArray){
System.out.println("The first element is " + myArray[0]);
System.out.printl("The entire list of arguments is");
for (String s: myArray){
System.out.println(s);
}
}
try this
private void Test(){
String[] arrayTest = new String[4];
ArrayA(arrayTest[0]);
}
private void ArrayA(String a){
//do whatever with array here
}
Try this Snippet :-
public class Test {
void somemethod()
{
String [] ArrayA = new String [5] ;
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1 (String[] A) {
System.out.println("Here's where I need ArrayA[0]"+A[0]);
}
public static void main(String[] args) {
new Test().somemethod();
}
}
The Class name should never had Test()
I am not sure what you are trying to do. If it is java code(which it seems like) then it is syntactically wrong if you are not using anonymous classes.
If this is a constructor call then the code below:
public class Test1() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0]);
}
}
should be written as this:
public class Test{
public Test() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1(String[] ArrayA){
System.out.println("Here's where I need " + ArrayA[0]);
}
}

java return string from class (linkedhashmap)

Not sure if the title makes sense, but I am trying to return a Success message from a class that receives a linkedhashmap, however eclipse is giving me error when I try to compile the files, offering
Remove arguments to match 'logFile()'
Create constructor 'logFile(Map<String, String>)'
How do set it up to send a Map and revieve a String?
thx
Art
Code corrected as per #Jeff Storey below with error suppression for eclipse
calling class
eventLog.put(stringA,stringB);
logFile logStuff = new logFile();
successRtn = logFile.Process(eventLog);
// Do Stuff with SuccessRtn
logFile class
public class logFile {
static String Success = "Fail";
public static String Process(Map<String, String> eventlog){
// Do Stuff
Success = "Yeh!"
return Success;
}
public static void main(String[] args){
#SuppressWarnings("static-access")
String result = new logFile().Procces(eventLog);
System.out.println("result = " + result);
}
The main method is a special method whose signature must public static void main(String[] args) when being used as an entry point to your application. Create a second method that does the actual work, like this:
public class LogFile {
public String process(Map<String,String> eventLog) {
// do stuff
return success;
}
public void main(String[] args) {
// eventLog will probably be read from a filepath passed into the args
String result = new LogFile().process(eventLog);
System.out.println("result = " + result);
}
}
Note that a lot of your naming conventions are also non standard. Classes should begin with a capital letter and variables should begin with a lower case.

Categories