I need to write a method called printOnLines() that takes two arguments an integer n and an integer inLine and prints the n integer, every inLine on a line.
for n = 10, inLine = 3:
1, 2, 3
4, 5, 6
7, 8, 9
10
My call is (10,3). Here's my code:
public static void printOnLines(int n, int s) {
for(int i=1; i<=s; i++) {
for(int j=1; j<=n-1; j++) {
System.out.print(j + ", ");
}
System.out.println();
}
}
}
I believe that there are two mistakes:
I need to remove the last comma appearing in the output.
I need to place 3 of the numbers of each line until I reach the
number 10.
Use this:
public static void printOnLines(int n, int s){
StringBuilder builder = new StringBuilder();
for(int i = 1; i <= n; i++){
builder.append(i);
if(i % s == 0)builder.append("\n");
else builder.append(", ");
}
System.out.println(builder.toString().substring(0,builder.toString().length() - 2));
}
I assume you've already had to submit your homework, so here's how I'd do it:
class printonlines {
public static void main(String[] args) {
printOnLines(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
public static void printOnLines(int n, int s) {
for(int i=1; i<=n; i++) { // do this loop n times
if ( (i != 1) && (i-1)%s == 0 ) { // if i is exactly divisible by s, but not the first time
System.out.println(); // print a new line
}
System.out.print(i);
if (i != n) { // don't print the comma on the last one
System.out.print(", ");
}
}
}
}
Oh, you don't want to use any if statements. All you really learn from doing "tricks" like what you are asked to do is a single trick, not how to write easily comprehensible (even by yourself when you have to debug later) code.
Anyway, here's my less comprehensible but more tricky code that doesn't use if as per the suggestions from the answer from #DavidWallace. I'm sure someone can do it neater but this is the best I could do in 15 minutes...
class printonlineswithnoifs {
public static void main(String[] args) {
printOnLines(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
// i 012012012
// j 000333666
// i+j 012345678
public static void printOnLines(int n, int s) {
int i = 0;
int j = 1;
for (; j <= n; j+=s) {
for (; i < (s-1) && (j+i)<n; i++) {
System.out.print((i+j) + ", ");
}
System.out.println(i+j);
i=0;
}
}
}
I'm not going to post a complete solution, since this is clearly homework. But here is what I would do, if I weren't allowed to use if statements or ternary operators.
Make the index of the outer loop start at 0 and increase by s on every iteration, instead of by 1 (So it goes 0, 3, 6, 9 in your example).
Print the sum of the two loop indexes on each iteration.
Print the last number on each line outside of the inner loop, without a comma.
Edit
OK, on #localhost's request, here is my solution.
public static void printOnLines(int n, int s) {
for (int i = 0; i < n; i += s) {
int j;
for (j = 1; j < s && i + j < n; j++) {
System.out.print(i + j + ", ");
}
System.out.println(i + j);
}
}
Here is the code sample you wanted..
public static void printOnLines(int n, int s) {
for (int i = 1; i < n; i++) {
System.out.print(i + ",\t");
if (i % 3 == 0) System.out.println();
}
System.out.println(n);
}
Related
I've been running into the issue of calling the class that's supposed to print even and odd numbers into the main method, printing each number without overwriting the previous one.
I've tried replacing the public int with public void, and it still didn't work, if you guys could help me it would help a lot.
this is the code:
package myprojects;
import java.util.*;
class ArrayMethod {
private int[] Array;
public void Calc(int[] Array) {
this.Array = Array;
}
public int Sum() {
int sum = 0;
for (int i = 0; i < Array.length; i++) {
sum += Array[i];
}
return sum;
}
public double Average() {
return Sum() / Array.length;
}
public int PrintOdd() {
for (int i = 0; i < Array.length; i++)
if (Array[i] % 2 != 0) {
int Odd = Array[i];
System.out.println(Odd);
}
}
public int PrintEven() {
for (int i = 0; i < Array.length; i++)
if (Array[i] % 2 == 0) {
int Even = Array[i];
System.out.println(Even);
}
}
}
public class ArrayEX {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
ArrayMethod B = new ArrayMethod();
int[] A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
B.Calc(A);
System.out.println("Sum of the numbers inside array is " + B.Sum());
System.out.println("Average of the numbers inside array is " + B.Average());
System.out.println("Even numbers " + B.PrintEven());
System.out.println("Odd Numebrs " + B.PrintOdd());
}
}
thank you to everyone who answered my question, the issue was resolved by making PrintOdd and PrintEven methods into Void type and calling it to main method outside of a print System.
my dearest thanks to #popovko57 and #zapl, who provided the solution.
If your function return nothing, you need to use void type method.
First you can update PrindOdd and PrintEven method to print each odd and even numbers when these functions are called:
class ArrayMethod {
...
public void PrintOdd() {
System.out.println("PrintOdd");
for (int i = 0; i < Array.length; i++)
if (Array[i] % 2 != 0) {
int Odd = Array[i];
System.out.print(Odd + " ");
}
}
public void PrintEven() {
System.out.println("PrintEven");
for (int i = 0; i < Array.length; i++)
if (Array[i] % 2 == 0) {
int Even = Array[i];
System.out.print(Even + " ");
}
System.out.println();
}
}
To print the result you need to update the way to call these functions:
public class Main {
public static void main(String[] args) {
....
B.PrintEven();
B.PrintOdd();
}
}
I hope that answers your question
The input is supposed to have an even length. The problem is that on the first iteration of the loop, it print Sc, but then it prints ch instead of ho. I'm not sure how to make that jump.
public static void twoAtATime(String a) { // School
int len = a.length();
if(len%2 == 0) {
for(int i = 0; i <a.length()/2; i++) {
System.out.print(a.substring(i,i+1) + a.substring(i+1,i+2));
System.out.println();
}
}
The output is supposed to be like this:
Sc
ho
ol
To fix it:
Increase i by 2.
Iterate until i < len.
You can improve it:
By calling substring once for two chars.
Using println with param.
Incrementing i once - i += 2.
After improvements:
public static void twoAtATime(String s) {
int len = s.length();
if (len % 2 == 0) {
for (int i = 0; i < len; ) {
System.out.println(s.substring(i, i += 2));
}
}
}
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1
{
public static void main()
{
int num, sum=0;
int i;
for(num=1; num<100; num++)
{
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
Change your code to :
public static void main(String[] s1) throws Exception {
int num, sum = 0;
int i;
for (num = 1; num < 100; num++) {
for (int j = 1; j <= num - 1; j++) { // change made here
if (num % j == 0) {
sum = sum + j;
}
}
if (sum == num) {
System.out.println(sum);
}
sum = 0; // change made here
}
}
Key takeaways:
Reset sum to 0 once done with inner iteration
In your inner for-loop you need to check if till num - 1 and not num because every number is divisible by itself
1) you definitely need to reset your sum variable for every iteration, so you should do int sum = 0; in every loop.
2) you need to iterate while j <= num/2;!
3) consider using Java 8, I'll write some sample here for you.
See my example here, this is so beautiful:
public class PerfectNumbersDemo {
public static void main(String[] args) {
IntStream.range(1, 100)
.filter(PerfectNumbersDemo::isPerfect)
.forEach(System.out::println);
}
private static boolean isPerfect(int number) {
return number == IntStream.rangeClosed(1, number / 2)
.filter(i -> number % i == 0)
.sum();
}
}
This seems to be an assignment or homework question. You are meant to solve this by yourself and not ask it to the people on Stack overflow.
However, what you are looking for has an answer here. Beware! This code prints if the input number is perfect number or not but does not print all the numbers below 100 that could be perfect numbers. That is your homework.
You need to:
sum = 0 with every loop iteration
iterate until < num and not <= num
Here's the fixed code:
public static void main(String[] args) {
int sum;
for(int num = 1; num < 100; num++) {
sum = 0;
for(int j = 1; j< num; j++) {
if(num % j == 0) {
sum += j;
}
}
if(sum == num) {
System.out.println(sum);
}
}
}
Output:
6
28
So, your code have some minor problems and I will try to pinpoint them out.
1.First of all your sum variable should be inside the first for loop
2. The limit upto which the second loop will run will be j<num not j<=num because, for the perfect number, the number itself shouldn't be counted in the sum.
You code will look like this.
I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.
class CompProject1 {
public static void main()
{
int num;
for(num=1; num<100; num++)
{
int sum = 0;
for(int j = 1; j<=num ; j++)
{
if(num%j==0)
{
sum = sum+j;
}
}
if(sum==num)
{
System.out.println(sum);
}
}
}
}
public class factors{
public static void main(String args[]){
int sum=0;
for(int k=2;k<=30;k++){
for(int i=1;i<k;i++)
{
if(k%i==0)
sum=sum+i;
}
if(k==sum)
System.out.println(sum);
sum=0; //sum=0 is very important.
}
}
}
OUTPUT
6
28
class PERFECT
{
public static void main(String args[])
{
int i,j,S,
for(i=1;i<=100;i++)
{
S=0
for(j=1;j<i;j++)
{
if(i%j==0)
S+=j;
if (S==i)
System.out.println(i+"is perfect");
}
}
}
}
Here is an alternate way of finding perfect numbers.
if 2p-1 is prime when p is prime. Then (2p-1)(2p-1) is a perfect number. 2p-1 is known as a Mersenne Prime
As these numbers get real big real fast, using BigInteger is recommended.
This computes the first 10 perfect numbers.
int N = 10;
int count = 1;
for(int i = 2; i < 10_000; i += i == 2 ? 1 : 2) {
BigInteger val = BigInteger.valueOf(i);
if (val.isProbablePrime(99)) {
BigInteger mersenne1 = (BigInteger.ONE.shiftLeft(i)).subtract(BigInteger.ONE);
if (!mersenne1.isProbablePrime(99)) {
continue;
}
BigInteger mersenne2 = BigInteger.ONE.shiftLeft(i-1);
System.out.printf("%3d: %,d\n",count, mersenne1.multiply(mersenne2));
if (count++ >= N) {
break;
}
}
}
prints
1: 6
2: 28
3: 496
4: 8,128
5: 33,550,336
6: 8,589,869,056
7: 137,438,691,328
8: 2,305,843,008,139,952,128
9: 2,658,455,991,569,831,744,654,692,615,953,842,176
10: 191,561,942,608,236,107,294,793,378,084,303,638,130,997,321,548,169,216
I'm supposed to modify code that I've written for an assignment:
public class ToweringStrings2 {
public static final int H = 2; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print("+");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("#");
}
System.out.println();
}
}
so that it prints sequential numbers starting at 1, instead of +s. Currently, it prints:
This is what the new code is supposed to print:
and so on.
For some reason I'm just really stuck and can't figure it out.
You can create an extra variable to print and increment
Like that:
public class ToweringStrings2 {
public static final int H = 10; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
int count = 1;
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print(count++ + " ");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("# ");
}
System.out.println();
}
}
Step 1 - make it print a variable rather than a hard-coded string. Instead of System.out.print("+"), System.out.print(counter).
For this to work you need to have declared counter somewhere in the same scope as the statement: int counter = 0.
Run this. You'll see it print "0" where it used to print "+".
Step 2 - Now you need to make counter increase by one every time it prints.
Find the right place to add:
counter = counter + 1;
Run it and see it work.
Further notes
A more concise alternative to var = var + 1 is var++.
You can even do this at the same time as you use the value of a variable:
System.out.println(var++);
This can be used to express some algorithms very concisely -- but it can be confusing for beginners, so feel free to not use this technique until you're comfortable with the basics.
Hello I'm new to programming and registered to this forum :)
So I created a little program with nested for loops that prints out all combinations of five numbers which can have a value from 0 to 5. With nested for-loops this works fine. But isn't there a cleaner solution? I tried it with calling the for loop itself, but my brain doesn't get the solution.. :(
//my ugly solution
int store1, store2, store3, store4, store5;
for (int count = 0; count <= 5; count++) {
store1 = count;
for (int count2 = 0; count2 <= 5; count2++) {
store2 = count2;
for (int count3 = 0; count3 <= 5; count3++) {
store3 = count3;
for (int count4 = 0; count4 <= 5; count4++) {
store4 = count4;
System.out
.println(store1 + " " + store2 + " " + store4);
}
//I'm trying around with something like this
void method1() {
for (int count = 0; count <= 5; count++) {
list.get(0).value = count;
count++;
method2();
}
}
void method2() {
for (int count = 0; count <= 5; count++) {
list.get(1).value = count;
count++;
method1();
}
}
Usually when people try to use recursion or functional, using a loop is simpler or faster. However, in this case recursion is the simpler option in combination with a loop.
public static void method(List<Integer> list, int n, int m) {
if (n < 0) {
process(list);
} else {
for(int i = 0; i < m; i++) {
list.set(n, i);
method(list, n-1, m);
}
}
}
I know that you are trying combinations but this might help.
Permutation with repetitions
When you have n things to choose from ... you have n choices each time!
When choosing r of them, the permutations are:
n × n × ... (r times) = n^r
//when n and r are known statically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i = 0, j = 0;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
System.out.println(values[j] + " " + values[i]);
}
}
}
}
//when n and r are known only dynamically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i[] = new int[r];
int rc = 0;
for(int j=0; j<Math.pow(n,r); j++)
{
rc=0;
while(rc<r)
{
System.out.print(values[i[rc]] + " ");
rc++;
}
System.out.println();
rc = 0;
while(rc<r)
{
if(i[rc]<n-1)
{
i[rc]++;
break;
}
else
{
i[rc]=0;
}
rc++;
}
}
}
}
Something like this?
// Print all sequences of len(list)+n numbers that start w/ the sequence in list
void method( list, n ) {
if ( list.length == n )
// print list
else for ( int c=0; c<=5; c++ ) {
// add c to end of list
method( list, n );
// remove c from end of list
}
}
Initial call would be method( list, 5 ) where list is initially empty.
here another interative but less elegant version
while (store1 < 6) {
store5++;
if (store5 == 6) {
store5 = 0;
store4++;
}
if (store4 == 6) {
store4 = 0;
store3++;
}
if (store3 == 6) {
store3 = 0;
store2++;
}
if (store2 == 6) {
store2 = 0;
store1++;
}
System.out.println(store1 + " " + store2 + " " + store3 + " " + store4 + " " + store5 + " ");
}
The simplest code I can think of would tackle the problem with an entirely different approach:
public class TestA {
public static void main(String[] argv) {
for (int i=0; i<(6 * 6 * 6 * 6 * 6); ++i) {
String permutation = Integer.toString(i, 6);
System.out.println("00000".substring(permutation.length()) + permutation);
}
}
}
From your text (not your code) I gather you have 5 places and 6 symbols, which suggests there are 6 to the 5th power combinations. So the code just counts through those numbers and translates the number to the output combination.
Since this can also be viewed as a number system with base 6, it makes use of Integer.toString which already has formatting code (except the leading zeros) for this. Leading zeros are added where missing.