public static void main(String args[]){
extract("e:\\");
}
public static void extract(String p){
File f=new File(p);
File l[]=f.listFiles();
int counter = 0;
for(File x:l){
if(x.isDirectory()) extract(x.getPath());
else if(x.getName().endsWith(".mp3"))){
counter = counter + 1;
}
}
// I want to count and return value at last
}
Using this method(above), resets the counter every time when for loop ends.
So here, I want to count even when the for loop ends so that I can keep track of the number of .mp3 files.
I want to count and return value at last.
Return the current counter and make sure you add the response when you call recursively back to the counter.
public static void main(String args[]) {
int count = extract("../");
}
public static int extract(String p) {
File f = new File(p);
File l[] = f.listFiles();
int counter = 0;
for (File x : l) {
if (x.isDirectory()) {
counter += extract(x.getPath());
} else if (x.getName().endsWith(".mp3")) {
counter++;
}
}
return counter;
}
You should not use recursion like that. (Recursion should always have a termination condition to avoid running in a loop forever!
I think the problem is, that you create new Integers every time you call your method, so you will eventually override your old value or even use many different Integers to count.
You can wrap everything in a class in which you keep track of one integer.
Some pseudo-code:
public class Mp3Counter {
private int numberOfMp3 = 0;
public void extract(...) {
if (foundMp3) {
this.numberOfMp3 += 1;
}
}
}
Related
I am writing a stack data structure in java using arrays. The problem is when I try to push the users char input it doesn't display. The problem is with this code.
public static void preSuf(Stack stack) {
Scanner key = new Scanner(System.in);
System.out.println("enter the values");
while(key.hasNext()){
char c = key.next().charAt(0);
stack.push(c);
}
}
When I change the while(key.hasNext()) to if(key.hasNext()) it works but it only prints one time and doesnt itterate. How can I fix this problem thank you.
Edit: Here is the whole code
import java.util.Scanner;
public class Stack {
private int top;
private char[] container;
private int size;
public static int pos = 0;
// constructor
public Stack(int N) {
container = new char[N];
size = N;
top = 0;
}
public boolean isFull() {
return (size == top);
}
public void push(char string) {
if (!isFull()) {
container[top] = string;
top++;
} else {
return;
}
}
public int pop() {
int drop;
drop = container[top - 1];
container[top] = 0;
top--;
return drop;
}
public int peek() {
int drop2;
drop2 = container[top - 1];
return drop2;
}
public void display() {
for (int i = 0; i < container.length; i++) {
if (container[i] != 0) {
System.out.print(container[i]);
}
}
}
public static void preSuf(Stack stack) {
Scanner key = new Scanner(System.in);
System.out.println("enter the values");
while(key.hasNext()){
char c = key.next().charAt(0);
stack.push(c);
}
}
public static void main(String args[]) {
Stack stack = new Stack(3);
preSuf(stack);
stack.display();
stack.display();
System.out.println();
}
}
The problem is that you haven't written any code to actually print the contents of your stack.
You could write a loop after your while loop to iterate over the stack and print out each character.
You'll also need a way of exiting your while loop. You can do this either with a special character, eg. if(c == '.') break; or you can just press Ctrl+Z.
EDIT: Based on the edit to the question and the full code being presented, I think the suggestion of needing the extra loop is now redundant. You have that in stack.display(). You just need to get out of your while loop.
you haven't determined when the loop should end.
you'd think if you press enter without entering anything the loop
would break but that's not how next operates. if you press enter
without entering anything or input data which consists of only whitespaces, next will block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
the solution is to include a condition at which control should break out of the loop.
I am trying to write a function in Java that returns the next ascending sequence (run) from a txt file, let's say the return type of a function would be ArrayList.
My example file input.txt contains next values: 78123421. So in terms of runs that means the file has 4 runs: |78|1234|2|1|.
What am I trying to reach here is like when I would call this function from main() four times it should print something like
1.run: 78,
2.run: 1234,
3.run: 2,
4.run: 1
or just two calls should print
1.run: 78,
2.run: 1234
I have tryed to solve my problem using BufferedReader/FileReader and RandomAccessFile but no working solution so far, please help :/
So this is what I have so far. The main idea was to use RandomAccessFile and read from input as long as run condition is satisfied. But the reader reads one value more, that is why I use seek() to start reading at the right position when next function call happens. There must be a bug in the code, because it doesn't print all the runs or just an Exception fires.
import java.io.File;
import java.util.ArrayList;
import java.io.RandomAccessFile;
public class GetRunsFromFile
{
static long start = 0;
static long read_len = 0;
public static void main(String[] args) throws Exception
{
File in = new File("C:/Users/henrich/Desktop/Gimp.txt");
RandomAccessFile raf = new RandomAccessFile(in,"r");
ArrayList<Integer> current_run = new ArrayList<Integer>();
for(int i=1;i<=4;i++)
{
current_run = getNextRun(raf);
printArrayList(current_run);
}
raf.close();
}
private static ArrayList<Integer> getNextRun(RandomAccessFile raf) throws Exception
{
int v;
String line;
int val = Integer.MIN_VALUE;
ArrayList<Integer> run = new ArrayList<Integer>();
while((line=raf.readLine())!= null)
{
v = Integer.parseInt(line.trim());
if(v >= val)
{
read_len = raf.getFilePointer() - start;
start = raf.getFilePointer();
run.add(v);
val = v;
}
else
{
raf.seek(raf.getFilePointer() - read_len);
start = raf.getFilePointer();
return run;
}
}
return null;
}
private static void printArrayList(ArrayList<Integer> al)
{
for(int i=0; i<al.size(); i++)
{
System.out.print(al.get(i) + " ");
}
System.out.println();
System.out.println("------");
}
}
For more questions please let me know.
Note: It should work only for ascending runs and files of any length.
Thanks for the support.
There are several ways to do it.
solution 1
For instance call your function with an int and make it return an int refering to the number of the last printed char.
Run Exaple:
after the first run return 2 cause the length of print text is 2
after the second run return 6 cause the length of print text is 4 +2 from last loop... etc.
public int function(int startPoint){
// do stuff here
return lastIndexofPrintChar;
}
then call your function like this
loop{
int result=0;
result= function(x);
}
solution 2
You can also dublicate your file and remove every String you print.
private static void getNextRun()
{
try
{
BufferedReader br = new BufferedReader(new FileReader(new File("C:/Users/henrich/Desktop/Gimp.txt")));
br.skip(skip_lines);
int v;
String line;
int val = Integer.MIN_VALUE;
ArrayList<Integer> al = new ArrayList<Integer>();
while((line=br.readLine())!= null)
{
skip_lines += line.length()+2;
v = Integer.parseInt(line.trim());
if(v >= val)
{
al.add(v);
val = v;
}
else
{
skip_lines -= line.length() + 2;
printArrayList(al);
break;
}
}
br.close();
}
catch (Exception e){System.out.println("EOF");}
}
I have an action listener that calls some methods and one of those methods counts the number of times that a loop inside of another method is run. The problem I am having is that the counter just adds to itself (I understand why I just don't know how to fix it) rather than resetting back to 0.
Here is my action listener code.
public double computeIterative(double n) throws InvalidInput {
int a=1, b=2;
int result = 0;
if (n>=0) {
if(n==0)return 0;
if(n==1)return 1;
if(n==2)return 2;
for(int i = 3; i <= n; i++) {
result = a+(2*b);
a=b;
b = result;
this.getEfficiency();
}
} else{
throw new InvalidInput();
}
return result;
}
ActionListener that calls methods and sets text:
public void actionPerformed(ActionEvent e) {
int n = Integer.parseInt(nField.getText());
//Try Catch for Iterate Radio Button
if (iterateBtn.isSelected()){
try {
double result = sequence.computeIterative(n);
int efficiency = sequence.getEfficiency();
rField.setText(Double.toString(result));
eField.setText(Integer.toString(efficiency));
}
catch (InvalidInput ex) {
}
}
The getEfficiency method counts how many times the loop inside computeIterative method is run and then sets it to a textField.
Here is my getEfficiency method:
public int getEfficiency() {
efficiency++;
return efficiency;
}
Now obviously this will just keep adding onto itself, and I am sure that I am looking way too hard for a solution but I just cant figure it out.
Basically, after the try, catch, I need to set efficiency to 0 so that the next time the computeIterative(n) method is called, I get a proper reading.
You could simply add a method resetEfficiency():
public int resetEfficiency() {
efficiency = 0;
}
And then call it at the beginning of computeIterative():
public double computeIterative(double n) throws InvalidInput {
this.resetEfficiency();
//rest of code goes here
//....
}
(Of course I'm assuming this is not multi-threaded or anything).
public double computeIterative(double n) throws InvalidInput {
int a=1, b=2;
int result = 0;
this.resetEfficiencyCounter(); //Call Reset if Number Got Invalid.
if (n>=0) {
if(n==0)return 0;
if(n==1)return 1;
if(n==2)return 2;
for(int i = 3; i <= n; i++) {
result = a+(2*b);
a=b;
b = result;
this.getEfficiency();
}
} else{
throw new InvalidInput();
}
return result;
}
add new Function Named resetEfficiencyCounter().
private void resetEfficiencyCounter(){
this.efficiency = 0;
}
So let's say I have a main class with a while loop:
public class Main {
public static void main(String[] args) throws InterruptedException {
int one = 1;
int counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
Function.Move();
one++;
}
The counter variable in this loop is counting each second elapsed.
There is a separate class called Function:
public class Function {
public static int Move (int result){
result = 1 + counter;
return result;
}
}
So as you can see, inside the Function class's Move method, I want to be able to use the counter variable's new value, which increases with each passing second, to calculate the value of a different variable which will then be returned to the main method.
The problem is that I can't figure out how to pass the value of counter to the Move method inside the Function class to begin with.
I'm not shure if i understand what you want to do correctly, depending on where exactly you will need that result variable later i think your coude should look something like this:
public class Main {
int counter;
public static void main(String[] args) throws InterruptedException {
int one = 1;
counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
one++;
}
}
public int getCounter() {
return counter;
}
}
public class Function {
public static int move (int result, Main main){
result = 1 + main.getCounter();
return result;
}
}
You can use Function.move() anywhere you need it's value in your Programm now.
Beware, though, that you will need your code using the Function.move() to run in a different Thread as the Main Thread. Otherwise it will always return 101 or 1, as the while loop will always be running before or after your call to Function.move(), depending on where you call it (except if you call it from within the while loop, but then you counld just use counter++ without the need to have an extra class)
So the first part creates a vector and adds a digit to the 10 slots. Then after this nothing happens, i have no errors in my code but it just stops.. why?
package ovn7;
import java.util.Scanner;
public class ovn7a {
int []vektor;
Scanner scan = new Scanner(System.in);
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
}
public int find(int tal) {
System.out.println("tal");
tal = scan.nextInt();
int i = 0;
while(i<10 && vektor[i] != tal) {
i++;
}
return (i <10) ? i : -1;
}
}
This is your main method:
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
}
That's all your program does - when it hits the closing right brace of the main method, execution ends. If you want it to execute public int find(int tal) as well, you need to include a method call to your main method:
int index = find(5); //for example
Remember, the main method is the only one that is called automatically when executing the program! You'll have to call find yourself inside main.
EDIT: per request, an example of main with the method call included:
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
int index = find(5); // <-- this find(5) here is a method call for find!
System.out.println("The method returned a value of " + index + ".");
}
You can replace that "5" with any integer, as the method find accepts an integer as an argument. (as a side note, it doesn't matter which integer you pass to find - it overwrites the argument with a new value anyway)