I want the integer that was asked to the user to go to the Cat class so it outputs the word "meow" until the counter is equal to the number - parameter-passing

This is the main method.
I want the integer that was asked to the user to go to the Cat class so it outputs the word "meow" until the counter is equal to the number
import java.util.Scanner;
public class Runnable {
**public static void main( String args[]) {
Scanner input = new Scanner(System.in);
Cat cat1 = new Cat();
System.out.print("Enter num :");
int num.sound()=input.nextInt();
System.out.println("Calling method with no parameters");
cat1.sound();
System.out.println("Calling method with one parameter");
cat1.sound();
}
}
this is a Class called Cat
public class Cat {
public void sound() {
System.out.println("Meow");
}
public void sound( int num){
int counter=0;
for(int num1=counter; num1>=num; counter++) {
System.out.println("Meow");
}
}
}

A couple of things first:
what you mean with the line:
int num.sound()=input.nextInt();
you not pass paramenters in
System.out.println("Calling method with no parameters");
cat1.sound();
System.out.println("Calling method with one parameter");
cat1.sound();
But the main flow is in the for loop that could be:
for (int num1 = 0; num1 < num; num1++)
{ ... }

Related

Lifecycle of #After method

I am trying to gather some information after every test method, and would like to analyze the gathered information after the test class completes. So, I have a private member variable, a list which I would like to add to after every test method completes. However, at the end of the day, the member variable always remains null.
Note: My test class implements Callable interface.
Here is my code snippet:
{
private List<String statisticsCollector;
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
this.statisticsCollector = new ArrayList<String>();
}
#Override
public List<String> call() {
log.info("Starting a new thread of execution with Thread# -" + Thread.currentThread().getName());
core.run(this.getClass());
return getStatisticsCollector(); // this is always returing a list of size 0
}
#After
public void gatherSomeStatistics() {
x = x+1;
String sb = new String("Currently executing ----" + x);
log.info("Currently executing ----" + x);
addToStatisticsCollector(sb);
}
#Test
#FileParameters(value = "classpath:folder/testB.json", mapper = MyMapper.class)
public void testB(MarsTestDefinition testDefinition) {
runTests(testDefinition);
}
#Test
#FileParameters(value = "classpath:folder/testA.json", mapper = MyMapper.class)
public void testA(MyDefinition testDefinition) {
runTests(testDefinition);
}
public List<String> getStatisticsCollector() {
return this.statisticsCollector;
}
public void addToStatisticsCollector(String sb) {
this.statisticsCollector.add(sb);
}
}
So, why is it always getting reset, even though I am appending to the list in my #After annotated method?
Any help will be highly appreciated. Thanks
Try with following code, is it working ?
private static List<String> statisticsCollector = new ArrayList<String>();
private JUnitCore core = null;
private int x = 0;
public MyLoadTest() {
this.core = new JUnitCore();
}
public List<String> getStatisticsCollector() {
return statisticsCollector;
}

Getting a constructor error in processing

I'm playing with processing from some days, but I encountered an error that i didn't understand. I declared the class and the constructor with the proper arguments, maybe you can help me. This is the code:
Cell[][] grid;
int rnc = 5;
int side = 5;
void setup(){
size(rnc*side,rnc*side);
grid = new Cell[rnc][rnc];
for(int i = 0; i < rnc; i++){
for(int j = 0; j < rnc; j++){
grid[i][j] = new Cell(i,j);
rect(grid[i][j].row*side,grid[i][j].column*side,side,side);
}
}
}
void draw(){}
class Cell
{
boolean isChecked;
int row,column;
int side;
void Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
void toggleCheck(){
if(isChecked == true){
isChecked = false;
}else{
isChecked = true;
}
}
}
The error I got after i tried to ran the program is : The constructor sketch.Cell(int,int) is undefined.
Thank you in advance.
I'm assuming this is Java, although you haven't specified a language. If so, this is the problem:
void Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
That's not a constructor. That's a method called Cell, with a void return type. You meant:
Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
(Or possibly public Cell(...).)
At that point, you should be okay. Note that this would have been a compile-time error - not an execution-time error. Don't try to run your code until it compiles.
Also, it's not clear why you've made your constructor parameters trow and tcolumn - what's the t meant to be for? I'd also make your variables private, and final if possible, and simplify your toggleCheck method. For example:
public final class Cell {
private final int row, column;
private boolean checked;
// It's not clear what side was for
public Cell(int row, int column) {
this.row = row;
this.column = column;
}
public void toggleChecked() {
checked = !checked;
}
public boolean isChecked() {
return checked;
}
}

