Edit: I figured out what was wrong, when count hits 5, it stays at 5 until the first condition is hit then count changes. This results in the extra empty lines.
So my goal is for the output to be one line after the other but its not doing that.
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
for (int i=n;i<=m;i++){
if(i%a==0&&i%b!=0) {
System.out.print(i + " ");
count++;
}
if (count%5==0)
System.out.println();
}
}
}
This code is suppose to take integer values of n, m, a and b and displays all the numbers from n to m that are divisible by a but not divisible by b, and prints the results 5 numbers per line. So far I have got printing the numbers 5 times per line down but every time it out puts the next line, instead of immediately printing to the next line it skips some.
Here is what its suppose to do when n=10, m=50, a=2 and b=3:
10 14 16 20 22
26 28 32 34 38
40 44 46 50
Instead its printing this:
10 14 16 20 22
26 28 32 34 38
40 44 46 50
What am I doing wrong?
When count reaches a number that's divisible by 5, you continue iterating over i. In some of these iterations, count is not incremented, so it remains divis5 and you continue adding new lines.
Moving the second if statement inside the for loop should solve this:
for (int i=n;i<=m;i++){
if(i%a==0&&i%b!=0) {
System.out.print(i + " ");
count++;
if (count % 5 == 0) // Here!
System.out.println();
}
}
You forgot to consider that the count variable will not increase as long as you dont satisfy the first if block. The better way is to check if its equal to 5
print new line the set count = 0
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
for (int i=n;i<=m;i++){
if(i%a==0&&i%b!=0) {
System.out.print(i + " ");
count++;
}
if (count==5){
System.out.println();
count = 0;
}
}
}
}
When the count is 5 and the code is not entered to the first "if" the new line will be printed because the count will not be increased.
Please try:
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
boolean is_new_line = false;
for (int i=n;i<=m;i++){
if(i%a==0&&i%b!=0) {
System.out.print(i + " ");
count++;
is_new_line = false;
}
if ((count%5==0) && (is_new_line==false)) {
System.out.println();
is_new_line = true;
}
}
}
}
Related
I'm making a program that counts how many times each digit (0-9) occurs in each number between 1 to 100. At the end it will say something like:
The digit 0 showed up ____ times between 1-100
The digit 1 showed up ____ times between 1-100
and so forth.
This is what I have:
public class CountEachDigit {
public static void main(String[] args) {
int counter =0;
int[] digit = new int[10];
for (int i=1;i<=100;i++) {
for (int j=0;j<=9;j++){
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(0)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(1)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(2)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
}
}
for (int j =0;j<=9;j++){
System.out.println("The number "+j+" appears "+digit[j]+" times between 1 - 100.");
}
}
}
I tried changing the charAt each digit to a String to count the occurrence using the try and catch. No dice so far.
You do not need a string operations. You have to use x % 10 to get the last digit, and then x \= 10, to remove this last digit.
public class CountEachDigit {
public static void main(String... args) {
final int lo = 1;
final int hi = 100;
int[] digits = countDigits(lo, hi);
for (int i = 0; i < 10; i++)
System.out.format("The number %d appears %d times between %d - %d.\n", i, digits[i], lo, hi);
}
private static int[] countDigits(int lo, int hi) {
int[] digits = new int[10];
for (int i = lo; i <= hi; i++) {
int val = i;
do {
digits[val % 10]++;
} while ((val /= 10) > 0);
}
return digits;
}
}
Demo:
The number 0 appears 11 times between 1 - 100.
The number 1 appears 21 times between 1 - 100.
The number 2 appears 20 times between 1 - 100.
The number 3 appears 20 times between 1 - 100.
The number 4 appears 20 times between 1 - 100.
The number 5 appears 20 times between 1 - 100.
The number 6 appears 20 times between 1 - 100.
The number 7 appears 20 times between 1 - 100.
The number 8 appears 20 times between 1 - 100.
The number 9 appears 20 times between 1 - 100.
Have an array with int[10] to count the occurrences for each digit.
Then have a function that traverses a string and for each digit it finds increases the correct field in the array.
Then have a loop over numbers from 1 to 100 which converts that number to string and feeds it into the function.
Finally print the array values.
In code this may look like
public class Test {
static int[] occurrences = new int[10];
static void checkOccurrences(String s) {
for (char c: s.toCharArray()) {
if (Character.isDigit(c)) {
occurrences[ c - '0' ]++;
}
}
}
public static void main(String[] args) {
for (int i=1; i<=100; i++) {
String s = String.valueOf(i);
System.out.println("checking "+s);
checkOccurrences(s);
}
System.out.println(Arrays.toString(occurrences));
}
}
and it prints
checking 1
checking 2
checking 3
...
checking 99
checking 100
[11, 21, 20, 20, 20, 20, 20, 20, 20, 20]
In case you or future readers want to see a stream approach, which I doubt, here's what I did just for fun: Stream over the range [1 - 100], convert and map to String, split each String at each charachter such that, for example "42" becomes a stream of "4" and "2", collect to map using digit as key and count of occurrence as value and finally print.
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
// ...
public static void main(String[] args) {
IntStream.rangeClosed(1, 100)
.mapToObj(String::valueOf)
.flatMap(s -> Arrays.stream(s.split("")))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.forEach((k,v) -> System.out.printf("The digit %s showed up %d times between 1-100%n", k, v));
}
Instead of converting a number to string and then loop over its digits, you can also take the remainder by 10, i.e., the last digit, and then divide the number by 10 to "shift" it to the right.
For example, 45 % 10 == 5, and 45 / 10 == 4.
After you exit the while loop, your number is a single-digit number, so you have to count again that digit.
public class CountEachDigit {
public static void main(String[] args) {
int[] digits_count = new int[10];
int min = 1;
int max = 100;
for (int i = min; i <= max; ++i) {
int number = i;
while (number > 9) {
int last_digit = number % 10;
digits_count[last_digit] += 1;
number /= 10;
}
digits_count[number] += 1;
}
for (int i = 0; i < 10; i++) {
int count = digits_count[i];
System.out.println("Digit " + i + " appears " + count + " times in range [" + min + ", " + max + "]");
}
}
}
Using strings:
for (int i = 1; i <= 100; i++) {
String num = String.valueOf(i);
for(int j=0;j<num.length();j++){
//substracting 0 to get the integer value
counts[num.charAt(j)-'0']++;
}
}
for (int i = 0; i < 10; i++) {
System.out.println("The digit " + i + " showed up " + counts[i] + " times between 1-100.");
}
You can do it using by streaming and collecting in a map.
allocate a map to hold the counts
stream the values from 1 to 100 inclusive
within mapMulti
get the last digit by using the remainder % operator
accept the digit and place on the stream
expose the next digit by dividing by 10
Now collect the digits in the map, creating a frequency count as they occur. Each digit will the the key and the value will be the count.
Map<Integer, Integer> counts = IntStream.rangeClosed(1, 100)
.mapMulti((val, consumer) -> {
while (val > 0) {
consumer.accept(val % 10);
val /= 10;
}
}).boxed()
.collect(Collectors.toMap(i -> i, i -> 1, Integer::sum));
counts.forEach((digit, count) -> System.out
.println(digit + " occurs " + count + " times."));
prints
0 occurs 11 times.
1 occurs 21 times.
2 occurs 20 times.
3 occurs 20 times.
4 occurs 20 times.
5 occurs 20 times.
6 occurs 20 times.
7 occurs 20 times.
8 occurs 20 times.
9 occurs 20 times.
I want to make it so that the code only adds completely unique versions of the number I am trying to read (ie. 1 in 111 gives out 3, but 33 in 333 only gives out 33.), but when I try to output the result, instances like the latter example count up once every interval and add each instance counted (33 in 333 gives out 66 instead of 33, for example).
Here is my code so far:
public static int sumRepeat(int num, String text)
{
int sum = 0;
String calc = Integer.toString(num);
int value = text.indexOf(calc);
for (int i = 0; i < text.length() - calc.length() + 1; i++) {
if (text.substring(i, i + calc.length()).equals(calc))
sum += num;
}
return sum;
}
Could someone help me get it to where I do not run into this error and the code runs as intended? Thank you.
Edit: Apologies, but I have more test cases than I initially said I had. Here are all of my test cases:
sumRepeat(1, "I love CSCE111") returns 3
sumRepeat(12, "The bill is $12.97") returns 0
sumRepeat(33, "333 bananas for 33 monkeys.") returns 66
sumRepeat(333, "My number is (333)-333-3333") returns 999
sumRepeat(87, "I can't believe Aragorn is 83 years old. 83!") returns 0
sumRepeat(41, "41414141") returns 164
sumRepeat(0, "") returns 0
Update (based on updated question):
You can use the Java Regex API to solve it. Use the regex, "(?<!\\$)(" + String.valueOf(num) + ")" and add each match to sum. Note that ?<! is used for negative lookbehind. Here, it means num should not be preceded by $.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(sumRepeat(1, "111"));
System.out.println(sumRepeat(33, "333"));
System.out.println(sumRepeat(1, "I love CSCE111"));
System.out.println(sumRepeat(12, "The bill is $12.97"));
System.out.println(sumRepeat(33, "333 bananas for 33 monkeys."));
System.out.println(sumRepeat(333, "My number is (333)-333-3333"));
System.out.println(sumRepeat(87, "I can't believe Aragorn is 83 years old. 83!"));
System.out.println(sumRepeat(41, "41414141"));
System.out.println(sumRepeat(0, ""));
}
public static int sumRepeat(int num, String text) {
int sum = 0;
Matcher matcher = Pattern.compile("(?<!\\$)(" + String.valueOf(num) + ")").matcher(text);
while (matcher.find()) {
sum += num;
}
return sum;
}
}
Output:
3
33
3
0
66
999
0
164
0
Non-regex solution:
You can use String#indexOf(String, int) to find the index of calc starting from the given index. Every time this index is found, add num to sum and move this index by the length of num; otherwise, keep moving this index by 1.
Demo:
public class Main {
public static void main(String[] args) {
System.out.println(sumRepeat(1, "111"));
System.out.println(sumRepeat(33, "333"));
System.out.println(sumRepeat(1, "I love CSCE111"));
System.out.println(sumRepeat(12, "The bill is $12.97"));
System.out.println(sumRepeat(33, "333 bananas for 33 monkeys."));
System.out.println(sumRepeat(333, "My number is (333)-333-3333"));
System.out.println(sumRepeat(87, "I can't believe Aragorn is 83 years old. 83!"));
System.out.println(sumRepeat(41, "41414141"));
System.out.println(sumRepeat(0, ""));
}
public static int sumRepeat(int num, String text) {
int sum = 0;
String calc = Integer.toString(num);
int len = calc.length();
int i = 0;
while (i < text.length()) {
int index = text.indexOf(calc, i);
if (index != -1) {
if (index == 0 || text.charAt(index - 1) != '$') {// Check to exclude num preceded by $
sum += num;
i = index + len;
} else {
i++;
}
} else {
i++;
}
}
return sum;
}
}
Output:
3
33
3
0
66
999
0
164
0
Original solution:
Modify the loop counter to terminate with i < text.length() and proceed with step value of num.
public class Main {
public static void main(String[] args) {
System.out.println(sumRepeat(1, "111"));
System.out.println(sumRepeat(33, "333"));
}
public static int sumRepeat(int num, String text) {
int sum = 0;
String calc = Integer.toString(num);
for (int i = 0; i < text.length(); i += num) {
if (text.substring(i, i + calc.length()).equals(calc)) {
sum += num;
}
}
return sum;
}
}
Output:
3
33
Rather than incrementing by 1, you should increment by the length of the input number. 1 is only 1 digit long, so moving your substring by 1 digit works, while 33 is 2 digits long, so moving your substring by 1 digit will see 33 twice.
[33]3 and 3[33]
The answer is to increment by the number of digits when a match is found, and since you're already in a for loop which is incrementing by 1, we subtract 1 from the length of the input number.
if (text.substring(i, i + calc.length()).equals(calc))
{
sum += num;
i += calc.length() - 1;
}
You have to print a pattern using recursion. Given a input
N
the pattern looks like this
N
,
a
i
,
a
i
+
1
,
a
i
+
2
,.....,
N
. Where if
a
i
>
0
then
a
i
+
1
=
a
i
−
5
else
a
i
+
1
=
a
i
+
5
. It will be a decreasing sequence from
N
till
a
i
<=
0
and then an increasing sequence till
N
. (See sample test cases for better explanation)
Input format
First line contains an integer
T
denoting number of test cases.
For each of the next
T
lines, each line contains an integer
N
.
Output format
For each test case on a new line, print the required pattern.
Constraints
1
<=
T
<=
6
0
<=
N
<=
2000
Example
Input
2
16
10
Output
16 11 6 1 -4 1 6 11 16
10 5 0 5 10
Sample test case explanation
For the first test case
N=16, it will be a decreasing sequence till the printing number becomes <=0.
16 11 6 1 −4
After this point it will be a increasing sequence till the printing number becomes N
1 6 11 16
So the pattern is 16 11 6 1 −4 1 6 11 16.
My code is below but i got the output as 16,11,6,1,-4 only. Help me to correct this code
import java.util.Scanner;
public class Day3
{
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=n)
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
series(n,true);
t-=1;
}
}
}
Because 'n' changes in every cases. You must create another variable and keep first 'n' in that, for control if temp smaller than 'n'.
For example
import java.util.Scanner;
public class Day3
{
int firstN = 0; //added that line
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=firstN) //changed that line
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
firstN = n; //added that line
series(n,true);
t-=1;
}
}
}
Also a little tip;
you can use (flag) for (flag==true)
and (!flag) for (flag==false)
Just FYI : Although this can be solved using recursion, it can be solved more efficiently without using recursion. It is as simple as this:
private static void printSeries(int N) {
int T = N;
while ( T >= 0 ) {
System.out.print(T + " ");
T = T - 5;
}
while ( T <= N ) {
System.out.print(T + " ");
T = T + 5;
}
}
Hello I am attempting to perform the hailstone sequence.
A hailstone sequence is basically: take a given integer n - if even, the next integer in the sequence is n/2, if odd, the next integer in sequence is n * 3 + 1.
The API I must follow for my assignment requires it to be performed as it is with a method returning an arraylist.
My problem is the code just hangs forever, when I added output in the method itself to see what was happening I see it always hangs when it is given the number 10 for some reason.
I am hoping that there is something small I am missing here perhaps in my conditions.
Here is some sample output when given n value of 15 it outputs this over and over again.
15 is odd so I make it 3n+1: 46
46 is even so I divide by 2: 23
23 is odd so I make it 3n+1: 70
70 is even so I divide by 2: 35
35 is odd so I make it 3n+1: 106
106 is even so I divide by 2: 53
53 is odd so I make it 3n+1: 160
160 is even so I divide by 2: 80
80 is even so I divide by 2: 40
40 is even so I divide by 2: 20
20 is even so I divide by 2: 10
15 is odd so I make it 3n+1: 46
My code
import java.util.ArrayList;
import java.util.Scanner;
public class HailstoneSequence {
public static ArrayList<Integer> getHailstoneSequence(int n){
ArrayList<Integer> results;
results = new ArrayList<Integer>();
results.add(n);
//while the last number is not 1 perform these actions
while((results.size() - 1) != 1){
//for each number in the array
for(int i=0; i< results.get(i); i++){
//test if odd or even
if((results.get(i)%2)==0){
System.out.println(results.get(i)+" is even so I divide by 2: "+ (results.get(i)/2));
results.add((results.get(i)/2));
}
else{
//odd
System.out.println(results.get(i)+" is odd so I make it 3n+1: "+ (3*(results.get(i))+1));
results.add((3*(results.get(i))+1));
}
}
}
return results;
}
public static void main(String[] args) {
int n=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of n ");
n=sc.nextInt();
sc.close();
//create an initialize new array list to hold results of the hailstonesequence
ArrayList<Integer> list;
list = new ArrayList<Integer>();
list = getHailstoneSequence(n);
//for each number in the array
for(int i=0; i< list.get(i); i++){
if ((list.get(i)!= 1)){
if((list.get(i)%2)==0){
System.out.println(list.get(i)+" is even so I divide by 2: "+ (list.get(i+1)));
}
else{
//odd
System.out.println(list.get(i)+" is odd so I make it 3n+1: "+ (list.get(i+1)));
}
}
else{break;}
}
}
}
In your method for(int i=0; i< results.get(i); i++){ and in main for(int i=0; i< list.get(i); i++){
These do not loops over each element of the list, or at least not only once, and it'll eventually result in out of bounds if you never added to the list.
Say results.get(i) is 10, and that's the only number in the list... You then add 5 ten times because 10 is even and the loop is running ten times. You then are probably adding 16 5*10 times, etc, etc
Adding elements to lists while you iterate over them is generally a bad idea anyway. You only need to keep track of two numbers at a time, and can add to the list separate from the iteration process.
Here's a working sample
ArrayList<Integer> results = new ArrayList<Integer>();
results.add(n);
if (n == 1) return results;
int next;
if (n % 2 == 0) next = n / 2;
else next = 3*n + 1;
results.add(next);
while (next != 1) {
if (next % 2 == 0) next = next / 2;
else next = 3*next + 1;
results.add(next);
}
return results;
I'm not sure why this won't print out anything
for (int number : humidity)
{
if (sum < 12)
{
System.out.printf("%6d",humidity[sum]);
sum++;
}
}
Humidity is taken in from a file
Scanner inFileHumid = new Scanner(fileNameHumid);
int [] humidity = new int[length];
Then is set to the array
while (inFileHumid.hasNextInt())
{
humidity[n] = inFileHumid.nextInt( );
n++;
}
and the numbers from the file are 69 67 66 64 66 69 67 67 70 69 69 70 which are the ones I'm trying to get to be printed in my for each loop
You are iterating each number in humidity, but then you ignore those values and test some unrelated sum. I think you want
for (int number : humidity)
{
System.out.printf("%6d", number);
}
Or equivalently,
for (int sum = 0; sum < humidity.length; sum++)
{
System.out.printf("%6d", humidity[sum]);
}
I think you just have a problem indexing into humidity. So this should work.
for (int number : humidity){
if (number < 12) // Look at the value
{
System.out.printf("%6d", number); // Print what is in the array
}
}
Assuming sum is zero before the loop is entered, that code works.
int[] humidity = {1,2,3,4,5,6,7,8,9,0,1,2};
int sum= 0;
for (int number : humidity) {
if (sum < 12) {
System.out.printf("%6d", humidity[sum]);
sum++;
}
}
producing:
1 2 3 4 5 6 7 8 9 0 1 2
So for the code to fail sum must be greater or equal to 12 before the loop is entered.