public class problem1 {
public static void main(String args [])
{
int [] a = new int [1000];
for (int counter = 0; counter<=a.length;counter++);
{
if ((counter % 3 == 0) || (counter % 5 == 0))
{
int temp += counter;
}
}
}
}
I am trying to solve an equation where you have to go through an array with the numbers 1-1000, and add up all of the numbers that are multiples of 3 and 5, but my code wont execute. Can anyone see my error?
Your code has two major problems:
You have a semi-colon at the end of your for loop.
for (int counter = 0; counter<=a.length;counter++); // Remove the ;
You are re-declaring your variable each time in your for loop.
int temp += counter; // replace it with `temp += counter`.
And declare the variable temp outside the for loop, with it's default value 0.
And a minor problem is:
You don't need that array a. Rather declare an int variable say total with the required value (in this case, 1000). And use it in loop condition, rather than a.length.
Do not create an array for your counter. It is not necessary, arrays usually store reusable values such as names, cities, ages etc. basically.
Also for loop does not ends with semi-colon.
Most important: Not declare a variable in a loop. If you do it you will create X times variable again and again
public class problem1 {
public static void main(String[] args) {
int temp = 0;
for (int i = 0; i <= 1000; i++)
{
if ((i % 3 == 0) || (i % 5 == 0)) {
temp += i;
}
}
System.out.println("Result is :" + temp);
}
}
Your code will never execute because of the semi-colon at the end of your for, it won't give you compilation error, but it means an empty statement, so the for body will never be executed, just remove the semicolon.
I believe you should initialize int temp outside the for loop first. It should be as follows: int temp = 0; and then temp += counter; should work.
Related
I'm stuck on a program from mooc.fi course; wherein I can't get my program to print results.
The program should 'print all the numbers divisible by three in the given range. The numbers are to be printed in order from the smallest to the greatest.'
Thanks for the help.
public class DivisibleByThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
divisibleByThreeInRange(a, b);
}
public static void divisibleByThreeInRange(int beginning, int end) {
for (int i = 0; i >= beginning && i <= end; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}
Welcome to stack overflow, Entropy!
The problem is this line:
for (int i = 0; i >= beginning && i <= end; i++) { ... }
Let's break up that for loop:
for says its a loop, with the first statement initializing the loop, the second giving the condition for executing the next iteration, and the third saying how to update after an interation. Inside the quotes is what to execute in an interation.
Loop initializing: int i = 0 defines the loop variable i and sets it to 0.
Loop condition: i >= beginning && i <= end. So we will execute the next iteration if i lies in the entered range.
Loop post update: i++ just increments the counter.
So effectively, you start with i being 0, and then execute the loop WHILE that number is within the entered range. But if i BEGINS outside your range, the loop is never executed, because the condition is false at the very beginning.
You can confirm that by entering making the range contain 0, i.e. enter a non-positive lower and a non-negative upper range (like -10 to 10). Then, the initial condition is fulfilled and your loop happily shows all the number divisable by 3.
So simply change the loop to
for (int i = beginning; i <= end; i++) { ... }
and it will work as intended: Start at the beginning of the range, and go the end of it -- done!
These for-loops can be tricky sometimes, don't they? :)
That's a great first post, by the way. Having a Minimal Reproducible Example (MRE, also called reprex or MCVE [Minimal, Complete, Verifiable Example]) always help others to quickly verify, debug and solve your problem.
public class DivisibleByThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
divisibleByThreeInRange(a, b);
}
public static void divisibleByThreeInRange(int beginning, int end) {
for (int i = beginning ; i <= end; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}
I am trying to separate digits from an Integer and then put them into an array.
All elements, except for the first, are printing as 0. Could someone explain why this is it happening?
public class Doom{
public static void main(String[] args){
int number = 1234;
int[] list = new int[5];
while (number > 0) {
int x = 0;
int fork = (number%10);
System.out.println(fork);
list[x] = fork;
x++;
number = number / 10;
}
for (int x : list){
System.out.println(x);
}
}
}
The problem is that you are declaring x inside the loop, so it gets reset to 0 each time. You want to move the int x = 0; line to be above the while (number > 0) { line, outside of the loop. Then it will be initialized to 0 only once, and each pass through the loop can assign it a new value with the x++ line.
You keep redeclaring x in your loop, causing only the first index to have meaningful data. Move it to the outside of your loop.
There are quite a few errors in your program. Biggest one is that you are inializing x to 0 and then incrementing it by 1 within the while loop. It will keep storing your digits at the same location (0th place). Compare the following snippet and try to learn your mistakes:
public class Doom{
public static void main(String[] args){
int number = 1234;
int[] list = new int[String.valueOf(number).length()];
int x = 0;
while (number > 0) {
int fork = (number%10);
System.out.println(fork);
list[x] = fork;
x++;
number = number / 10;
}
for (int y : list){
System.out.println(y);
}
}
}
You are reinitializing x to 0 every time. Declare it outside of the while loop.
I want to print put the elements in an array that only occur twice. So if, for example, number 2 occurs 3 or 4 times, it should not be printed. The code I've written so far is below.
The issue in my code is with the loop. For example, for the number 2, since j=i+1 is the initialization condition, the inner loop won't read the elements before the jth location- since there is a 2 at index 6, it won't count the 2s before it, making the required condition true and displaying the 2. Is there a way to fix this?
public class Problem2 {
public static void exactlytwice(int[] x) {
int count, j;
for (int i = 0; i < x.length; i++) {
count = 0;
for (j = i + 1; j < x.length; j++) {
if (x[i] == x[j])
count++;
}
if (count == 1) System.out.print(x[i] + " ");
}
}
public static void main(String[] args) {
int[] x = new int[15];
x[0] = 2;
x[1] = 2;
x[2] = 2;
x[3] = 13;
x[4] = 44;
x[5] = 44;
x[6] = 2;
x[7] = 63;
x[8] = 63;
x[9] = 90;
x[10] = 1;
x[11] = 2;
x[12] = 150;
x[13] = 150;
x[14] = 180;
exactlytwice(x);
}
}
aside from the issue you wrote, the bigger problem I see with your code is that its inefficient. You are doing a loop inside a loop here, which is very slow (o(n^2)).
My suggestion is to keep a map of numbers->count, and then only take the ones that appear only twice in the map:
public static void exactlytwice(int[] x) {
Map<Integer, Integer> counter = new HashMap<>();
for (int i = 0; i < x.length; i++) {
if (counter.contains(i)) {
counter.put(i,1);
} else {
counter.put(i,counter.get(i)+1);
}
}
for (Integer i : counter.keyset()) {
if (counter.get(i) == 2) {
System.out.println(i);
}
}
}
Think about maintaining a seperate array/list which keeps track of all the elements that has been counted/printed by which you could just skip the same number that shows again down the array.
Or you could sort the array and then perform the whole logic to check for duplicates.
Just for completeness, there is a solution without extra-map. It's still O(n^2), but uses no extra memory. And It uses kind of fun idea.
First, we only need to output first occurence of a number, every other one is not relevant, because we either have more than 2 of them, or we've already output the first one.
Second, we can then indeed continue, from i+1 element, because at this point, there are no elements equal to ith, that are earlier in array.
public static void exactlytwice(int[] x) {
int count, j;
TOP:
for (int i = 0; i < x.length; i++) {
count = 0;
for (j = 0; j < i; j++) {
if (x[j] == x[i])
// had this number earlier, so go to the next one.
continue TOP;
}
for (j = i+1; j < x.length; j++) {
if (i != j && x[i] == x[j])
count++;
}
if (count == 1) System.out.print(x[i] + " ");
}
}
In addition to the answers provided, there are two more ways you could go about this:
If array modification is permitted, change elements already encountered to a dummy value, and skip the value if encountered. This reduces the time complexity to O(n) from O(n^2), but destroys the original array. Of course, this assumes that the acceptable integers are restricted to a certain set (thanks to #Dzmitry Paulenka for reminding me that I hadn't stated this explicitly). To keep the array, you could make a copy (although then the space complexity becomes O(n) ).
If any integer is acceptable, then create an encountered boolean array, all intialized to false. Change the locations of elements encountered in the original array to true in the encountered boolean array, and if the value is already true, it can be skipped. Again, time complexity O(n), but O(n) space complexity, and unlike in the second method of 1., does not require the permissible range of numbers (ints) to be restricted.
Alternately, simply make the initialization of j as j=0, and then ensure that only those numbers which don't have that number appearing before them are printed, i.e., that the number is printed only if it occurs at j>=i (thanks to #Nir Levy for pointing the j>=i requirement out). This is (slightly) more inefficient than the code already written, but the time complexity remains the same O(n^2).
With Java 8 you can achieve this using streams like this :
public static void main(String[] args)
{
List<Integer> list = Stream.of(12,1,3,4,2,3,7,6,7,3,1,8,4,12,33,45,78,36,8)
.collect(Collectors.groupingBy(x->x, Collectors.summingInt(x->1)))
.entrySet().stream().filter(x->x.getValue()==2)
.collect(ArrayList<Integer>::new,(x,y)->x.add(y.getKey()),ArrayList<Integer>::addAll);
System.out.println(list);
}
The result is :
[1, 4, 7, 8, 12]
Code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Writer {
private int counter;
private Random generator = new Random();
private List<Integer> data = new ArrayList<Integer>();
private Map<Integer,Integer> map = new HashMap<Integer,Integer>();
public Writer(int n){
populate(n);
}
private final void populate(int n){
for(int i = 0; i != n; i++){
data.add(generator.nextInt(10));
}
}
private final void reset(){
this.counter = 0;
}
public final void occurence(){
for(int dp : data){
for(int i = 0; i < data.size(); i++){
if(dp == data.get(i)){
counter += 1;
}
}
map.put(dp, counter);
reset();
}
}
public final void filter(int d){
for(int key : map.keySet()){
if(map.get(key) == d){
System.out.println("Key: " + key + " Value: " + map.get(key));
}
}
}
public void rawData(){
System.out.println(data.toString());
}
public void output(){
System.out.println(map.toString());
}
Initiate:
// Create instance of Writer class and generate '100' random numbers
Writer writer = new Writer(100);
// Output raw data
writer.rawData();
// Process data
writer.occurence();
// Filter numbers with occurence '10'
writer.filter(10);
// Output processed data
writer.output();
Output (from from calling filter(10)):
Key: 3 Value: 10
Key: 8 Value: 10
I'm playing around with double arrays and am trying to set all the even elements of an array to 0 and all of the odd elements of the array to 1. Everything looks okay to me, but when I run it I get a bunch of errors. Not sure what's wrong; I've been looking at it for a while with no luck. Any advice on how to fix the errors it gives would be great, thanks!
Code:
public class SetOf0and1 {
public static void main(String[]args)
{
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
System.out.println("Before setting elements between 0 and 1: ");
displayArray(numbers1);
setEvenRowsTo0OddRowsTo1 (numbers1);
System.out.println("After setting the elements between 0 and 1");
displayArray(numbers1);
}
public static void setEvenRowsTo0OddRowsTo1(int [][]array)
{
for(int i=0; i<array.length;i++)
{
for(int j=0; j<array[i].length;j++)
{
if(i%2 == 0)
array[i][j]=0;
else
array[i][j]=1;
}
}
}
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
}
}
Errors given:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at SetOf0and1.displayArray(SetOf0and1.java:38)
at SetOf0and1.main(SetOf0and1.java:10)
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
^^^^^^^^^
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
Your inner loop should stop at array[i].length.
In the method displayArray, the line:
for( int j=0; j<array.length;j++)
Should be:
for( int j=0; j<array[i].length;j++)
array.length does not return the length you thing it does! You have a 2 dimentional array. So if we say you have array[x][y] then array.length will be x and array[i].length (for 0 <= i < x) will be y. This could be different depending on the length of the array on that index. (so the formula does not exactly apply like that)
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
this statement initializes an array with three arrays of the legthes 3, 3 and 2!!!
(in the third block you have only two elements !!! - {1,3})
In your displayArray-method you use two times ...
array.length
... to distinct the size of the loop
that sets the number of loops to 3 ... But last block is only two elements long -> errror.
Use this instead for the second loop:
for( int j=0; j<array[i].length;j++)
If you want to check if a number is odd, you can do it this way:
int answer = thenumber % 2;
'thenumber' is the integer to check if it is even.
Then 'answer' would be 0 if the number was even.
And if you want to loop through the array and do it:
for (int i = 0; i < numbers1.length(); i++)
{
if (numbers1[i] % 2 == 0) {
//EVEN
numbers1[i] = 0;
}
else if (numbers1[i] % 2 == 1) {
//ODD
numbers1[i] = 1;
}
}
And, even more compact:
for (int i = 0; i < numbers1.length(); i++)
{
numbers1[i] %= 2;
}
Edit: I forgot that it was an array you had! I was thinking about ArrayList! Fixed.
I have a method that must do the following:
for (int a01 = 1; a01 <= 25; a01++) {
for (int a02 = a01 + 1; a02 <= 25; a02++) {
for (int a03 = a02 + 1; a03 <= 25; a03++) {
...
System.out.println(a01 + "," + a02 + "," + ... + "," + a015);
}
}
}
I'd like to specify the number of nested for's (in the case above, I want 15 nested for's).
Is there a way to use recursive programming here?
Yes. This can be performed by recursive programming.
I assume you do not like to WRITE DOWN these nested for's in source code - as in your example, because this is really ugly programming - like the commentors explain.
The following (pseudo Java-like) code illustrates it. I assume a fixed depth for the nesting. Then you actually like to loop over an integer vector of dimension depth.
int[] length = new int[depth];
int[] counters = new int[depth];
The array counters has to be initialised to 0 (Arrays.fill(counters,0)). The array length has to be initialised to the number of iterations for the respective for loop.
I assume that you like to perform a certain operation within the inner loop. I will call this
performOperation(int[] counters);
- it depends on the multi-dimensional counter, i.e. the counters of the outer for's.
Then you can run the nested for loops by calling
nestedLoopOperation(counters, length, 0);
where
void nestedLoopOperation(int[] counters, int[] length, int level) {
if(level == counters.length) performOperation(counters);
else {
for (counters[level] = 0; counters[level] < length[level]; counters[level]++) {
nestedLoopOperation(counters, length, level + 1);
}
}
}
In your case your System.out.println() would be
performOperation(int[] counters) {
String counterAsString = "";
for (int level = 0; level < counters.length; level++) {
counterAsString = counterAsString + counters[level];
if (level < counters.length - 1) counterAsString = counterAsString + ",";
}
System.out.println(counterAsString);
}
I created this program to show all the different possible combination of cards (non repeating). It uses recursive for loops. Maybe it can help you.
//I'm lazy, so yeah, I made this import...
import static java.lang.System.out;
class ListCombinations {
//Array containing the values of the cards
static Symbol[] cardValues = Symbol.values();
//Array to represent the positions of the cards,
//they will hold different card values as the program executes
static Symbol[] positions = new Symbol[cardValues.length];
//A simple counter to show the number of combinations
static int counter = 1;
/*Names of cards to combine, add as many as you want, but be careful, we're
talking about factorials here, so 4 cards = 24 different combinations (4! = 24),
but 8 cards = 40320 combinations and 13 cards = 6.23 billion combinations!*/
enum Symbol {
AofSpades, TwoofSpades, ThreeofSpades, FourofSpades
}
public static void main(String args[]) {
//I send an argument of 0 because that is the first location which
//we want to add value to. Every recursive call will then add +1 to the argument.
combinations(0);
}
static void combinations(int locNumber) {
/* I use a recursive (repeating itself) method, since nesting for loops inside
* each other looks nasty and also requires one to know how many cards we will
* combine. I used 4 cards so we could nest 4 for loops one after another, but
* as I said, that's nasty programming. And if you add more cards, you would
* need to nest more for loops. Using a recursive method looks better, and gives
* you the freedom to combine as many cards as you want without changing code. */
//Recursive for loop nesting to iterate through all possible card combinations
for(int valueNumber = 0; valueNumber < cardValues.length; valueNumber++) {
positions[locNumber] = cardValues[valueNumber];
if (locNumber < (cardValues.length-1)) {
combinations(locNumber + 1);
}
//This if statement grabs and displays card combinations in which no card value
// is repeated in the current "positions" array. Since in a single deck,
// there are no repeated cards. It also appends the combination count at the end.
if (locNumber == (cardValues.length-1) && repeatedCards(positions)) {
for (int i = 0; i < cardValues.length; i++) {
out.print(positions[i]);
out.print(" ");
}
out.printf("%s", counter);
counter++;
out.println();
}
}
}
static boolean repeatedCards(Symbol[] cards) {
/*Method used to check if any cards are repeated in the current "positions" array*/
boolean booleanValue = true;
for(int i = 0; i < cardValues.length; i++) {
for(int j = 0; j < cardValues.length; j++) {
if(i != j && cards[i] == cards[j]) {
booleanValue = false;
}
}
}
return booleanValue;
}
}