It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Java {
public static int numberOfLoops;
public static int numberOfIterations;
public static int[] loops;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("N = ");
numberOfLoops = input.nextInt();
System.out.print("K = ");
numberOfIterations = input.nextInt();
input.close();
loops = new int[numberOfLoops];
System.out.println("main START");
nestedLoops(0);
System.out.println("main END");
}
public static void nestedLoops(int currentLoop) {
System.out.println("nestedLoops");
System.out.println("currentLoop " + currentLoop);
if (currentLoop == numberOfLoops) {
printLoops();
return;
}
for (int counter = 1; counter <= numberOfIterations; counter++) {
System.out.println("nestedLoops in LOOP");
System.out.println("currentLoop in LOOP " + currentLoop);
loops[currentLoop] = counter;
nestedLoops(currentLoop + 1);
}
}
public static void printLoops() {
System.out.println("printLoops");
for (int i = 0; i < numberOfLoops; i++) {
System.out.printf("%d", loops[i]);
}
System.out.println();
}
}
Hi all. I'm new here and this is my first post.
My question is:
If i put for N = 2 and K = 4 why after first return currentLoop continue with 1 we pass to the method 0 ?
Thanks , Nikola
I'm not sure if I understand your question completely..but
When you call
nestedLoops(0);
You go into the nestedLoops function with currentLoop = 0.
Within this function, you call
nestedLoops(currentLoop + 1);
And that's why you get a
nestedLoop(1)
called while you're in your
nestedLoop(0)
Let me know if I misunderstood your question.
Edited:
When
nestedLoops(1)
is called, we call
nestedLoops(2)
right?
When we compare currentLoop and numberOfLoops inside of nestedLoops(2), they are both 2,
so we go into
printLoops();
Once printLoops is done, we return into
nestedLoops(2)
However, after printLoops(), we have a
return;
Therefore, we return out of
nestedLoops(2)
and we come back into
nestedLoops(1)
where nestedLoops(2) was called from.
Does that make sense?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Why is the else statement not giving the values of sub[1], sub[3], sub[5], etc (odd array positions)?
What am I doing wrong? I thought that i % 2 == 0 would give me the even array positions? Therefore, the else statement should give me the odd, correct?
public class PolyValues {
public PolyValues() {
String value = "5 6 8 9 1 9";
String sub[] = value.split(" ");
double coeff = 0;
int exp = 0;
for (int i = 0; i < sub[i].length(); i++) {
if (sub[i].isEmpty()) {
System.out.println("No input");
}
if (i % 2 == 0) {
try {
coeff = Double.parseDouble(sub[i]);
System.out.println(coeff);
} catch (NumberFormatException e) {
System.out.println("Fix This");
}
} else {
try {
exp = Integer.parseInt(sub[i]);
System.out.println(exp);
} catch (NumberFormatException e) {
System.out.println("Fix This");
}
}
}
public static void main(String[] args) {
Polyvalues p1 = new Polyvalues();
}
} //end of class
You are getting the length of the strings from sub array and not the length of that array.
Change in the for:
i<sub[i].length()
to
i<sub.length
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to find combination for the data which are given in following manner,
jobs #ofIntervals
---- -------------
4 1
1 2
3 2
0 3
2 3
have to make a combination set of the given jobs based on the the #ofIntervals.
The output possible combinations will affect the position of jobs. If there is more than one jobs with same #ofIntervals then only change on those jobs position will make new job set. The possible outcome of the given input should like this,
combination-1: 4 1 3 0 2 // same as input
combination-2: 4 3 1 0 2 // here as job 3 and 1 have 2 #ofIntervals they make a new combination
combination-3: 4 1 3 2 0 // here as job 2 and 0 have 3 #ofIntervals they make a new combination
combination-4: 4 3 1 2 0
Can anyone please help me to write a code or suggest an algorithm for that.
Separate your jobs into separate sets, where each member of a set has the same "#of intervals" value.
For each set, generate a collection that holds all permutations of that set.
Generate a collection that holds the cartesian product of the collections from step 2.
This final collection is your solution.
I like the answer that mbeckish wrote but here is the code that I wrote to actually do the work:
import java.util.ArrayList;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<JobsInterval> jobsIntervalList = new ArrayList<JobsInterval>();
jobsIntervalList.add(new JobsInterval(4, 1));
jobsIntervalList.add(new JobsInterval(1, 2));
jobsIntervalList.add(new JobsInterval(3, 2));
jobsIntervalList.add(new JobsInterval(0, 3));
jobsIntervalList.add(new JobsInterval(2, 3));
printPossibleCombinations(jobsIntervalList);
}
public static void printPossibleCombinations(List<JobsInterval> list)
{
//Assumes the list is already in interval order.
int currentInterval = -1;
List<List<JobsInterval>> outerList = new ArrayList<List<JobsInterval>>(list.size());
List<JobsInterval> innerList = null;
//Loop through the list and group them into separate lists by interval.
for (JobsInterval ji : list)
{
if (ji.interval != currentInterval)
{
if (null != innerList)
outerList.add(innerList);
currentInterval = ji.interval;
innerList = new ArrayList<JobsInterval>(list.size());
}
innerList.add(ji);
}
if (null != innerList)
outerList.add(innerList);
print(0, outerList, null);
}
public static void permute(StringBuilder value, List<JobsInterval> list, List<String> permutations)
{
//Check to see if this is the last recursive call
if (0 == list.size())
{
permutations.add(value.toString());
}
else
{
List<JobsInterval> subList;
for (int i = 0; i < list.size(); i++)
{
subList = new ArrayList<>(list);
subList.remove(i);
permute(new StringBuilder(null == value ? "" : value).append(list.get(i).jobs), subList, permutations);
}
}
}
public static void print(int index, List<List<JobsInterval>> list, StringBuilder value)
{
//Check to see if this is the last recursive call
if (list.size() == index)
System.out.println(value.toString());
else
{
List<JobsInterval> intervalGroup = list.get(index);
List<String> permutations = new ArrayList<String>();
permute(null, intervalGroup, permutations);
for (String permutation : permutations)
print(index+1, list, new StringBuilder(null == value ? "" : value).append(permutation));
}
}
private static class JobsInterval
{
public int jobs;
public int interval;
public JobsInterval(int j, int i)
{
jobs = j;
interval = i;
}
public String toString()
{
return new StringBuilder().append('{').append(jobs).append(", ").append(interval).append('}').toString();
}
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
public class ReaderWriter extends Bank {
private final String FILENAME = "clients.txt";
public void writeToFile() {
int i = 0;
boolean repeat = true;
Formatter output = null; // Used to write to file
try {
output = new Formatter(FILENAME);
// Open the file
while ((i <= accounts.length - 1) && (accounts[i] != null)) {
output.format("%s\n", accounts[i].getAccountHolder());
output.format("%d%n", accounts[i].getAccountNumber());
output.format("%d%n", accounts[i].getAmount());
i = i + 1;
}catch (Exception ex) {
ex.printStackTrace();
} finally {
output.close(); // Make sure to close the resource after usage.
}
}
And this is Bank class:
public class Bank {
public final int MAX_NUMBER_OF_ACCOUNTS = 10;
public int max = 0;
String name1;
int money1;
int number1;
Scanner input = new Scanner(System.in);
BankAccount[] accounts = new BankAccount[MAX_NUMBER_OF_ACCOUNTS];
public void greateAccount() {
int i = 0;
boolean repeate2 = true;
System.out.println("You have chosen to create a new account.");
System.out.println("Enter the name of the account holder: ");
name1 = input.next();
System.out.println("Enter the account no.");
number1 = input.nextInt();
System.out.println("Enter the initiating amount: ");
money1 = input.nextInt();
while (repeate2 == true) {
if (accounts[i] == null) {
if (i < 1) {
accounts[i] = new BankAccount();
accounts[i].setAccountHolder(name1);
accounts[i].setAccountNumber(number1);
accounts[i].setAmount(money1);
repeate2 = false;
} else {
if (ifAccountExist(number1) != true) {
accounts[i] = new BankAccount();
accounts[i].setAccountHolder(name1);
accounts[i].setAccountNumber(number1);
accounts[i].setAmount(money1);
repeate2 = false;
} else {
System.out.println("****This account ALREADY EXIST!****");
System.out.println("*************************************");
System.out.println();
max = max - 1;
repeate2 = false;
}
}
}
i = i + 1;
}
max++;
}
Now I want to write to text file account number, name and money.
My code doesn't work. I does not write it can not retrieve values from array I don't know why?
Can you help me?
The code is not going to compile, for many reasons...
For example:
Why this line:
ex.printStackTrace();
is floating in your class ReaderWriter (line 21) and away a catch block?
Why you don't have include declarations?
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm trying to write a program that gets a .txt file that only has something like 10000010000010000010001
I'm trying to count the number of zeros and output it like 5 5 5 3. I thought if I convert a string into a double or int I could write an if or for loop.
import java.util.Scanner;
public class test1{
public static void main(String[] args) {
java.io.File test2 = new java.io.File("test3.txt");
try
{
Scanner input = new Scanner(test2);
while(input.hasNext())
{
String num = input.nextLine();
System.out.println(num);
double n = Double.parseDouble(num);
System.out.println(n);
}
}
catch (Exception e){
System.out.println("could not find file");
}
}
}
Here you go:
char[] numArray = num.toCharArray();
int counter=0;
for(int i=0;i<numArray.length;i++) {
if(numArray[i]=='0') {
counter++;
}
if((i==numArray.length-1&&counter>0)||(counter>0&&numArray[i]!='0')) {
System.out.println("Number of Zeroes: "+counter);
counter=0;
}
}
Some important points:
1) It's best to use an array of char values here, instead of operating using a double, because a char array can store many more values- the example you posted is too long for a double to handle.
2) Most of this should be self-explanatory (at least, if you study it bit-by-bit), but in case the i==numArray.length-1 part is confusing, this ensures that if the string ends with a 0, the final count of 0's will be printed out as well.
This should work for any string you can throw at it- including values besides 0 and 1, if you need support for it!
where is your effort?
you can simply try (if your string contains only 1s and 0s):
String[] splitArr = num.split("1");
String countStr = "";
for (int i = 0; i < splitArr.length; i++) {
if( ! splitArr[i].isEmpty() )
countStr += splitArr[i].length();
}
System.out.println(countStr);
import java.util.*;
import java.io.*;
public class ZeroCounter {
ArrayList <Integer> listOfNumbers = new ArrayList <Integer> ();
DataInputStream inStream;
long inFileSize;
long outFileSize;
// Track how many bytes we've read. Useful for large files.
int byteCount;
public ZeroCounter() {
}
//read the file and turn it into an array of integers
public void readFile(String fileName) {
try {
// Create a new File object, get size
File inputFile = new File(fileName);
inFileSize = inputFile.length();
// The constructor of DataInputStream requires an InputStream
inStream = new DataInputStream(new FileInputStream(inputFile));
}
// Oops. Errors.
catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
// Read the input file
try {
// While there are more bytes available to read...
while (inStream.available() > 0) {
// Read in a single byte and store it in a character
int c = (int)inStream.readByte();
if ((++byteCount)% 1024 == 0)
System.out.println("Read " + byteCount/1024 + " of " + inFileSize/1024 + " KB...");
// Print the integer to see them for debugging purposes
//System.out.print(c);
// Add the integer to an ArrayList
fileArray.add(c);
}
// clean up
inStream.close();
System.out.println("File has been converted into an ArrayList of Integers!");
}
// Oops. Errors.
catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
//Print the ArrayList contents for debugging purposes
//System.out.println(fileArray);
}
public void countZeroes() {
int zeroCounter = 0;
for (int i = 0; i < listOfNumbers.size(); i++) {
if (listOfNumbers.get(i) == 0) {
zeroCounter++;
}
else if (listOfNumbers.get(i) != 0 && zeroCounter > 0) {
//this only prints the number of zeroes if the zero counter isn't zero
System.out.println(zeroCounter + " ");
zeroCounter = 0;
}
else {
//do nothing
}
}
}
public static void main(String[] args) {
ZeroCounter comp = new ZeroCounter();
comp.readFile("test3.txt");
comp.countZeroes();
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So I'm using this code to sort a number array but it gives me an error that I need a "}".
Am I missing some "}"?
Any help would be appreciated!
double Median()
{
int k,Hide;
boolean IsThereASwap;
IsThereASwap = false;
while(IsThereASwap == false )
{
for ( k = 0 ; k < TheArrayAssingment.length - 1; k++)
{
if( TheArrayAssingment[k] > TheArrayAssingment[k+1] )
{
Hide = TheArrayAssingment[k+1];
TheArrayAssingment[k+1] = TheArrayAssingment[k];
TheArrayAssingment[k] = Hide;
IsThereASwap = true;
}
}
if ( IsThereASwap == true)
{
IsThereASwap = false;
}
else
{
IsThereASwap = true;
}
}
}
You're failing to return a value. The method is declared to return a double, but you're falling off the end of your method without returning anything.
I see too many problems with your code to bother answering your question.
Start by learning and following the Sun Java coding standards.
A good IDE will make errors like mismatched parentheses and failure to return a value a thing of the past. Try IntelliJ; it's the best there is.
This will work much better than yours:
package cruft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* StatisticsUtil has statistics utility methods
* #author Michael
* #link
* #since 7/21/12 7:30 PM
*/
public class StatisticsUtil {
public static void main(String[] args) {
List<Double> values = new ArrayList<>();
for (String arg : args) {
values.add(Double.valueOf(arg));
}
System.out.println(String.format("median: %10.4f", getMedian(values)));
}
public static double getMedian(List<Double> values) {
double median = 0.0;
if (values != null) {
int numValues = values.size();
if (numValues > 0) {
Collections.sort(values);
if ((numValues%2) == 0) {
median = (values.get((numValues/2)-1)+values.get(numValues/2))/2.0;
} else {
median = values.get(numValues/2);
}
}
}
return median;
}
public static double getMedian(double [] values) {
double median = 0.0;
if (values != null) {
int numValues = values.length;
if (numValues > 0) {
Arrays.sort(values);
if ((numValues%2) == 0) {
median = (values[(numValues/2)-1]+values[numValues/2])/2.0;
} else {
median = values[numValues/2];
}
}
}
return median;
}
}
You declare the method "Median()" to return a double, but you don't return anything.