I am quite a new coder in Java, I have already used it before but without going deep into it, but now that I learned the basic I am searching for a way to be more efficient in my way of coding, so I ask how could I do lines of code to run one after another each time I use a certain word, for example, I would like my code to run several fighting commands that I premade using only the word "fight" in my code
All you need to do is set up a scanner that waits for a string input after which is process the string received through the scanner and if said string is "fight" then call the fight method.
Like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String command = in.next();
in.close();
ProcessCommand(command);
}
static void ProcessCommand(String command) {
if (command.equalsIgnoreCase("fight")) {
fight();
}
}
static void fight() {
// Do Stuff..
}
Hope this helps! :D
Related
I'm trying to write a code where it takes words from a text file, and puts each word in canonical order, and when run prints the original word next to its canonical form like this:
coding cdgino
games aegms
All I have so far is this:
import java.util.*;
import java.io.*;
public class CanonicalWords
{
public static void main(String[] args) throws Exception
{
if (args.length<1)
{
System.out.println("You must provide an input file.");
system.exit(0);
}
String infileName = args[0];
BufferedRead infile = new BufferedReader(new FileReader(infileName));
while(infile.ready())
{
//arraylist.add(infile.readLine())
}
//sort arraylist
for (int i=0;i<arrayList.size;i++)
{
}
}
static String canonical(String word)
{
char[] canonicalWord = word.toCharArray();
Arrays.sort(canonicalWord);
String cWord = new String(canonicalWord);
return cWord;
}
}
Please let me know if you need clarification on anything I have writen. I do not know how to take these words to put them into canonical form.
Right now there is no real output, it doesn't even compile. I'm just very confused. If someone could help me to understand what is the basic formula (if there is one) to put words into canonical form and do what I stated above that'd be wonderful, but I understand that what I'm asking may come off as a bit confusing. Thank you.
First, from the looks of this code:
BufferedRead infile = new BufferedReader(new FileReader(infileName));
should look like this:
BufferedReader infile = new BufferedReader(new FileReader(infileName));
Be careful that you fully spell out correctly; variable names and they're data types!
Another thing to take note of is, the method:
static String canonical(String word)
isn't being called. Try accessing it in the main method.
This question already has answers here:
JUnit test for System.out.println()
(14 answers)
Closed 4 years ago.
I want to test method setDay() using arguments [-1,0,24,2,32].
I know that Scanner reader can be
String test="-1 0 24 2 32";
Scanner reader=new Scanner(test);
The main problem is infinite loop and void method. How can we test this kind of code? Here is example code:
public NameOfTheDay(){
int day=1;
}
{...}
public void setDay(Scanner reader) {
while (true) {
System.out.print("Day: ");
String input = reader.nextLine();
if (input.matches("\\d{2}")) {
int day = Integer.parseInt(input);
if (day > 0 && day < 32) {
this.day = day;
return;
}
}
System.out.println("Wrong day. Try again.");
}
}
Thanks for the answer.
How can we test this kind of code?
You cannot.
unittest verify the public observable behavior of your code under test where "public observable behavior" is any rreturn value or communication with dependencies.
Communication with dependencies is checked with test doubles which we (usually) create using a mocking framework and which we inject into the code under test.
A major prerequest is that you code cleanly incorporates Single Responsibility/Separation of Concerns pattern.
Your code does not return anything and has no possibility to replace the dependencies of interest (here System.out) because it mixes business logic with user interaction.
Some may argue, that you can assign a test double to System.out or use PowerMock to replace dependencies but IMHO this is just a surrender to your bad design and will not pay off as your program grows.
I will not focus on the contents of your method, but just on the question on how to unit test a method expecting a Scanner object as parameter.
The easy answer is: Provide your test input data as a String, and build a scanner around it, like this:
#Test
public void testSetDay_positive() {
String testInput = "23\n";
Scanner testScanner = new Scanner(testInput);
NameOfTheDay notd = new NameOfTheDay();
notd.setDay(testScanner);
Assert.assertEquals(23, notd.getDay()); // or whatever condition to test
}
Now it gets harder. Perhaps you want to test an invalid input first, and make sure the second input is used then?
#Test
public void testSetDay_negative_then_positive() {
String testInput = "999\n23\n"; // two lines of input here
Scanner testScanner = new Scanner(testInput);
NameOfTheDay notd = new NameOfTheDay();
notd.setDay(testScanner);
Assert.assertEquals(23, notd.getDay()); // or whatever condition to test
}
If you want to test if the error message is written to System.out, you would have to replace that with a custom stream to test afterwards:
ByteArrayOutputStream mockOut = new ByteArrayOutputStream();
PrintStream newOut = new PrintStream(mockOut);
System.setOut(newOut);
// execute test from above
Assert.assertTrue(new String(mockOut.toByteArray(), "UTF-8").contains("Wrong day. Try again."));
Still, most comments to your question contain valuable input (move validation to an extra method etc.) which should be considered.
i have a program in java and what i want to do is somehow store all the functions that have been run whilst the program ran. but i can not seem to find anything on this matter. Also then have to find out which of the function has been ran the most amount out time.
my thought was that i could make an array, assign each function to have a variable with a name of the function and then everytime it is run return that char into the array, and print out the array at the end. But i dont know how to go about storing them in different arr[i] i's everytime same function is ran, also im not sure how i would then find the one that was ran most, any help is much appreciated.
What I'd recommend is creating a boolean for each method, and at the beginning of the method, set the boolean to true. Then create a save method using the java.io class and save the boolean name and value to the file.
EDIT
I just realized i put boolean instead of integer. Have an integer for each method and do integer++ for each method run.
AOP is great for something like this.
See https://dzone.com/articles/monitoring-performance-spring for an example that uses the Spring AOP library.
i tried a program that may help you or not. i created a Interceptor class which will print out the details you may need. You didnot mention about any frameworks, so i just gave you an example program with plain old java.
This approach also offers flexibility to print all the details at the end of program execution.
public class Test {
public void demoMethod() throws InterruptedException{
Intercept.printMethodStartTime(System.currentTimeMillis());
Intercept.printMethodName(Thread.currentThread().getStackTrace()[1].getMethodName());
Thread.sleep(5000);
Intercept.printMethodEndTime(System.currentTimeMillis());
}
public static void main(String[] args) throws InterruptedException {
new Test().demoMethod();
}
}
class Intercept{
private static Long startTime;
private static Long endTime;
public static void printMethodName(String methodName){
System.out.println("Current method name: "+methodName);
}
public static void printMethodStartTime(Long time){
startTime = time;
System.out.println("Method started at "+startTime);
}
public static void printMethodEndTime(Long time){
endTime = time;
System.out.println("Method ended at "+endTime);
printMethodRunTime();
}
public static void printMethodRunTime(){
System.out.println("Method ran for "+((endTime-startTime)/1000)+" seconds");
}
}
Hi this is the first time im trying out unit testing in java using eclipse.
So when i test my class, it requires user input. Lets say a command called "add hello", so that it will create a new textfile and add the word "hello" to it. Then i want to test a function called getAllLines which returns "hello" and compare it with assert.
My main problem is how to simulate user input to console via junit test. This is what i tried but its not working..
private void performUserInput(String strInput){
ByteArrayInputStream in = new ByteArrayInputStream(strInput.getBytes());
System.setIn(in);
}
private void releaseUserInputToSystem(){
System.setIn(System.in);;
}
#Test
public void testSearchingInEmptyFile() {
TextBuddy textBuddy = new TextBuddy("file.txt");
textBuddy.run();
performUserInput("add little brown fox");
releaseUserInputToSystem();
assertEquals("little brown foxx", "asd");
}
It seems to me like the code never reaches assert.
edit----------------------------------------------
After debugging, its getting stuck here
private String[] getCommandAndArgs(){
String[] splitCommand = scanner.nextLine().split(" "); //<<STUCK HERE
printNewLine();
return splitCommand;
}
With the Unit-Test you should rather test single Methods (units) of your TextBuddy Class. You probably have a method which check the commands (add, remove, whatever you have). Write Unit Tests for those e.g.:
#Test
public void testCommandAdd() {
TextBuddy tb = new TextBuddy ();
int command tb.parseCommand("add hello");
assertThat(command,is(TextBuddy.ADD));
}
#Test
public void testCommandRemove() {
TextBuddy tb = new TextBuddy ();
int command tb.parseCommand("remove hello");
assertThat(command,is(TextBuddy.REMOVE));
}
Then write tests for each command, e.g. that a file was written/deleted whatever:
#Test
public void testWriteFile() throws SQLException {
TextBuddy tb = new TextBuddy ();
tb.writeFile("file.txt", "hello");
File f = new File("file.txt");
String content = readFile(f);
assertThat(content,is("hello"));
}
Always test single units of your program with small Unit Tests. Later you can write bigger Tests that check if your hole Program works.
If you don't want to expose your Methods with the public modifier, you can still test them - the simplest way is makeing them package-private and have your tests the same package (they can and should be in a differnet src-folder)
e.g. for a Class with the package com.yourpackage like this
src/com/yourpackage/YourClass.java
You could store your test in
test/com/yourpackage/YourClassTest.java
Then you can access package-private Methods.
Or you use Reflection to access and test a private Method, see here and here
A unit test is all about automation and should not rely on user input. If you want to test a user input mechanism, you should write a test that simulates a user entering the input to be tested (e.g. using Selenium for front end testing a web application). If you want to test behavior based on input, you should contruct tests that enter all possibilities that shall be tested automatically and validate the respective correct behavior of your application/program/functionality.
If TextBuddy.run() is specified to read something from System.in, it looks like a good idea to redirect System.in before the call to run():
performUserInput("add little brown fox");
textBuddy.run();
releaseUserInputToSystem();
But maybe you could improve your TextBuddy to be more testable by adding the input stream to read from as a parameter to the run method:
public void run(InputStream in) {
// use parameter in instead of System in...
}
/**
* Convenience method to run with System.in
*/
public void run() {
run(System.in);
}
In your test, call run(InputStream):
ByteArrayInputStream in = new ByteArrayInputStream(strInput.getBytes());
textBuddy.run(in);
You could also add an out parameter to be able to redirect the output of your tested method.
I agree with #LarsGendner you should mock (do some simulate or fake things) for the input task. You can use some technique that provides input to coverage at least for some part of this code (for example TextBddy). In this case, I can suggest three approaches.
static inputs use this approach if you need to have some text samples derived from empirical testing. You can use this form model some typical behavior from existing users;
random string generator use this approach to do string generation from scratch (you can combine this approach with static input)
framework (or library) to extend jUnit capability in towards of data mining or artificial intelligence such as genetics algorithms, neural networks and so on.
In my onion the last technique is more sophisticate. So, you should evaluate and perform a thread-off to decide which parts should be testing and which should be the code coverage that you need. Notice, that mocking some input task according to human behavior it is not trivial task.
Regarding your original code, when you execute textBuddy.run(); it will lock expecting user input, so the next line (performUserInput("add little brown fox"); which does provide the input it is waiting for) is never executed.
So, to make that code work, you should call performUserInput("add little brown fox"); before calling textBuddy.run():
#Test
public void testSearchingInEmptyFile() {
TextBuddy textBuddy = new TextBuddy("file.txt");
performUserInput("add little brown fox"); // changed these two lines
textBuddy.run(); // switched their order
releaseUserInputToSystem();
assertEquals("little brown foxx", "asd");
}
Another approach is to use threads: execute textBuddy.run() in one thread and performUserInput("add little brown fox") in other. It is probably best to avoid this, though, as threads may make your tests way more difficult to maintain.
Full demo code:
public class TextBuddyTest {
private InputStream performUserInput(String strInput) {
InputStream originalSystemIn = System.in;
ByteArrayInputStream in = new ByteArrayInputStream(strInput.getBytes());
System.setIn(in);
return originalSystemIn;
}
private void restoreSystemInputStream(InputStream originalSystemIn) {
System.setIn(originalSystemIn);
}
#Test
public void testSearchingInEmptyFile() {
// setup
InputStream defaultSystemIn = performUserInput("add little brown fox");
TextBuddy textBuddy = new TextBuddy("file.txt");
// execute
textBuddy.run();
// verify
assertEquals("[add, little, brown, fox]", textBuddy.getWhatWasInput());
// teardown
restoreSystemInputStream(defaultSystemIn);
}
static class TextBuddy { // created for this demo
Scanner scanner = new Scanner(System.in);
String whatWasInput;
public TextBuddy(String s) { }
public void run() { this.whatWasInput = Arrays.toString(getCommandAndArgs()); }
private String[] getCommandAndArgs() { return scanner.nextLine().split(" "); }
public String getWhatWasInput() { return whatWasInput; }
}
}
I have to display the current user into the gui, but it keep saying the the hashset is empty, this has been bugging me for hours. What is the easiest way to fix this? There might be a lot of un used code as i was testing things trying to make it work.
Client.java
public class Client {
Server.names();
}
Server.java
public class Server {
public static HashSet<String> names = new HashSet<String>();
public static void main(String[] args) throws Exception{
while(true){
name = in.readLine();
if(name == null){
return;
}
if(!names.contains(name)){
names.add(name);
break;
}
}
}
}
Your Q is a bit unclear, but if you want to get the HashSet, names from your Server class, you need to get the reference to it by calling Server.name, not Server.name() as it is not a method.
Now names will be empty until you populate it. To populate it you need to call code that will read user input and store it in names. In this case you can call the main method of Server (see this related Q here) but unless you really want that to be your main method of Server, I would recommend renaming the method to populateNames() or something similar.