How to write a JUnit test for an atm validation program? - java

I'm new to java and I'm writing an ATM program where user can enter pin code three times and if they fail to enter the correct one, their card is blocked. I've tried to write a Junit test for the following code but I couldn't seem to figure it out. I have two classes AtmPin and AtmTester. AtmTester is where the main class is.
AtmPin.java
import java.util.Scanner;
public class AtmPin {
public static boolean validPIN(int user, int orignal){
return user==orignal;
}
public static int getPin(Scanner sc){
System.out.print("Enter PIN: ");
int pin = sc.nextInt();
return pin;
}
}
AtmTester.java
package atm;
import java.util.Scanner;
public class ATMTester {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int i = 0, userpin;
int PIN = 1234;
while(i< 3){
userpin = AtmPin.getPin(keyboard);
if(AtmPin.validPIN(userpin, PIN)){
System.out.println("Your PIN is correct");
System.exit(0);
}
else {
System.out.println("Your PIN is incorrect");
}
i++;
}
System.out.println("Your Bank Card is blocked");
}
}

Try to search the internet for "kata":
A "kata", or "coding kata", is defined as an exercise in programming which helps hone your skills through practice and repetition.
Searching for "kata atm" found this:
https://githubhelp.com/xpepper/ATM-kata-java
which may be a good starting point.
Each requerement of the kata can be translated to one or more junittests

Related

How do you run a Java class from another class?