How to attach a DataPoint with a Theory?

#DataPoints public static final Integer[] input1={1,2};
#Theory
#Test
public void test1(int input1){
}
#DataPoints public static final Integer[] input2={3,4};
#Theory
#Test
public void test2(int input2 ){
}
I want that test1 runs with data set input1 - {1,2} and test2 runs with input2 - {3,4}. But currently each test runs with both the data sets {1,2,3,4}. How to bind specific #DataPoints to specific #Theorys
With JUnit 4.12 (not sure when it was introduced) it is possible to name the DataPoints and assign them to parameters (i learned it from http://farenda.com/junit/junit-theories-with-datapoints/):
#RunWith(Theories.class)
public class TheoriesAndDataPointsTest {
#DataPoints("a values")
public static int[] aValues() {
return new int[]{1, 2};
}
#DataPoints("b values")
public static int[] bValues() {
return new int[]{3, 4};
}
#Theory
public void theoryForA(#FromDataPoints("a values") int a) {
System.out.printf("TheoryForA called with a = %d\n", a);
}
#Theory
public void theoryForB(#FromDataPoints("b values") int a) {
System.out.printf("TheoryForB called with b = %d\n", a);
}
}
Output:
TheoryForA called with a = 1
TheoryForA called with a = 2
TheoryForB called with b = 3
TheoryForB called with b = 4
DataPoints apply to the class. If you have a #Theory method which takes an int, and you have a DataPoint which is an array of ints, then it will be called with the int.
#RunWith(Theories.class)
public class TheoryTest {
#DataPoint public static int input1 = 45;
#DataPoint public static int input2 = 46;
#DataPoints public static String[] inputs = new String[] { "foobar", "barbar" };
#Theory public void testString1(String input) {
System.out.println("testString1 input=" + input);
}
#Theory public void testString2(String input) {
System.out.println("testString2 input=" + input);
}
#Theory public void test1(int input) {
System.out.println("test1 input=" + input);
}
#Theory public void test2(int input) {
System.out.println("test2 input=" + input);
}
}
This calls test1 with 45 & 46, and test2 with 45 & 46. It calls testString1 with "foobar" and "barbar" and testString2 with "foobar" and "barbar".
If you really want to use different data sets for different theories, you can wrap the data in a private class:
#RunWith(Theories.class)
public class TheoryTest {
public static class I1 { int i; public I1(int i) { this.i = i;} }
public static class I2 { int i; public I2(int i) { this.i = i;} }
#DataPoint public static I1 input1 = new I1(45);
#DataPoint public static I2 input2 = new I2(46);
#Theory
public void test1(I1 input) {
System.out.println("test1 input=" + input.i);
}
#Theory
public void test2(I2 input) {
System.out.println("test2 input=" + input.i);
}
}
This calls test1 with 45 and test2 with 46. This works, but in my opinion, it obscures the code, and it may be a better solution to just split the Test class into two classes.
In reference to Gábor Lipták's answer, named datapoints can be defined as a static fields (reference) which give us more concise code:
#RunWith(Theories.class)
public class TheoriesAndDataPointsTest {
#DataPoints("a values")
public static int[] aValues = {1, 2};
#DataPoints("b values")
public static int[] bValues = {3, 4};
#Theory
public void theoryForA(#FromDataPoints("a values") int a) {
System.out.printf("TheoryForA called with a = %d\n", a);
}
#Theory
public void theoryForB(#FromDataPoints("b values") int a) {
System.out.printf("TheoryForB called with b = %d\n", a);
}
}
Some of the references I have seen talking about using tests for specific values and theories for verifying behavior. As an example, if you have a class that has methods to add and subtract from an attribute, a test would verify correctness of the result (e.g., 1+3 returns 4) whereas a theory might verify that, for the datapoint values (x1, y1), (x2, y2), x+y-y always equals x, x-y+y always equals x, x*y/y always equals x, etc. This way, the results of theories are not coupled as tightly with the data. With theories, you also can filter out cases such as y == 0; they don't count as failure. Bottom line: you can use both. A good paper is: http://web.archive.org/web/20110608210825/http://shareandenjoy.saff.net/tdd-specifications.pdf

