count the "IfStmt" statement in java parser - java

I am using javaparser to parse a java file , when I count the "If" statement it display the output as an incremental number such that Eg: if there are 3 "if" statements then it displays as
[
1
2
3
]
I want to get only the total number of "IF" statements. eg:[ 3].
I don't want to get all the incrementing count
This is my source code.
package org.javaparser.examples.chapter2;
public class VoidVisitorComplete {
private static final String FILE_PATH = "src/main/java/org/javaparser/samples/prime.java";
public static void main(String[] args) throws Exception {
CompilationUnit cu = StaticJavaParser.parse(new FileInputStream(FILE_PATH));
VoidVisitor<Void> methodNameVisitor = new IfStmtVisitor();
methodNameVisitor.visit(cu, null);
}
private static class IfStmtVisitor extends VoidVisitorAdapter<Void> {
int i=0 ;
#Override
public void visit(IfStmt n, Void arg) {
//visit a if statement, add 1
i++;
System.out.println( getNumber() );
}
public int getNumber() {
return i;
}
}
}

You have to put the print statement after all the if statements have been counted.
package org.javaparser.examples.chapter2;
public class VoidVisitorComplete {
private static final String FILE_PATH = "src/main/java/org/javaparser/samples/prime.java";
public static void main(String[] args) throws Exception {
CompilationUnit cu = StaticJavaParser.parse(new FileInputStream(FILE_PATH));
VoidVisitor<Void> methodNameVisitor = new IfStmtVisitor();
methodNameVisitor.visit(cu, null);
System.out.println(methodNameVisitor.getNumber());
}
}
private static class IfStmtVisitor extends VoidVisitorAdapter<Void> {
int i = 0;
#Override
public void visit(IfStmt n, Void arg) {
//visit a if statement, add 1
i++;
}
public int getNumber() {
return i;
}
}

Related

Junit 5 test failing when running togheter