I am working on a project for school. at this point i'm just going over board, I would like to run the class bookstoreCreditPersonal if none of the following conditions are true, but I cant get it to work. any suggestions?
import java.util.Scanner;
public class bookstoreCreditPersonal {
public static void main(Object o) {
String studentNamePers;
String userType;
double studentGPAPers;
double bookstoreCreditPers;
Scanner input = new Scanner(System.in);
System.out.print("Please enter 'S' if you are the student, 'T' if you are the teacher, or 'P' if you are the Parent: ");
userType = input.nextLine();
if (userType.equals("S")) {
System.out.println("Greetings student...");
Scanner Sinput = new Scanner(System.in);
System.out.println("Please enter your(The students) first and last name :");
studentNamePers = input.nextLine();
Scanner SSinput = new Scanner(System.in);
System.out.println("Please enter your(The student's) GPA :");
studentGPAPers = input.nextDouble();
bookstoreCreditPers = studentGPAPers * 10;
System.out.println(studentNamePers + ", your GPA is " + studentGPAPers + ", and you have an available bookstore credit of $" + bookstoreCreditPers);
} else if (userType.equals("T")) {
System.out.println("Teacher");
} else if (userType.equals("P")) {
System.out.println("Parent");
} else {
System.out.println("Lets try that again, one character, in capital form only please.");
//created a class that reruns this class
runClassBSCP.call(null);
}
}
}
Here is the class runClassBSCP:
public class runClassBSCP {
public void call() {
bookstoreCreditPersonal.main(null);
}
}
You need to instantiate/create an object of the class. Then you can call the desired method with the object.
runClassBSCP bscp = new runClassBSCP();
bscp.call();
Also, your class names should always start with an uppercase letter: RunClassBSCP, rather than `runClassBSCP'. For more info, check out Code Conventions for the Java Programming Language.

Java - Assigning User Input to Variable and display Scoreboard

I know it's very basic java but I am trying to learn. Can someone help me to understand my errors and what should I do to solve it?
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int teamA = 0;
int teamB = 0;
//asks for the team selection
System.out.println("Would you like to be in Team A or Tema B? Write A for team A and B for team B");
Scanner input = new Scanner(System.in);
int result = input.nextInt();
public String scoreBoard() {
String displayScoreBoard = "No Score";
if (result.toString == "A" || result.toString == "a"){
teamA++;
displayScoreBoard = "Score of TeamX is" + teamA;
} else if (result.toString == "B" || result.toString == "b"){
teamB++;
displayScoreBoard = "Score of TeamY is" + teamB;
} System.out.println(displayScoreBoard.toString);
}
// write your code here
}
}
You made several mistakes. For example you wrote a function within a function. You better don't do that. Just look at my code. If you have any questions, just ask ;)
UPDATE: Due to the comments that there should be a loop, I've adapted the code.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
int teamA = 0;
int teamB = 0;
//asks for the team selection
while(true) {
System.out.println("Would you like to be in Team A or Tema B? Write A for team A and B for team B. Type anything else to quit.");
Scanner input = new Scanner(System.in);
String result = input.next();
if (result.toUpperCase().equals("A")) {
System.out.println("Score of TeamX is" + ++teamA);
} else if (result.toUpperCase().equals("B")) {
System.out.println("Score of TeamY is" + ++teamB);
}
else {
break;
}
}
}
}

Creating Methods that will produce the same result

I'm in a Beginner Java class and I'm confused about using additional methods and using them in another. I think that I have most of my assignment done but I just need help to create the methods. One is to generate the question and the other one is to display the message.
I know that in order to call a method
public static test(num1,num2,num3)
but in my code, how do I make it so that I call the method and still make it loop correctly?
In the assignment instructions that was given to me, In order to do that, I have to write a method named
public static in generateQuestion()
and
public static void displayMessage(boolean isCorrect)
This is my code:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
//Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
//Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
//Question prompt
System.out.println("How much is " +number1+ " times " +number2+ "? ");
answer = input.nextInt();
//If Else While Statements
if(answer == (number1*number2))
{
System.out.println("Good job! You got it right!");
}
else
{
while (answer !=(number1*number2))
{
System.out.println("You got it wrong, try again!");
answer = input.nextInt();
}
}
}
}
You are going to have two methods
public static void generateQuestion()
Which is going to hold the code to generate the random values and output it. It will return void because all it's doing is printing out.
Next you will have
public static void displayMessage(boolean isCorrect)
which will be called if if(answer == (number1*number2)) is true with true as the parameter. Otherwise it will still be called, but the parameter passed in will be false. This method will determine if isCorrect is true or false, and output the appropriate message.
If I got it right, I have a solution that might be a little stupid but will work for your assignment.
If you make generateQuestion that makes two random ints, prints the question and returns their multiple (answer).
And displayMessgae that prints "Good job! You got it right!" if isCorrect is true and "You got it wrong, try again!" else,
you can call generateQuestion, then get an answer (in main), and loop until answer is correct (according to return value of generateQuestion).
Every time you get a new answer (in loop), call displayMessgae(false).
After the loop ended call displayMessgae(true)
This is my working code for this:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static int generateQuestion()
{
Random r = new Random();
int x = r.nextInt(9), y = x = r.nextInt(9);
System.out.println("How much is " + x + " times " + y + "? ");
return x * y;
}
public static void displayMessage(boolean isCorrect)
{
if (isCorrect)
System.out.println("Good job! You got it right!");
else
System.out.println("You got it wrong, try again!");
}
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
int rightAnswer = 0;
rightAnswer = generateQuestion();
while (input.nextInt() != rightAnswer)
displayMessage(false);
displayMessage(true);
}
}
If I understand your question correctly, It's simply a matter of separating the functionality that prints a question and displays the answer into separate methods. See my edited version of your code below
public class Assign6
{
public static void main(String[] args)
{
// Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
// Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
// Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
displayQuestion("How much is " + number1 + " times " + number2 + "?");
answer = input.nextInt();
// If Else While Statements
if (answer == (number1 * number2))
{
displayMessage(Boolean.TRUE);
}
else
{
while (answer != (number1 * number2))
{
displayMessage(Boolean.FALSE);
answer = input.nextInt();
}
}
}
public static void displayQuestion(String q)
{
System.out.println(q);
}
public static void displayMessage(Boolean isCorrect)
{
if (isCorrect)
{
System.out.println("Good job! You got it right!");
}
else
{
System.out.println("You got it wrong, try again!");
}
}
}

Netbeans compilation error

// I am new to Java and was practicing some questions on netbeans. I get compilation error on public class bank_acc ( ide is suggesting me to change the name of my whole program to bank_acc but as far as I know the program name is same as the class name which has the main function ). When I change it I get error on class prog2. Either way it's not working out. Please help.
package prog2;
import java.util.Scanner;
public class bank_acc{
String name;
double acc_no;
String acc_type;
double bal;
Scanner s = new Scanner(System.in);
void bank_acc(){
System.out.println("Enter basic values");
name = s.nextLine();
acc_no = s.nextInt();
acc_type = s.nextLine();
bal = 1000;
}
// function to deposit money in acc.
void deposit(){
System.out.println("Enter the amount to be deposited");
double amt=s.nextDouble();
bal+=amt;
}
// function to withdraw amt after checking it.
void wac(){
System.out.println("Current balance = "+bal);
System.out.println("Enter amount to be withdrawn");
Double wdraw_amt=s.nextDouble();
bal-=wdraw_amt;
}
void display(){
System.out.println("Welcome to THE BANK !");
System.out.println("Your name is: "+name);
System.out.println("Account Balance: "+bal);
}
}
public class Prog2{
public static void main(String[] args) {
// TODO code application logic here
bank_acc a = new bank_acc();
a.deposit();
a.wac();
a.display();
System.out.println("Thank you. Keep working!");
}
}
You can have only one top level public either class or interface in any java compilation unit ( .java source file ).

how to get data from other methods?

does anyone know how to get the counters value transfered after it is increased? so if you awnser it right it changes to one in the next method?
package swag;
import java.util.Scanner;
public class Main {
public static void enter(){
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")){
System.out.println(" Level one");
}else{
System.out.println("Please press enter");
}
}
public static void firstlevel(){
System.out.println("What is the tenth digit of PI?");
Scanner input = new Scanner(System.in);
int awnser = input.nextInt();
int awnser1 = 5;
int counter = 0;
if (awnser == awnser1 ){
System.out.println("Correct!");
counter++;
System.out.println(" Score: " +counter + "/1");
}else{
System.out.println("Wrong!");
System.out.println(" Score:"+ counter+"/1");
}
}
public static void secondlevel(){
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
Scanner input = new Scanner(System.in);
String awnser = input.nextLine();
if (awnser.equals("two ")){
System.out.println(" Correct!");
}
}
public static void main(String args[]){
enter();
firstlevel();
}
}
Ah, the way you have defined counter, it can only be seen in firstLevel.
Best thing to do is make it a 'class variable'. To do that:
Delete int counter = 0; from the firstLevel method.
Add static int counter = 0; on the very next line after public class Main {
So the start of your class should look like:
public class Main {
static int counter = 0;
Now counter will be visible in all methods.
I would highly recommend not using a static counter, as suggested by others. Static mutable objects tend to violate the principle of object oriented programming. If you separate the functionality of your game into methods, you'll have a much more beautiful main method:
public static void main(String args[]) {
// Lets create a new Game object. it will keep track of the counter itself!
Game game = new Game();
// Then we only have to call the methods defined below..
game.enter();
game.firstLevel();
game.secondlevel();
}
Now the code for the class Game containing all the logic:
public class Game {
// Some static final members. they are not meant to change throughout the execution of the program!
// The advantage of defining INDENTAION just once, is that you can easily change it in one place and it will always be consistent!
private static final String INDENTAION = "\t\t";
private static final int TOTAL_POINTS = 2;
// We can use the same scanner object in each method!
private Scanner input = new Scanner(System.in);
// Just like the counter. it will be accessible in each method and refer to the same integer!
private int counter = 0;
public void enter() {
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")) {
System.out.println(INDENTAION + "Level one");
} else {
// I am not sure why you put this here, but I'll leave it in for now
System.out.println("Please press enter");
}
}
// We put that code into seperate methods, since it will get called multiple times!
private void answerCorrect() {
System.out.println("Correct!");
counter++;
printScore();
}
private void answerWrong() {
System.out.println("Wrong!");
printScore();
}
private void printScore() {
System.out.println(INDENTAION + "Score: " + counter +"/"+ TOTAL_POINTS);
}
public void firstLevel() {
System.out.println("What is the tenth digit of PI?");
int awnser = input.nextInt();
if (awnser == 5) {
answerCorrect();
}else{
answerWrong();
}
}
public void secondlevel() {
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
String awnser = input.nextLine();
if (awnser.equals("two") || awnser.equals("2")) {
answerCorrect();
} else {
answerWrong();
}
}
}

Categories

Resources