How would I develop the driver class for this code ive written ?
Array Class:
import java.util.Scanner;
public class Array
{
Scanner sc = new Scanner(System.in);
private double[] array = new double[];
public void setArray(double[] arr)
{
//I must set a value for the array length. set by user.
//user must input data
}
public boolean isInIncreasingOrder()
{
//must test if input is in increasing order
}
public boolean isInDecreasingOrder()
{
//must test if input is in descending order
}
public double getTotal()
{
//must find the total of all input
//total +=total
}
public double getAverage()
{
//must calculate average
//average = total/array.length
}
}
I guess what I'm asking is what exactly do i call in the DriverClass and how do I do it.
Thanks
The simplest way to test a class is to have a "public static void main(String[] args)" method in the class itself.
In this "main" method, you first create an instance of the class, and then call the various methods in the class, and verify that they do what you expect. To make testing easier, you might want to print out a message after each call to the class under test, showing the expected result, the actual result, and a friendly "OK" or "FAIL" to let you see easily if the method did what you wanted.
Example:
class MyClass {
private int x = 0;
public int getX() { return x;}
public void setX(int x) { this.x = x; }
public static void main(String[] args) {
MyClass instance = new MyClass();
instance.setX(42);
int value = instance.getX();
System.out.print("Expected 42, got "+value);
if (value == 42) {
System.out.println("OK");
}
else {
System.out.println("FAIL");
}
}
}
Once you're familiar with this approach to testing, you might look into unit test frameworks such as JUnit, which provide better ways to "assert" that a particular test is passing, and to understand the results of your testing.
Related
I'm new to JAVA programming, and was wondering if it's possible/how to ask the user to input what class they'd like to run and then call/run that class?
Example:
I created two classes to solve the Towers of Hanoi given (supplied by user) n amount of disks. One class solves the puzzle recursively and the other class solves the puzzle iteratively. When I am asking the user for the number of disks they'd like to use, is it possible to ask them how they would like to solve the program whether it be recursively or iteratively and then call the class that they chose?
Yes, that is possible.
This version may look a bit more complicated on first glance, but it separates the parts more clearly. The interface and the classes would usually be in separate files in real applications. Also, the static chooseSolver - method would possible be moved to a separate class named something like SolverFactory.
import java.util.Scanner;
import java.util.Set;
public class Main {
interface Solver {
void solveIt();
}
static class SuperSolver implements Solver {
public void solveIt() {
System.out.println("SuperSolver always solves anything");
}
}
static class FastSolver implements Solver {
public void solveIt() {
System.out.println("Noone beats the FastSolver");
}
}
public static void main(String[] args) {
String in = askUserForOption();
Solver s = chooseSolver(in);
s.solveIt();
}
private static String askUserForOption() {
String in;
Set<String> validOptions = Set.of("A", "B");
try (Scanner sc = new Scanner(System.in)) {
do {
System.out.print("Enter A or B: ");
in = sc.nextLine();
} while (!validOptions.contains(in));
}
return in;
}
private static Solver chooseSolver(String in) {
switch (in) {
case "A":
return new SuperSolver();
case "B":
return new FastSolver();
default:
throw new IllegalArgumentException("something went terribly wrong - an invalid option was given");
}
}
}
You can do this in a pretty straightforward manner using a common interface both solvers implement.
interface HanoiSolver {
void solve(int n);
}
// iterative solver
class IterativeHanoi implements HanoiSolver {
public void solve(int n) { ... }
}
// iterative solver
class RecursiveHanoi implements HanoiSolver {
public void solve(int n) { ... }
}
public class MainClass {
public static void main(String[] args) {
// you can change this to read input however you like
String userInput = args[0];
Integer n = Integer.parseInt(args[1]);
HanoiSolver solver;
if (userInput.equals("recursive")) {
solver = new RecursiveHanoi();
} else {
solver = new IterativeHanoi();
}
solver.solve(n);
}
}
Depends on where this code is used internally or as library package.
Internally you can use interface and then seperate out the concrete implementation.
In library , you can again let user call interface method , write implementation of that interface based on condition.
Or if you want the user to determine the algo to use during the runtime then use Reflection to decide which class's object to create.
My overall goal with this program is to validate that a user inputted string is in fact a valid number. I am required to use at least two methods, including the main method. I have read many posts related to calling user-defined methods from within the main method, but I am however struggling to make mine work. When declaring my isAValidNumber method, I keep getting the error "illegal start of expression". How can I declare this method so that I can call it from within the main method and contentiously run it until the user enters an invalid invalid number?
import java.util.Scanner;
public class IsAValidNumber
{
public static void main(String[] args)
{
//prompt user for a valid number
Scanner consoleInput = new Scanner(System.in);
System.out.print("\nEnter a valid integer or floating point value: \n");
String input = consoleInput.nextLine();
/* while(isAValidNumber = true)
{
//
} */
public static isAValidNumber(String input)
{
for(int j=0;j<input.length();j++)
{
if(input.matches("\\d+(\\.\\d*)?|\\.\\d+") == true)
{
boolean isAValidNumber = true;
}
else
{
boolean isAValidNumber = false;
}
}
}
}
}
You can't declare methods inside of methods in Java. Declare isAValidNumber outside of main (either before or after it, doesn't matter) and you should be OK:
public class IsAValidNumber
{
public static boolean isAValidNumber(String input)
{
// Method's body snippet for brevity's sake
}
public static void main(String[] args)
{
// Code that can call isAValidNumber
}
}
public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}
When I play it in NETBEANS IDE 8.0 it keeps saying there is no main class even though I added the main class already?
Need help can't understand.
PS. If I delete the static in magic() it blocks the magic() in main.
package fibotail;
import java.util.Scanner;
public class Fibotail {
public static int fibo(int control, int currentValue, int previousValue) {
if (control < 2) {
return currentValue;
}
return fibo(control - 1, currentValue + previousValue, currentValue);
}
public static void magic() {
String cCharacter;
do {
System.out.println("Input here: ");
int something = new Scanner(System.in).nextInt();
for (int i = 1; fibo(i, 0, 1) <= something; i++) {
System.out.println(fibo(i, 0, 1));
}
do {
System.out.println("Do you want to try again? ");
cCharacter = new Scanner(System.in).next();
} while (!(cCharacter.equals("y") || cCharacter.equals("Y") || cCharacter.equals("N") || cCharacter.equals("n")));
} while (cCharacter.equals('y') || cCharacter.equals('Y'));
}
public static int main(String args[]) {
magic();
return 0;
}
}
Return type should be void, not int:
public static void main(String args[]) { ... }
The JVM looks for the exact signature of the method.
When you run your project you would get:
Error: Main method must return a value of type void in class MainTest, please
define the main method as:
public static void main(String[] args)
In other languages than java, where main returns int (such as C and C++) the return code of main becomes the exit code of the process, which is often used by command interpreters and other external programs to determine whether the process completed successfully.
But java needs void as the return value. (Java internal architecture)
If you reaaly need to return a value just use the following:
System#exit(int)
To enable your program quit with a specific exit code which can be interpreted by the operating system.
Your main() method must have return type void
public static void main(String[] args){
}
Not int or other.
main() method is the entry point of your program and JVM is looking exact main() method.
You have to change your code a little bit. It should be:
public static void main(String args[])
The return type of main method is void
I have the following method that I would like to test, it simply increments an int if a Boolean condition is true:
public void incrementIfConditionMet(Boolean personCheckedIn) {
int peopleInHotel=0;
if (personCheckedIn==true){
peopleInHotel++
}
}
I am very new to unit testing in Java. How can I unit test this to check if the int has been incremented or not?
Currently your value of peopleInHotel cannot be accessed outside the method, as it was created internally. If you want to access it, you should do the following:
private int peopleInHotel=0;
public int getPeopleInHotel() {
return peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn){
peopleInHotel++
}
}
Now in your test class, you can check by calling getPeopleInHotel();
So the test case would be:
int initalValue = classInstance.getPeopleInHotel();
classInstance.incrementIfConditionMet(true);
assertEquals(classInstance.getPeopleInHotel(), initalValue +1);
This would also fix your issue where you don't keep the value once the method has been ran. At the moment, in your current code setup, your variable of peopleInHotel is discarded after you've finished with the method.
int peopleInHotel=0;
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
public int getPeopleInHotel() { //test the returned value after you've incremented
return peopleInHotel;
}
Try like this:
public class Hotel {
private int peopleInHotel = 0;
//a constructor...
public int getPeopleInHotel() {
return this.peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
}
In your Unit-Test, you now can do something like that:
//defining your TestCase
Hotel hotel = new Hotel();
int initValue = hotel.getPepleInHotel();
hotel.incrementIfconditionmet(true);
assertEquals(hotel.getPeopleInHotel(),initValue+1);