0

enter link description here

Q When there are two natural numbers A and B, A%B is the remainder of A divided by B. For example, the remainder of 7, 14, 27, 38 divided by three is 1, 2, 0, 2.

After receiving 10 inputs, divide them by 42 and get the rest. Then write a program that prints out how many different values there are. ex input 39 40 41 42 43 44 82 83 84 85 ex output 6

when I complied it cnt is still 0 I dont know why for loop doesnt work plz help //codeline

import java.util.Scanner;

public class Modular3052_1 {

    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        
        boolean mod[] = new boolean [42];
        int cnt = 0;
        
        for(int i = 0 ; i<10 ; i++) {           
            mod[sc.nextInt()%42] = true;
            if(mod[i])
                cnt++;
        }
        System.out.println(cnt);
        
    }
}
Turo
  • 4,724
  • 2
  • 14
  • 27
이정우
  • 19
  • 1
  • 3
    Try to single step through your program with a debugger. Where does the actual behaviour deviate from your expectations? – Henry Aug 13 '20 at 06:26
  • What makes you think that the for loop does not work? The increment is conditional and hence not a reliable indicator. Add and unconditional statement (e.g. an output) to check whether the loop is executed. – Yunnosch Aug 13 '20 at 06:28
  • Related: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Lino Aug 13 '20 at 06:29
  • Also, please "enter link description here". – Yunnosch Aug 13 '20 at 06:29
  • What is "enter link description here"? – Adrian Aug 13 '20 at 07:27

2 Answers2

0

The problem is that you are incrementing the counter by checking mod[i], when you should have check mod[sc.nextInt()%42]. An optimal solution would be to check firstly if mod[sc.nextInt()%42] is false, and if so increment the counter, then put it true:

for(int i = 0 ; i<10 ; i++) {   
  int number = sc.nextInt();
       if (mod[number%42] == false) cnt++;
       mod[number%42] = true;     
}
Vladimir Stanciu
  • 1,468
  • 1
  • 7
  • 24
  • Thx my problem always happen in tiny things actually I already found answer to go to the next step but I wanna solve own my code I appreciate it – 이정우 Aug 14 '20 at 05:30
0

I believe you are comparing and taking input in the same loop due to which the issue is there whart happens: for i =5 if the remainder comes to be 0 it never gets compared as for i=5 the only statement gets executed is if(mod[5]) but what needs to be checked is if(mod[0]) is true or not.\n Try using two loops one for input and other for comparison you will get your answer correct. or if you want to do it in a single loop try using Set to save the values.

Shubham Parmar
  • 147
  • 1
  • 13