Ok, so this test work individually fine, but for some reason, they fail when running together, as you can see, I real a String of values from a File.
When running together, it looks like the app stops reading the commands of the file after a few entries.
Any ideas?
One example of the file text:
10
10
5
5
e
3
3
3
1
5
at the second 3 of the sequence, the app stops reading the values.
All this test work individually.
#TestInstance(TestInstance.Lifecycle.PER_METHOD)
public class MarsRoverTest {
#BeforeEach
public void setUp() {
cleanUpMars();
}
//Test rover's movement
#Test
public void roverSetUp_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_SET_UP_OK)));
MarsRover.main(new String[]{});
assertEquals(RIGHT, Mars.getInstance().getMars()[5][5]);
}
#Test()
public void roverSetUp_OutOfMars() {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_SET_UP_ERROR)));
OutOfMarsException exception = assertThrows(OutOfMarsException.class, () ->
MarsRover.main(new String[]{}));
assertEquals("You set the Rover in the Space!", exception.getMessage());
}
#Test
public void roverMoveAround_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_MOVE_AROUND_OK)));
MarsRover.main(new String[]{});
assertEquals(RIGHT, Mars.getInstance().getMars()[5][0]);
}
//Test rover's rotation
#Test
public void roverRotateUp_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_ROTATE_UP_OK)));
MarsRover.main(new String[]{});
assertEquals(UP, Mars.getInstance().getMars()[4][5]);
}
//Test rover's rotation
#Test
public void roverRotateLeft_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_ROTATE_LEFT_OK)));
MarsRover.main(new String[]{});
assertEquals(LEFT, Mars.getInstance().getMars()[5][4]);
}
//Test rover's rotation
#Test
public void roverRotateDown_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_ROTATE_DOWN_OK)));
MarsRover.main(new String[]{});
assertEquals(DOWN, Mars.getInstance().getMars()[6][5]);
}
private byte[] getInstructions(String path) {
try {
return Files.readString(Path.of(path)).getBytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void cleanUpMars() {
Mars.getInstance().setMarsReady(true);
}
Mars is a Singleton instance
public class Mars {
private static Mars INSTANCE;
private int sizeX;
private int sizeY;
private String[][] mars; //Map of Mars
private boolean marsReady = false; //I hade to add this for the testing, needs improvement
private Mars(){
}
public static Mars getInstance() {
if(INSTANCE == null) {
INSTANCE = new Mars();
}
return INSTANCE;
}
Mars class is this:
package org.mars.entities;
import static org.mars.constants.MarsConstants.OBSTACLE;
import static org.mars.utils.ReaderUtils.requestInt;
/**
* Singleton class
*/
public class Mars {
private static Mars INSTANCE;
private int sizeX;
private int sizeY;
private String[][] mars; //Map of Mars
private boolean marsReady = false; //I hade to add this for the testing, needs improvement
private Mars(){
}
public static Mars getInstance() {
if(INSTANCE == null) {
INSTANCE = new Mars();
}
return INSTANCE;
}
public static void removeInstance() {
INSTANCE = null;
}
public int getSizeX() {
return sizeX;
}
public void setSizeX(int sizeX) {
this.sizeX = sizeX;
}
public int getSizeY() {
return sizeY;
}
public void setSizeY(int sizeY) {
this.sizeY = sizeY;
}
public String[][] getMars() {
return mars;
}
public void setMars(String[][] mars) {
this.mars = mars;
}
public boolean isMarsReady() {
return marsReady;
}
public void setMarsReady(boolean marsReady) {
this.marsReady = marsReady;
}
/**
* Define the size of the map for the rover
*/
public static void setMarsSize() {
System.out.println("Insert horizontal map size:");
getInstance().sizeX = requestInt();
System.out.println("Insert vertical map size:");
getInstance().sizeY = requestInt();
getInstance().mars = new String[INSTANCE.sizeX][INSTANCE.sizeY];
if(!getInstance().isMarsReady())
addObstacles();
}
/**
* Shows the map of Mars with the rover and obstacles
*/
public static void printMars(){
for (String[] placeX: INSTANCE.mars) {
System.out.print("|");
for (String placeY: placeX) {
if(placeY != null && !placeY.isBlank())
System.out.print("_" + placeY + "_");
else System.out.print("___");
System.out.print("|");
}
System.out.println();
}
}
/**
* Add obstacles for the mars Map
*/
private static void addObstacles() {
int min = 0;
int numberOfObstacles = (int)(Math.random() * getInstance().sizeX * getInstance().sizeY / 10) + min;
for (int i = 0; i < numberOfObstacles; i++) {
int randomX = (int)(Math.random() * getInstance().sizeX -1) + min;
int randomY = (int)(Math.random() * getInstance().sizeY -1) + min;
getInstance().mars[randomX][randomY] = OBSTACLE;
}
}
}
And the main app:
public static void main(String[] args) throws OutOfMarsException {
try {
reader = new Scanner(System.in);
//Map size configured
setMarsSize();
//Rover initial position
roverCar.setRoverPosition();
//Show mars map
printMars();

How to pass the correct value when calling a method?

I'm doing an assignment in which I have created an Appliance class that has a timePasses()method within it. This method re-directs some values that need to be stored within another method that is inside of another class. Here is where I am up to on this:
Appliance
public class ElectricCooker extends Cooker {
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState() {
if (varPass == 0) {
return isOff;
} else {
return isOn;
}
}
#Override
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses() {
if (varPass == isOff) {
varPass = 0;
} else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter
public class ElectricMeter {
ElectricMeter() {
}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
System.out.println(value);
}
public int incrementGenerated() {
}
public boolean canGenerate() {
}
public String getConsumed() {
}
public String getGenerated() {
}
}
Main method
public class MainCoursework {
public static void main(String[] args) {
ElectricMeter a = new ElectricMeter();
a.incrementConsumed(//what goes here?);
}
}
So the value from timePasses()has been redirected into an ElectricMeter instance but now I need to return that value to the increentConsumed() method in the meter class and I'm stuck on how to do this. Since the value of electricityConsumed is 20, the output should be 20. But instead I have to pass a parameter into a.incrementConsumed(//pass parameter here) and what ever is passed gets printed out onto the screen instead of the 20 from electrictyUse. Any help on how to do this is appreciated, thanks.
Actually, the incrementConsumed method is indeed implemented as you described:
public void incrementConsumed(int value)
{
System.out.println(value);
}
A method called incrementXXX shouldn't really output anything, should it? It should increment a variable/field:
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
You should declare another method that returns electricityUsed:
public int getElectricityUsed() {
return electricityUsed;
}
Now let's fix your main method.
In your main method, you didn't even create anything that consumes electricity! How can the electric meter incrementConsumed? So remove everything from the main method and create a cooker:
// your constructor looks weird. So I passed in some random arguments..
ElectricCooker cooker = new ElectricCooker(20, 0, 0, 60);
Now call timePasses to simulate that some time passed:
cooker.timePasses();
And print the electricity used:
System.out.println(ElectricMeter.getInstance().getElectricityUsed());
you need to create an instance variable in ElectricMeter and update that value on say incrementConsumed. When you want to print that use accessor of this variable.
public class Electric {
public static void main(String[] args) {
ElectricCooker cooker = new ElectricCooker(1,2,3,4);
//opertion on cooker
//ignoring best way for singleton creation
int electricityUse = ElectricMeter.getInstance().getElectricityUse();
System.out.println(electricityUse);
}
}
class ElectricCooker // extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
public int electricityUse = -1;
public int currentState() {
if (varPass == 0)
return isOff;
else {
return isOn;
}
}
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
public void timePasses() {
if (varPass == isOff)
varPass = 0;
else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
this.electricityUse = 5 * incrementTime;
}
}
class ElectricMeter {
public int electricityUse = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
this.electricityUse = value;
}
public int getElectricityUse() {
return electricityUse;
}
}
In ElectricMeter, some operations don't perform what they should.
ElectricMeter.getInstance().incrementConsumed(electricityUse);
should increment something but it writes only in the output:
public void incrementConsumed(int value){
System.out.println(value);
}
You should write it rather :
public void incrementConsumed(int value){
consumed+=value;
}
and add a private int consumed field in ElectricMeter class to store the actual consumed.
And your getConsumed() which has a empty implementation :
public String getConsumed(){
}
should simply return the consumed field and you should return a int value and not a String.
public int getConsumed() {
return consumed;
}
In this way, you can do :
public static void main(String[] args){
ElectricMeter.getInstance().incrementConsumed(20);
int consumed = ElectricMeter.getInstance().getConsumed();
}

Java error - invalid method declaration; return type required

I'm trying to complete this java program, but every time I try to compile it I get this error. Can someone figure out why my program is doing this. It seems that no matter what I do I still happen to get an error on my program. I tried everything I know to see if it would work. Please someone help me.
import java.util.Scanner;
public class Period
{
private static String phrase;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
// this is where the error is occuring at.
public Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
The 'Sorter' method is missing a return type. It should be:
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0, newPhrase.indexOf("."));
}
The method is not called anywhere, so i am not sure if this is what you intended it to do.
add the void return type:
public void Sorter(String newPhrase) // HERE
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
There are a lot of errors in the above code - see below for some code that runs, though i can't be sure it does exactly what you want given the limited scope of the question.
I don't want to stray too far from the original question, but you should really consider using instance variables and encapsulating your data, rather than relying on static variables.
import java.util.Scanner;
public class Period
{
private static String phrase;
private static int[] alphabet = new int [27];
public static void main(String [] args)
{
System.out.println("Enter a sentence with a period at the end.");
Scanner keyboard = new Scanner(System.in);
phrase = keyboard.nextLine().toLowerCase();
Period period = new Period();
period.entryPoint();
}
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}

how this while(true) is working

package interf;
public class NumberPrinter {
public interface Printer {
public void print (int idx);
}
public static void print (Printer p) {
for (int i = 0; i < 4; i++) {
p.print(i);
}
}
public static void main(String[] args) {
while(true){
System.out.println("hi-1");
print(new Printer() {
#Override
public void print(int idx) {
while(true){
System.out.println(idx);
}
}
});
}
}
}
why it only printing 0 0 0
why it is not printing System.out.println("hi-1");
The code (when fixed to make system System) prints "hi-1" then lots of 0's (forever), because your inner print method has a while(true) loop in it.
The outer while(true) loop is never executed more than once because your code gets "stuck" in this inner loop, so you never see "hi-1" more than once.
Comment out the second while loop and capitalize the first letter of system.out.println and you'll get an infinite loop of:
hi-1
0
1
2
3
hi-1
0
1
2
3
...
package interf;
public class NumberPrinter {
public interface Printer {
public void print (int idx);
}
public static void print (Printer p) {
for (int i = 0; i < 4; i++) {
p.print(i);
}
}
public static void main(String[] args) {
while(true){
System.out.println("hi-1");
print(new Printer() {
#Override
public void print(int idx) {
//while(true){
System.out.println(idx);
//}
}
});
}
}
}

Java 'this' keyword

I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.
It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}
this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}
The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.
you are using operator + for your current object (this). Operator overloading is not supported in java.
Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.
i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}
You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}
This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}

Categories

Resources