Junit test cases for number to word program - java

public class NumberWords {
public String toWords(int number) {
String result = "";
if (number == -1) {
result = "Number out of range";
}
if (number >= 0 && number <= 999) {
if (number == 0) {
System.out.println("NUMBER AFTER CONVERSION:\tZERO");
} else {
System.out.print("NUMBER AFTER CONVERSION:\t");
numberToWord(((number / 100) % 10), " HUNDRED");
numberToWord((number % 100), " ");
}
}else if(number >= 1000){
System.out.println("Number not in range");
}
if (number == 0) {
System.exit(number);
}
return result.trim();
}
public static void numberToWord(int num, String val) {
String ones[] = {" ", " ONE", " TWO", " THREE", " FOUR", " FIVE", " SIX", " SEVEN", " EIGHT", " NINE", " TEN", " ELEVEN", " TWELVE", " THIRTEEN", " FOURTEEN", " FIFTEEN", " SIXTEEN", " SEVENTEEN", " EIGHTEEN", " NINETEEN"
};
String tens[] = {" ", " ", " TWENTY", " THIRTY", " FOURTY", " FIFTY", " SIXTY", " SEVENTY", " EIGHTY", " NINETY"};
if (num > 19) {
System.out.print(tens[num / 10] + " " + ones[num % 10]);
} else {
System.out.print(ones[num]);
}
if (num > 0) {
System.out.print(val);
}
}
}
public class NumberWordsApplication {
private final NumberWords numberWords;
private final BufferedReader reader;
public NumberWordsApplication() {
numberWords = new NumberWords();
reader = new BufferedReader(new InputStreamReader(System.in));
}
public void execute() {
while (true) {
try {
System.out.print("\nPlease type a number between 1 and 999 OR (0 to exit) : ");
String value = reader.readLine();
int number = Integer.parseInt(value);
String toWords = numberWords.toWords(number);
} catch (NumberFormatException | IOException e) {
System.out.println("Invalid number");
}
}
}
public static void main(String[] args) {
new NumberWordsApplication().execute();
}
}
This is main class for generate number to word eg 57 then output should be "Fifty Seven"
I want to generate test cases for class NumberWords i have got stuck
Develop the numbers to words application using TDD
Implement the main application to read numbers from the keyboard
and print out the values
On the server navigate to the Numbers
project
Run ant to build the project. The build will fail if the
unit tests fail.
~/ant/bin/ant dist
The results of the unit
tests are in the report directory which got created  Run the
application and try it out
java –j Numbers.jar

Since this is a (homework?) question about Test-Driven Development, the very first steps would be to:
Create a very simple test case that checks that the number 1 is mapped to "ONE"
Create a very simple implementation that just returns "ONE" when the input is 1.
Create a built script (using ant if you must) to run this test.
Once you have this up and running you can gradually add more test cases, until your class (which will be a simplified version of NumberWords) can convert any input.
To keep the application testable it is best to abstain from using System.exit(), and to minimize code included in a while(true). This is easy to do for the given assignment.
It looks like you have tried to apply TDD in the wrong order, doing test-last instead of test-first development.

Related

How can I print something based on the result of a boolean method?