Line Wrapping Cell Renderer - Java

I am having trouble implementing a custom cell renderer which will wrap message content when it extends past one line in length. The following is what I have:
public class MessageTable extends JTable
{
private static MessageTable messageTable;
private DefaultTableModel model = new DefaultTableModel();
private String[] emptyData = {};
private TreeMap<Integer, String> messages = null;
public class LineWrapCellRenderer extends JTextArea implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
this.setText((String)value);
this.setWrapStyleWord(true);
this.setLineWrap(true);
this.setBackground(Color.YELLOW);
int fontHeight = this.getFontMetrics(this.getFont()).getHeight();
int textLength = this.getText().length();
int lines = textLength / this.getColumns() +1;//+1, because we need at least 1 row.
int height = fontHeight * lines;
table.setRowHeight(row, height);
return this;
}
}
public MessageTable()
{
super();
messageTable = this;
this.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
model.addColumn("Message Number", emptyData);
model.addColumn("Message Content", emptyData);
this.setModel(model);
this.setFont(MappingView.theFont);
this.setDefaultRenderer(String.class, new LineWrapCellRenderer());
}
/**
* Set the current messages.
* #param messages
*/
public void setCurrentMessages(TreeMap<Integer, String> messages)
{
clearCurrentMessages();
this.messages = messages;
if (messages != null)
{
for (Integer key : messages.keySet())
{
String[] row = { key.toString(), messages.get(key).toString() };
model.addRow(row);
}
}
}
For some reason, the LineWrapCellRenderer is never used and the rows only ever contain one line of text.
What am I doing wrong?
Your cellrenderer is not used because the default table model returns Object.class for any column (it does not override AbstractTableModel's implementation):
public Class<?> getColumnClass(int columnIndex) {
return Object.class;
}
So either override the method yourself for the model or assign the renderer to Object.class.

How do I implement a fibonacci sequence in java using try/catch logic?

I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it.
So far I have:
public static int fibo(int index) {
int sum = 0;
try {
fibo_aux(index, 1, 1);
}
catch (IntegerException me) {
sum = me.getIntValue();
}
return sum;
}
fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?
I don't know what your implementations for fibo_aux and IntegerException look like, but the following two implementations work with your existing code (I don't think there's anything wrong with the code you posted, so I assume something is awry in either fibo_aux or IntegerException). Maybe you'll find this helpful.
public static void fibo_aux(int index, int a, int b) throws IntegerException
{
if (--index > 0)
fibo_aux(index, b, a + b);
else
throw new IntegerException(a + b);
}
An implementation for IntegerException:
public class IntegerException extends Exception
{
private static final long serialVersionUID = -6795044518321782305L;
private Integer intValue;
public IntegerException(int i)
{
this.intValue = i;
}
public Integer getIntValue()
{
return intValue;
}
}
Here you go :
public class ExcFib {
/**
* #param args
*/
public static void main(String[] args) {
new ExcFib().fibo ( 10 );
}
class FiboException extends Throwable
{
public int n;
public FiboException(int n)
{
this.n = n;
}
private static final long serialVersionUID = 1L;
}
public void fibo(int idx) {
try {
fibo_aux(idx-1,1,1);
} catch (FiboException e) {
System.out.println ( "F(" + idx + ") = " + e.n );
}
}
private void fibo_aux(int i, int j, int k) throws FiboException {
if ( i < 1 )
{
throw new FiboException(k);
}
fibo_aux(i - 1, k, j + k );
}
}