How do I properly write out a JUnit test for a method that counts how many e's are in a string? - testing

Here is the method I have defined that is supposed to accept a String as input and should return the number of times the char 'e' occurs as an int:
public int count_e(String input){
int count = 0;
for (int i = 0;i<input.length();i++){
char e = 'e';
if (input.charAt(i)==e){
count=count+1;
i++;
return count;
}
else{
count=count+1;
i++;
}
}
return count;
}
}
I am trying to write a JUnit test to see if I can input a string into the method and return the correct number of e's. Below is my test, and at the moment I keep getting an error saying that my method count_e is undefined for type String.
Can someone tell me why it is coming up as undefined?
#Test
public void testCount_e() {
String input= "Isabelle";
int expected= 2;
int actual=input.count_e();
assertTrue("There are this many e's in the String.",expected==actual);
}
}

You failed to pass anything to your count_e method!
How about something like:
#Test
public void testCount_e() {
String input = "Isabelle";
int expected = 2;
int actual = count_e(input);
Assert.assertEqual("There are this many e's in the String.", expected, actual);
}
For a unit test, you could probably shorten it to:
#Test
public void testCount_e() {
Assert.assertEqual("There are this many e's in the String.", count_e("Isabelle"), 2);
}

Related

C# main method cannot run program

I am doing this C# code for my homework for calculating sum and substract
for the sum it is working fine, but I don't know how to code for two math equation as a code. I am thinking of the way I put the main method and brackets? There's only one error which what I have commented // on it.
Thank you in advance for your time.
using System;
namespace pg392mod
{
internal class Program
{
private static void Main(string[] args)
{
int firstNumber = 10;
int secondNumber = 2;
int result;
//2 call the method calculatesum and pass the 2 parameters to it
result = CalculateSum(firstNumber, secondNumber);
//3 write to console the result of the sum of the 2 numbers
Console.WriteLine("Sum of {0} and {1} is = {2}.", firstNumber, secondNumber, result);
Console.ReadLine();
}
public static int CalculateSum(int n1, int n2)
{
int sum;
sum = n1 + n2;
return sum;
}
//this is the error private static void Main(string[] args)
{
int firstNumber = 10;
int secondNumber = 2;
int result;
//2 call the method calculatesum and pass the 2 parameters to it
result = CalculateSum(firstNumber, secondNumber);
//3 write to console the result of the sum of the 2 numbers
Console.WriteLine("Substraction of {0} and {1} is = {2}.", firstNumber, secondNumber, result);
Console.ReadLine();
}
public static int CalculateSubstract(int n1,int n2)
{
int sub;
sub = n1 - n2;
return sub;
}
}
}
The error is thrown as you duplicated main definition. Items declared static must be unique as there is only one instance of them within the scope that they are declared.
Commenting out the line leaves you with a block of code, encompassed by { and } that is left floating and not within a defined scope.
The following would be better:
using System;
namespace pg392mod
{
internal class Program
{
private static void Main(string[] args)
{
int firstNumber = 10;
int secondNumber = 2;
int result;
//2 call the method calculatesum and pass the 2 parameters to it
result = CalculateSum(firstNumber, secondNumber);
//3 write to console the result of the sum of the 2 numbers
Console.WriteLine("Sum of {0} and {1} is = {2}.", firstNumber, secondNumber, result);
Console.ReadLine();
//2 call the method calculatesubtract and pass the 2 parameters to it
result = CalculateSubtract(firstNumber, secondNumber);
//3 write to console the result of the sum of the 2 numbers
Console.WriteLine("Substraction of {0} and {1} is = {2}.", firstNumber, secondNumber, result);
Console.ReadLine();
}
public static int CalculateSubtract(int n1,int n2)
{
int sub;
sub = n1 - n2;
return sub;
}
public static int CalculateSum(int n1, int n2)
{
int sum;
sum = n1 + n2;
return sum;
}
}
}

Adding message to faceContext is not working in Java EE7 run on glassFish?

