I'm trying to write a program using Java, that (outputs) the following pattern depending on an input (integer) (n = 5):
0********1
23******45
678****901
2345678901
As you noticed:
input(3) represent 3 rows
single row digits (n * 2)
Digits should start from 0 to 9 and then repeat until the pattern is fully done
First row should have only 2 numbers (start 0 end 1)
(*) will be in between
Next row should have 4 numbers (start 23 end 45) and so on
How can this program written?
Here is my code:
import java.util.Scanner;
public class b_test_2 {
public static void main (String arug[]) {
String star = "*";
int star_count, digit = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please type a number (int)");
int n = sc.nextInt();
while (n != 0){
star_count = n * 2 - 2;
for (int i=0; i<n; i++) {
System.out.print(star);
i = i + 1;
}
String stars = star;
n = n - 1;
for (int i2=0; i2<n; i2++) {
System.out.print(star);
i2 = i2 + 1;
int x = 0;
x = digit;
x = x + 1;
if (x == 10){
x = 0;
System.out.print(digit + stars + digit);
}
}
}
}
}
There are any parts missing in your code, but you also seem to make it more complicated than it is.
To illustrate, and hopefully help you to go in the right direction, here is compact code to do it. Do not hand in this code unless you fully understand how it works.
static void printPattern(int n) {
for (int row = 1, digit = 0; row <= n; row++) {
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
for (int i = (n - row) * 2; i > 0; i--)
System.out.print('*');
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
System.out.println();
}
}
Test
printPattern(4);
Output
0******1
23****45
678**901
23456789
I case you haven't learned it yet, the % operator calculates the remainder after division.
Related
I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}
Hello All,
I was wondering if someone could help me with making a number triangle in Java that looks like the one below using nested while loops. Would someone be able to help me out?
4
56
789
1234
56789
I have a variable 'i' on the outer loop determining how many rows the triangle will be and a variable 'j' on the inner loop determine which number the triangle will begin with. the numbers have to stay between [1-9].
Can anyone help me out?
Try This, It Will Work... It accepts rows & number through user and in first for loop it runs the loop till the number of rows and second loop print the number as per the value of I in pattern and if condition to check if the number is 10 then reset the number with 1 to start the numbering again.
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
int rows, number = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter no of rows");
rows = sc.nextInt();
System.out.println("Enter no to start with");
number = sc.nextInt();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
++number;
if (number == 10) {
number = 1;
}
}
System.out.println();
}
}
}
Try.. r is for number of rows and v is the value
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int v = sc.nextInt();
int i = v - 1;
int j = 1;
while(j != r + 1){
int k = 0;
int ans = 0;
while( k < j){
i = i + 1;
if(i == 10){
i = 1;
}
ans = ans * 10 + i;
k = k + 1;
}
System.out.println(ans);
j = j + 1;
}
I'm doing this program: Given an integer, n, if the sum of its divisors (not counting itself) equals n, that number is said to be perfect. If the sum is lower, it is said to be decient, and if it is higher it is said to be abundant. For example:
6 has divisors 1,2,3: they add 6, therefore 6 is perfect. 8 has divisors 1,2,4: they add 7, therefore 8 is deciente. 24 has divisors 1,2,3,4,6,8,12: they add 36, therefore 24 is abundant.
Write a program that reads two positive integers and displays, on the screen, how many numbers there are of each type in that interval (including the extremes).
I have the following code and I know where it fails, for example if I enter a single number, I do it well, example of entries 6 and 7. If I then enter 6 and 9 the output is Perfect 1 Deficient 0 Abundant 2, when I should to be Perfect 1 Deficient 2 Abundant 0. Variable j stores the divisors of all in the variable j and then that's why it's abundant but I have not been able to correct it for more than I've tried.
import java.util.Scanner;
public class PerfectNumbers {
public static void main(String[] args) {
System.out.println("Enter two numbers for the interval:");
Scanner teclado = new Scanner(System.in);
int x = teclado.nextInt();
int y = teclado.nextInt();
int cont1 = 0;
int perfect = 0;
int deficient = 0;
int abundant = 0;
for (int i = x; i < y; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0) {
cont1 += j;
} else {
cont1 += 0;
}
}
if (cont1 == x) {
perfect += 1;
} else if (cont1 < x) {
deficient += 1;
} else if (cont1 > x) {
abundant += 1;
}
}
System.out.println("Perfect"+ perfect);
System.out.println("Deficient"+ deficient);
System.out.println("Abundant"+ abundant);
}
}
One problem is that you didn't reset cont1.
Another problem is that instead of comparing to x to decide perfect/deficient/abundant, you need to compare to i.
for (int i = x; i < y; i++) {
cont1 = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
cont1 += j;
}
}
if (cont1 == i) {
perfect += 1;
} else if (cont1 < i) {
deficient += 1;
} else {
abundant += 1;
}
}
I think the second problem was easy to overlook because of the poor naming of variables. I suggest to improve that, and it will be easier to read and harder to make such mistakes:
for (int n = start; n < end; n++) {
sum = 0;
for (int j = 1; j < n; j++) {
if (n % j == 0) {
sum += j;
}
}
if (sum == n) {
perfect++;
} else if (sum < n) {
deficient++;
} else {
abundant++;
}
}
I tried it several times but still gives me ArrayOutOfIndex. But i want to save the memory so i use
boolean[]isPrime = new boolean [N/2+1];
instead of
boolean[]isPrime = new boolean [N+1];
This gives me ArrayOutOfIndex for line 23 and 47
line 23:
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
line 47:
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
...
}
Full code:
public class PrimeSieve {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java PrimeSieve N [-s(ilent)]");
System.exit(0);
}
int N = Integer.parseInt(args[0]);
// initially assume all odd integers are prime
boolean[]isPrime = new boolean [N/2+1];
isPrime[2] = true;
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
int tripCount = 0;
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 3; i * i <= N; i=i+2) {
// if i is prime, then mark multiples of i as nonprime
if (isPrime[i]) {
int j = i * i;
while (j <= N){
tripCount++;
isPrime[j] = false;
j = j + 2*i;
}
}
}
System.out.println("Number of times in the inner loop: " + tripCount);
// count and display primes
int primes = 0;
if(N >= 2 ){
primes = 1;
}
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
if (args.length == 2 && args[1].equals("-s"))
; // do nothing
else
System.out.print(i + " ");
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
You should store and access the array using the same indexing function: isPrime[i/2]
When you change the size of your array from [N+1] to [N/2+1], you need to also update the end-conditions of your for-loops. Right now your for-loops run until i=N, so you are trying to do isPrime[i] when i > (N/2+1) ... so you get an ArrayIndexOutOfBoundsException.
Change this:
for (int i = 3; i <= N; i=i+2)
to this:
for (int i = 3; i <= N/2; i=i+2)
Well, for example if N=50 your isPrime only holds 26 elements, and you're trying to access the elements at 3,5..47,49 (which, of course, is out of bounds)
What you probably want is to use i/2 (as the index) inside your loops, that way you are still iterating over the numbers 3,5..47,49, but you use the correct indexes of your vector.
I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together 1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.
String num2;
String num3;
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");
String[] result = num3.split("");
int inte = Integer.parseInt(num3);
for (int i = 0; i < 8; i++){
// Stuck
}
How about that (I skipped exceptions...):
String[] sNums = jTextField1.getText().replaceAll("[^1-9]", "").split("(?<!^)");
int sum = 0;
for (String s : sNums) {
sum += Integer.parseInt(s); // add all digits
}
while (sum > 9) { // add all digits of the number, until left with one-digit number
int temp = 0;
while (sum > 0) {
temp += sum % 10;
sum = sum / 10;
}
sum = temp;
}
For every element in result, you need to convert it to an int, then add it to some variable, maybe called sum.
int sum = 0;
// for every String in the result array
for (int i = 0; i < BOUND; i++) {
// convert s[i] to int value
// add the int value to sum
}
This pseudo code should do it without splitting, arrays etc.
String s = "1234.56";
int sum = 0;
int i = 0;
while (i < s.length()) {
char c = s.charAt(i)
if (c >= '0' && c <= '9') sum += c - '0';
i++;
}
Should result in sum = 21
public static int addAll(String str) {
str = str.replaceAll("[^1-9]", "");
if (str.length() == 0)
return 0;
char[] c = str.toCharArray();
Integer result = c[0] - 48;
while (c.length > 1) {
result = 0;
for (int i = 0; i < c.length; i++) {
result += c[i] - 48;
}
c = result.toString().toCharArray();
}
return result;
}