I have two methods
*`public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}`*
validateMarks(): Used to validate qualifying exam marks - qualifying marks is in the range of 65 to 100(both inclusive)
validateCourseId(): Used to validate the course entered, based on the courseId - given in the table above
calculateCourseFee(): Used to calculate the course fee after applying the discount.
So when is less than 65 print print "not elegible, you've failed" and when the course is not valid "course is not correct, please try again with the correct number of the course"
and this is my calculateCourseFee method
***if(this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("Wroog for course");
}
***
I make two different ifs for the two requirements, but everytime I run it, it prints the else statement to, even if marks is greather than 65... am I missing something?
Reviewing my code and tell me what am I missing or what am I doing wrong
The portion of the code you have shown here seems to be working as expected.
public class Driver {
public static void main(String args[]) {
Eligible e1 = new Eligible();
e1.calculateCourseFee();
}
}
class Eligible{
int qualifyingMarks = 66;
int courseId = 1002;
public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}
public void calculateCourseFee(){
if(this.validateMarks()) {
System.out.println("works for marks");
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
System.out.println("works for course");
}else {
System.out.println("Wroog for course");
}
}
}
output:
works for marks
works for course
Maybe the issues is with how you set the values for the qualifyingMarks and courseId variables?
I wish I could give you a like or thumbs up, I finally did it, thanks to all of your answers you gave me, and I just combined the two ifs into one. here's the code:
if(this.validateCourseId() && this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else if(!this.validateCourseId()) {
System.out.println("Wrong course");
}
else if(!this.validateMarks()) {
System.out.println("You've failed");
}
Thanks everyone!!
maybe qualifyingMarks is zero or another value, print qualifyingMarks in method "validateMarks",u will get the reason of your problem.

How do I fix an if statement that uses "parseInt()" so that the else portion is activated and my program doesn't fail?

I wrote a program that asks for user input (numbers), then tells the user which of the two numbers they put in are bigger after making sure both values are numbers. This is looped. The problem is, when the user enters something that isn't valid, the program shuts down instead of referring to my else statements. I think this is because text values in strings cannot be processed using parseInt() so instead of the program realizing that a text value isn't a valid number, it just fails. I am using BlueJ to make this program if that helps anyone solve the problem. I am also open to people telling me how to make my program more efficient/easier to code (I am a beginner).
import java.util.Scanner;
public class TemperatureDriver {
public static void main(String[] args) {
while (true) {
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter a number"+ "\n");
String number_one = keyInput.next();
if (Integer.parseInt(number_one) <=0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if(Integer.parseInt(number_two) <=0 || Integer.parseInt(number_two) > 0){
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) < Integer.parseInt(number_two)){
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) == Integer.parseInt(number_two)){
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
}
}
}
Your code where you call parseInt should be embedded in a try block, which should be followed by a catch block to catch the NumberFormatException.
try {
if (Integer.parseInt(number_one) <= 0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if (Integer.parseInt(number_two) <= 0 || Integer.parseInt(number_two) > 0) {
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) < Integer.parseInt(number_two)) {
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) == Integer.parseInt(number_two)) {
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}

Trying to mimic Splitwise app logic - suggest a better way to handle settlements

I am trying to write the basic logic used in apps like Splitwise.
Input - Transactions in the trip
a|a,b,c,d|120
b|a,b,d|210
c|a,b,c,d|40
a|a,b,c|60
a, b, c and d are friends on a trip
in the first transaction a paid 120 units for a transaction involving all four friends
in the second transaction b paid 210 units for a transaction involving only a, b and d
there are n such transactions and there can be m friends
Expected Output
a has to get 50
b has to get 80
c has to give 20
d has to give 110
d has to give 80 to b
d has to give 30 to a
c has to give 20 to a
This is what I tried. Person class is the pojo used.
public class Person {
private String name;
private Integer totalExpense;
private Integer totalSpent;
private Integer balanceAmt;
}
This is the code for settle operation.
public void settle(Map<String, Person> personMap) {
List<Person> getterList = new ArrayList<>();
List<Person> giversList = new ArrayList<>();
for (String key : personMap.keySet()) {
Person user = personMap.get(key);
int balanceAmt = user.getTotalSpent() - user.getTotalExpense();
user.setBalanceAmt(Math.abs(balanceAmt));
if (balanceAmt > 0) {
System.out.println(key + " has to get " + balanceAmt);
getterList.add(user);
} else if (balanceAmt < 0) {
System.out.println(key + " has to give " + Math.abs(balanceAmt));
giversList.add(user);
} else if (balanceAmt == 0) {
System.out.println(key + " is all settled");
}
}
getterList.sort((p2, p1) -> p1.getBalanceAmt().compareTo(p2.getBalanceAmt()));
giversList.sort((p2, p1) -> p1.getBalanceAmt().compareTo(p2.getBalanceAmt()));
giversList.forEach(giver -> {
getterList.forEach(getter -> {
if (getter.getBalanceAmt() == 0) {
return;
}
if (giver.getBalanceAmt() == getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + giver.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(0);
getter.setBalanceAmt(0);
} else if (giver.getBalanceAmt() > getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + getter.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(giver.getBalanceAmt() - getter.getBalanceAmt());
getter.setBalanceAmt(0);
} else if (giver.getBalanceAmt() < getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + giver.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(0);
getter.setBalanceAmt(getter.getBalanceAmt() - giver.getBalanceAmt());
}
});
});
}
The code is not good, it has too many loops.
Suggest a good method to settle the amount and come up with the second part of the output.
Reduce your bottom part's logic from O(m2) to O(m) by using two pointer.
int giverPointer = 0;
int getterPointer = 0;
while(giverPointer < giversList.size() && getterPointer < getterList.size()){
if (giversList.get(giverPointer).getBalanceAmt() == getterList.get(getterPointer).getBalanceAmt()) {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + giversList.get(giverPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(0);
getterList.get(getterPointer).setBalanceAmt(0);
giverPointer++;
getterPointer++;
} else if (giversList.get(giverPointer).getBalanceAmt() > getterList.get(getterPointer).getBalanceAmt()) {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + getterList.get(getterPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(giversList.get(giverPointer).getBalanceAmt() - getterList.get(getterPointer).getBalanceAmt());
getterList.get(getterPointer).setBalanceAmt(0);
getterPointer++;
} else {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + giversList.get(giverPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(0);
getterList.get(getterPointer).setBalanceAmt(getterList.get(getterPointer).getBalanceAmt() - giversList.get(giverPointer).getBalanceAmt());
giverPointer++;
}
}

show result in crores,lacs,thousands android

I want to show my edit text result in crores,lacs and thousands user enter values in integer and double.
I want result like this:
sample1
sample2
public class NumberToWord
{
private static String input;
private static int num;
private static String[] units=
{"",
" One",
" Two",
" Three",
" Four",
" Five",
" Six",
" Seven",
" Eight",
" Nine"
};
private static String[] teen=
{" Ten",
" Eleven",
" Twelve",
" Thirteen",
" Fourteen",
" Fifteen",
" Sixteen",
" Seventeen",
" Eighteen",
" Nineteen"
};
private static String[] tens=
{ " Twenty",
" Thirty",
" Forty",
" Fifty",
" Sixty",
" Seventy",
" Eighty",
" Ninety"
};
private static String[] maxs=
{"",
"",
" Hundred",
" Thousand",
" Lakh",
" Crore"
};
public String convertNumberToWords(int n)
{
input=numToString(n);
String converted="";
int pos=1;
boolean hun=false;
while(input.length()> 0)
{
if(pos==1) // TENS AND UNIT POSITION
{ if(input.length()>= 2) // TWO DIGIT NUMBERS
{
String temp=input.substring(input.length()-2,input.length());
input=input.substring(0,input.length()-2);
converted+=digits(temp);
}
else if(input.length()==1) // 1 DIGIT NUMBER
{
converted+=digits(input);
input="";
}
pos++;
}
else if(pos==2) // HUNDRED POSITION
{
String temp=input.substring(input.length()-1,input.length());
input=input.substring(0,input.length()-1);
if(converted.length()> 0&&digits(temp)!="")
{
converted=(digits(temp)+maxs[pos]+" and")+converted;
hun=true;
}
else
{
if
(digits(temp)=="");
else
converted=(digits(temp)+maxs[pos])+converted;hun=true;
}
pos++;
}
else if(pos > 2) // REMAINING NUMBERS PAIRED BY TWO
{
if(input.length()>= 2) // EXTRACT 2 DIGITS
{
String temp=input.substring(input.length()-2,input.length());
input=input.substring(0,input.length()-2);
if(!hun&&converted.length()> 0)
converted=digits(temp)+maxs[pos]+" and"+converted;
else
{
if(digits(temp)=="") ;
else
converted=digits(temp)+maxs[pos]+converted;
}
}
else if(input.length()==1) // EXTRACT 1 DIGIT
{
if(!hun&&converted.length()> 0)
converted=digits(input)+maxs[pos]+" and"+converted;
else
{
if(digits(input)=="") ;
else
converted=digits(input)+maxs[pos]+converted;
input="";
}
}
pos++;
}
}
return converted;
}
private String digits(String temp) // TO RETURN SELECTED NUMBERS IN WORDS
{
String converted="";
for(int i=temp.length()-1;i >= 0;i--)
{ int ch=temp.charAt(i)-48;
if(i==0&&ch>1 && temp.length()> 1)
converted=tens[ch-2]+converted; // IF TENS DIGIT STARTS WITH 2 OR MORE IT FALLS UNDER TENS
else if(i==0&&ch==1&&temp.length()==2) // IF TENS DIGIT STARTS WITH 1 IT FALLS UNDER TEENS
{
int sum=0;
for(int j=0;j < 2;j++)
sum=(sum*10)+(temp.charAt(j)-48);
return teen[sum-10];
}
else
{
if(ch > 0)
converted=units[ch]+converted;
} // IF SINGLE DIGIT PROVIDED
}
return converted;
}
private String numToString(int x) // CONVERT THE NUMBER TO STRING
{
String num="";
while(x!=0)
{
num=((char)((x%10)+48))+num;
x/=10;
}
return num;
}
private void inputNumber()
{
Scanner in=new Scanner(System.in);
try
{
System.out.print("Please enter number to Convert into Words : ");
num=in.nextInt();
}
catch(Exception e)
{
System.out.println("Number should be Less than 1 Arab ");
System.exit(1);
}
}
public static void main(String[] args)
{
NumberToWord obj=new NumberToWord();
obj.inputNumber();
System.out.println("input in Words : "+obj.convertNumberToWords(num));
}
}

Calling method on an object, and using same object as parameter for method

I am working on a java program for creating a slot machine. The program works how I want it to but I am not sure if one of my method calls is proper java etiquette. In my main method below, inside my for loop, I call the method rollAndCompare() on the FourTumblers object, machine. This method returns an integer, coin, which represents how much the user won based on the number of tumblers matched. This if-else statement is written in the FourTumblers class. However, I also pass the same machine object as a parameter so that the method can access the tumbler values of the object. Is there a better way to do this? Is this correct?
public static void main(String[] args) {
int coins;
int addtLives;
int bank = 0;
int lives = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter how many games you want to play:");
int num = scan.nextInt();
System.out.println("You have decided to play " + num + " games.\n");
for (int i = 1; i <= num; i++) {
FourTumblers machine = new FourTumblers();
coins = machine.rollAndCompare(machine);
bank += coins;
addtLives = coins/100;
lives += addtLives;
System.out.println("You won " + coins + " coins. That's " + addtLives + " lives.");
System.out.println("You now have a total of " + bank + " coins and " + lives + " lives.\n");
}
scan.close();
}
Here is my rollAndCompare method...
public int rollAndCompare(FourTumblers machine) {
value1 = machine.getValue1();
value2 = machine.getValue2();
value3 = machine.getValue3();
value4 = machine.getValue4();
if ((value1 == value2)&&(value2 == value3)&&(value3 == value4)){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
System.out.println("Jackpot!");
coins = 600;
return coins;
}
else if (((value1 == value2)&&(value2 == value3))||((value1 == value3)&&(value3 == value4))||((value1 == value2)&&(value2 == value4))||((value2 == value3)&&(value3 == value4))){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 300;
return coins;
}
else if ((value1 == value4)||(value1 == value2)||(value1 == value3)||(value2 == value3)||(value2 == value4)||(value3 == value4)){
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 100;
return coins;
}
else{
System.out.println(value1 + " | " + value2 + " | " + value3 + " | " + value4);
coins = 0;
return coins;
}
}
The times you would want to add an object onto itself in a class is if you are going to compare it with other objects from the same class.
Ex:
public class Sample
{
private String name = "Sample Chocolate";
private int cost = 1;
public boolean compareSample(Sample sample)
{
if (sample.name.equals(name) && cost == sample.cost)
return true;
else
return false;
}
Then from another class:
public class SampleTester
{
public static void main(String[] args)
{
Sample sample1 = new Sample();
Sample sample2 = new Sample();
System.out.println("Are sample one and sample two the same?: " + sample1.compareSample(sample2));
}
}
Otherwise you can simply put nothing inside the parenthesis:
public boolean compareSample()
{
if (name.equals("Sample Chocolate") && cost == 1)
return true;
else
return false;
}
As Ashiquzzman eloquently said: You can call that using this.getValue(), you don't need to pass machine (to be used as machine.getValue()).

Categories

Resources