I am doing the tutorial on Java EE7 that comes with glassFish installation. It is also available here. The code is present in glassFish server installation directory
/glassFish_installation/glassfish4/docs/javaee-tutorial/examples/cdi/guessnumber-cdi.
The code works fine as it is. It currently displays correct! when a user correctly guesses the number but does not display failed at end of the game. so I introduced, just one minor change to display the failed message. I have added comments right above the relevant change in code.
Somehow, this change did not help. That is, the at the end of the game, failed message is not displayed.
But the game works as usual. I would like to know why this did not work and how to correct it?
Thanks
public class UserNumberBean implements Serializable {
private static final long serialVersionUID = -7698506329160109476L;
private int number;
private Integer userNumber;
private int minimum;
private int remainingGuesses;
#Inject
#MaxNumber
private int maxNumber;
private int maximum;
#Inject
#Random
Instance<Integer> randomInt;
public UserNumberBean() {
}
public int getNumber() {
return number;
}
public void setUserNumber(Integer user_number) {
userNumber = user_number;
}
public Integer getUserNumber() {
return userNumber;
}
public int getMaximum() {
return (this.maximum);
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
public int getMinimum() {
return (this.minimum);
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public int getRemainingGuesses() {
return remainingGuesses;
}
public String check() throws InterruptedException {
if (userNumber > number) {
maximum = userNumber - 1;
}
if (userNumber < number) {
minimum = userNumber + 1;
}
if (userNumber == number) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Correct!"));
}
//if remainingGuesses is less than or equal to zero, display failed message
//-----------------------------------------------
if (remainingGuesses-- <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
return null;
}
#PostConstruct
public void reset() {
this.minimum = 0;
this.userNumber = 0;
this.remainingGuesses = 10;
this.maximum = maxNumber;
this.number = randomInt.get();
}
public void validateNumberRange(FacesContext context,
UIComponent toValidate,
Object value) {
int input = (Integer) value;
if (input < minimum || input > maximum) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("Invalid guess");
context.addMessage(toValidate.getClientId(context), message);
}
}
}
Adding the FacesMessage is actually working, the problem is that you are using postdecrement in your condition.
Postdecrement, as the name suggests, is decremented AFTER the execution of the statement containing the postdecrement.
That means, if you write:
if (remainingGuesses-- <= 0) {
the var remainingGuesses is decremented after the if-condition was evaluated.
In your case, when the last guess is checked, remainingGuesses is actually 1 and therefore the if-condition is not true and the message is not added.
Different obvious solutions:
if (remainingGuesses-- <= 1) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
or
if (--remainingGuesses <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
or
remainingGuesses--;
if (remainingGuesses <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
See also:
Is there a difference between x++ and ++x in java?
Difference between i++ and ++i in a loop?

How to determine input datatype?

I want to accept two inputs. If both the inputs are integer then add them. If any or both the inputs are string then concatenate them. I want to know the code to determine whether the input is integer or string?
Thanks for reading...
You can use method overloading for this,
Check out Java code given below
public class MethodExample
{
public static void main (String[] args)
{
int a,b;
String string1,string2;
//accept values for all variables...;>>
System.Out.Println("Addtion is "+sum(a,b));
System.Out.Println("Contact is "+sum(string1,string2));
}
int sum(int a,int b)
{
return(a+b);
}
String sum(string a,string b)
{
return(a+b);
}
}
I have used the following logic:
Console.WriteLine("Enter two inputs:");
string s1 = Console.ReadLine();
string s2 = Console.ReadLine();
double num;
int s3;
string s4;
bool isNum1 = double.TryParse(s1, out num);
bool isNum2 = double.TryParse(s2, out num);
if( isNum1==true && isNum2==true)
{
s3 = Convert.ToInt32(s1) + Convert.ToInt32(s2);
Console.WriteLine("Output = {0}", s3);
}
else
{
s4 = s1 + s2;
Console.WriteLine("Output = {0}",s4);
}

Null pointer exception with a method call

Ok this is the code for one section of my switch statement:
case 1: {
System.out.print("Member ID: ");
int key = in.nextInt();
while(members.findItemByKey(key) == -1){
System.out.print("That is an invalid member ID!\nEnter a new one: ");
key = in.nextInt();
}
System.out.print("ISBN: ");
int book = in.nextInt();
while(books.findItemByKey(book) == -1){
System.out.println("That book is not in the system.\nPlease make a new choice: ");
book = in.nextInt();
}
while(stock.findItemByKey(book) != -1){
try {
m = members.get(members.findItemByKey(key));
t = books.get(books.findItemByKey(book));
} catch (Exception e) {
e.printStackTrace();
}
if(m.checkOut(t) == true){
stock.removeItem(t);
}
}
}
Here is the method that is calling:
public int findItemByKey(int key){
for(E e: list)
{
if(e.getKey() == key){
return findItem(e);
}
}
return -1;
}
public int findItem(E item){
if (item == null){
for (int i = 0; i < numElements; i++)
if(list[i]==null)
return i;
}else {
for( int i = 0; i < numElements; i++)
if (item.equals(list[i]))
return i;
}
return -1;
}
Ok, I know there's a lot to look at here, but here's what's happening. When I enter an invalid member ID, it functions properly and keeps asking the user for a new member ID until a valid one is entered. Now when I enter a book, regardless of whether I enter a valid or invalid book, I am getting a null pointer exception thrown by this line:
if(e.getKey() == key)
books, members, and stock are all arraylists defined the same way in my code. I don't understand why I'm having this exception thrown with books and not with the members. The classes for book and member are defined the same way, both have the same getKey method within them.
Maybe there's just too much going on in this question for anyone to be able to really see what's going on. Basically I just can't understand why I get a null pointer exception with the one and not with the other.
Edit: Decided I should post the getKey() method for each class.
public int getKey()
{
return ISBN;
}
Is the one for books
public int getKey()
{
return memberId;
}
Is the one for members.
ISBN is the identifier for books and memberId is the identifier for my members. Everything looks like it's calling the same things, but it errors for books and not for members. Just don't get it.
Either this e is null or the value returned from the statement e.getKey() is null.
You have to make sure that the list doesn't contain a null element and then their keys should also be not-null.
If you want to ignore these values being null, you can do like:
if(e!=null && e.getKey()!=null && e.getKey() == key){
//statements here.
}

NullPointerException when object is instantiated

This is a homework, I would appreciate any kind of answer.
Im trying to figure out why i keep getting a NullPointerException when i call the equals method. I have instantiated the object if im not mistaken, but it still doesn't work.
Exception in thread "main" 8
java.lang.NullPointerException
at labbfyra.TextBuilder.equals(TextBuilder.java:69)
at labbfyra.SkapaOrd.main(SkapaOrd.java:17)
Is this the stacktrace?
public class TextBuilder {
private static class Node{
public char inChar;
public Node next;
public Node(char c, Node nästa){
inChar = c;
next = nästa;
}
}
private Node first = null;
private Node last = null;
public TextBuilder(){
first = null;
last = null;
}
public void append(String s){
int x = s.length();
for(int i=0;i<x;i++){
Node n = new Node(s.charAt(i),null);
if(first ==null){
first = n;
last = n;
}else{
last.next = n;
last = n;
}
}
}
public int ShowSize(){
int counter = 0;
Node n = first;
while(n!=null){
counter++;
n=n.next;
}
return counter;
}
public boolean equals(String s){
boolean eq = false;
int counter = 0;
char[] cArray = s.toCharArray();
char[] cArrayComp = new char[10];
Node n = first;
cArrayComp[counter] = n.inChar;
while(n!=null){
counter++;
n=n.next;
cArrayComp[counter] = n.inChar; //THIS IS LINE 69
}
if(cArrayComp==cArray){
eq = true;
}
else{
eq=false;
}
return eq;
}
}
In your while loop, you check that n is not null, but then you assign n.next to n just before accessing n. The problem is that you do not ensure that the assigned value (n.next) is not null.
At a quick glance, looks like the counter variable in your while loop is going past the 10 you set your cArrayComp size to. Perhaps the string parameter being passed is longer than 10 chars?
public boolean equals(String s){
boolean eq = false;
int counter = 0;
char[] cArray = s.toCharArray();
char[] cArrayComp = new char[10];
Node n = first;
while(n!=null){
System.out.println(counter);
cArrayComp[counter] = n.inChar;
System.out.println(cArrayComp[counter]);
System.out.println(n.inChar);
n=n.next;
counter++;
}
if(cArrayComp==cArray){
eq = true;
}
else{
eq=false;
}
return eq;
}
This is the corrected version, i found a bug in your loop. Just check my version. Works at 100%