Write a program that read an integer number N (0 ≤ N ≤ 100) that correspond to the order of a Bidimentional array of integers, and build the Array according to the above example.
Input
The input consists of several integers numbers, one per line, corresponding to orders from arrays to be built. The end of input is indicated by zero (0).
Output
For each integer number of input, print the corresponding array according to the example. (the values of the arrays must be formatted in a field of size 3 right justified and separated by a space. None space must be printed after the last character of each row of the array. A blank line must be printed after each array.
This is My Code. Here I get presentation error always. I know when space or line is not matching then get presentation error.But here i don't understand why give me presentation error.
import java.util.Scanner;
import java.text.DecimalFormat;
public class FirstClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
DecimalFormat df = new DecimalFormat("0.0");
Scanner input = new Scanner(System.in);
int n;
while((n =input.nextInt())!= 0){
int newArray[][] = new int[n][n];
int hn = n/2;
if(n%2 == 1) {
hn++;
}
int a = 0;
int b = n-1;
for (int l = 1; l <= hn; l++) {
for (int i = a; i <= b; i++) {
for (int j = a; j <= b; j++) {
newArray[i][j] = l;
}
}
a++;
b--;
}
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray.length; j++) {
if (j == 0) {
System.out.print(" "+newArray[i][j]);
}else {
System.out.print(" "+newArray[i][j]);
}
}
System.out.println();
}
System.out.println();
}
}
}
The problem is with your printing logic. Try the following code for printing. I have checked the code in the online judge, and its working!
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray.length; j++) {
if(j == 0) System.out.printf("%3d",newArray[i][j]);
else System.out.printf(" %3d",newArray[i][j]);
}
System.out.println();
}
Hopefully this will solve your problem. If you don't understand anything let me know. Happy coding!
Related
Help with this question:
Take a positive integer n and form n triangles from stars with their base down of size n each.
For example, for input 3, the following output will be obtained:
* * *
** ** **
*** *** ***
Here's what I've tried.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
for (int c = 1; c <= r; c++)
System.out.print("*");
System.out.println();
}
}
}
Here's my solution, with explanations in comments
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)) {
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) { // <-- we will have to print n rows
printLine(n, r);
}
}
}
static void printLine(int n, int lineNumber) {
StringBuffer line = new StringBuffer();
for(int i = 0; i < n; i ++) { // <-- each line will have '*'s for n triangles
for(int j = lineNumber; j > 0; j--) { // <-- each line has as many '*'s as its line number, so print those first
line.append("*");
}
for(int j = 0; j < n - lineNumber + 1; j ++) { // <-- we then have to add enough spaces to leave room for the next triangle's '*'s
line.append(" ");
}
}
System.out.println(line.toString()); // <-- print the line we've built so far
}
}
EDIT:
Here's a replit that avoids one of the loops by using a modulo to print an entire line at once, and also uses recursion, for no real reason, in place of the outer-most loop: https://replit.com/#anqit/MicroExtrovertedTrace#Main.java
First, the blanks follow the stars, then, you have to repeat n times the two loops:
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++)
System.out.print("*");
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
}
System.out.println();
}
You have one for loop that prints out a single triangle of stars using nested for loops. The outer loop is responsible for the number of rows and the inner loops are responsible for printing the spaces and stars.
In my updated code, I added an outer loop that runs n times, and each time it runs, it prints out a triangle of stars. The inner loops are responsible for printing the stars of the triangle and spaces between the triangles.
The main difference is that in your first code, only one triangle is printed, while in my updated code, n triangles are printed. In addition, the indentation of the inner loops has been adjusted to align the triangles correctly on the same line.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n:");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error: please enter a positive number:");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++) {
System.out.print("*");
}
for (int i = 0; i < n - r + 1; i++) {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Here is a 3 forloop variant
int n = 4;
for (int i = 1; i <= n; i++) {
StringBuilder b = new StringBuilder("");
for (int s = 0; s < n; s++) {
b.append(s < i ? "*" : " ");
}
String line = b.append(" ").toString();//space between
for (int j = 1; j < n; j++) {
System.out.print(line);
}
System.out.println();
}
produces
> * * *
> ** ** **
> *** *** ***
> **** **** ****
I need to print all prime numbers from 1 to 1,000,000 and print all even numbers from 4 to 10,000 and two prime numbers that sum to it.
I have a sieve method that changes all non-prime numbers in an array to a 0 (the problem specifically asks for this to be done), and I need to use a goldbach method that passes this array and displays all even numbers from 4 to 10,000 and two primes that sum up to that number.
The point of the goldbach portion of the problem is to print the numbers efficiently, and I am pretty sure my solution uses a polynomial time search when the correct solution is to be done with a linear time search. Any clue on how I might optimize this?
import java.lang.Math;
public class sieveAndGoldbach {
public static void sieve(int[] a) {
int n = a.length;
a[0] = 0;
for (int i = 1; i <= Math.sqrt(n); i++) {
if (a[i] != 0) {
for (int j = a[i]*a[i]; j <= n; j+=a[i]) {
a[j-1] = 0;
}
}
}
}
public static void goldbach(int[] a) {
int max = 10000;
for (int i = 4; i <= max; i += 2) {
int count = 0;
for (int j = 0; j < i/2; j++) {
if (a[j] != 0) {
int difference = i-a[j];
for (int k = 0; k < max; k++) {
if (a[k] == difference && count == 0) {
System.out.println(i + " = " + a[j] + " + " + (difference));
count++;
}
}
}
}
}
}
public static void main(String[] args) {
//initialize and fill array from 1 to n
int n = 1000000; //initially one million GOLDBACH METHOD WILL NOT WORK FOR n < 10,000
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = i + 1;
}
//Call sieve method on array a, then print all primes, not the zeros
sieve(a);
for (int i = 0; i < n; i++) {
if (a[i] != 0) {
System.out.print(a[i]);
System.out.print(" ");
}
}
System.out.print("\n");
//Call goldbach method on array a
goldbach(a);
}
}
You currently seem to be iterating through the array of primes for each prime looking for one that sums to your target. That's not necessary; you just need to check whether the difference is a prime:
int[] primes;
int target;
for (int i = 2; i < target / 2; i++) {
if (primes[i] != 0 && primes[target - i] != 0)
...
}
Beyond that I can't see a lot of obvious optimisation but there may well be some numerical analysis that allows you to target likely primes first.
I am a newbie to java programming and I am working on this excercise from my textbook. The goal is to print a V shape pattern of numbers. From the picture below, you can see what the output should look like. I am having trouble creating the other half of numbers. I have pasted my code down below for reference.
for (int i = 7; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int k = 1; k >= i*2; k++) {
System.out.print(" ");
}
System.out.println(i);
Use the following code (just made a few modifications to your code, did not check its efficiency):
public static void main(String[] args) {
for (int i = 7; i >= 1; i--) {
for (int k = 7; k >= i; k--) {
System.out.print(" "); // Print 7-i number of spaces before start of each line
}
System.out.print(i); // Print i
for (int j = 1; j <= i*2; j++) {
System.out.print(" "); // Print i*2 number of spaces after printing i
}
System.out.println(i); // Print i
}
}
Rather then nesting loops (and iterating backwards), I would decompose the generating of white-space with a method to repeat a given String a given number of times. Like,
private static String repeat(String s, int n) {
return Stream.generate(() -> s).limit(n).collect(Collectors.joining());
}
Then I would prefer a StringBuilder and a single call to println like
public static void main(String[] args) {
int start = 6;
for (int i = 0; i < start; i++) {
int v = start - i;
StringBuilder sb = new StringBuilder();
sb.append(repeat(" ", i)).append(v);
sb.append(repeat(" ", 2 * v)).append(v);
System.out.println(sb);
}
}
I need to create a nested for loops that gives the following output,
0
1
2
3
This is what I have, but for the second test, userNum is replaced by 6 and obviously my code fails.. help?
public class NestedLoop {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
for(i = 0; i <= userNum; i++){
System.out.println(i);
for(i = 1; i <= userNum; i++){
System.out.println(" " +i);
for(i = 2; i <= userNum; i++){
System.out.println(" " +i);
for(i = 3; i <= userNum; i++){
System.out.println(" " + i);
}
}
}
}
return;
}
}
I think (it's a guess, though) that you're looking for this.
public static void main (String [] args)
{
int limit = 6;
for(int i = 0; i <= limit; i++)
{
for(int j = 0; j < i; j++)
System.out.print(" ");
System.out.println(i);
}
}
The reason why your approach fails is, as I see it, that you are looping through the numbers to show (which is right) but you fail to loop up on the number of spaces (which I resolved by relating the inner loop's limit to the outer loop's current value.
Let's talk a bit about what your intention is with these loops.
The inner loop is meant to produce an arbitrary number of spaces, depending on what number you're iterating on. So if you're on number 0, you produce no spaces, and if you're on 1, you produce one space, and so forth. The other caveat is that they all must appear on the same line, so System.out.println is the incorrect choice.
You would want to use System.out.print to print out the spaces. So let's write that.
for(int j = 0; j < 6; j++) {
System.out.print(" ");
}
This will print out six spaces unconditionally. What that condition is depends on the current number we're iterating on. That comes from your outer loop.
You only need to define a loop that starts from an arbitrary starting point - like 0 - and then loop until you are at most your ending number. For this, your current loop is sufficient:
for(i = 0; i <= userNum; i++) {
}
Now, we need to bring the two pieces together. I leave the figuring out of the question mark and what to print after you've printed the spaces as an exercise to the user, bearing in mind that you must stop printing spaces after you've reached your number.
for(int i = 0; i <= userNum; i++) {
for(int j = 0; j < ?; j++) {
System.out.print(" ");
}
}
Let's analyse the task
In every line, we should print a number and different number spaces in the front of the number.
For that, we need two loops - one outer to iterate from 0 to N and one inner to add spaces in front of the number.
private static void method1(int userNum) {
int nummSpaces = 0;
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < nummSpaces; j++) {
System.out.print(" ");
}
nummSpaces++;
System.out.println(i);
}
}
In this solution, we have variable numSpaces which used to count the number of spaces in front of the number. It is unneeded - we can use variable i for that purpose.
private static void method2(int userNum) {
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
}
Let's analyses once again the output
- the fist line: printed zero spaces and number 0
- the second line: printed one space and number 1
- the third line: printed two spaces and number 2
- and so on
Finally, we can use just one variable, which contains spaces and after that print the length of it:
private static void method3(int userNum) {
for (String spaces = ""; spaces.length() <= userNum; spaces += " ") {
System.out.println(spaces + spaces.length());
}
}
C/C++
#include <iostream>
using namespace std;
int main() {
int userNum;
int i;
int j;
cin >> userNum;
for (i = 0; i <= userNum; ++i) {
for (j = 0; j < i; ++j) {
cout << " ";
}
cout << i << endl;
}
return 0;
}
Basically, I am given an array of numbers and I have to count all the negative numbers.
Then make a new array that contains all of the positive numbers from the previous with the length of the array being firstarray-numberOfNegatives
Here is my code:
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length-1; i++)
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
I am getting the wrong result: negative numbers are replaced with 0s
At first write i < numbers.length; or i <= numbers.length-1; instead of i < numbers.length-1;
And then fix code.
Also note that you can have zeros in your 'numbers' array, so in if() in first for() you should write <=0 instead of <0
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] > 0) numbers2[count] = numbers[i];
count++;
System.out.println(numbers2[count-1]);
}
Firstly: you have an off-by-one error in your first for loop. Walk through some small example arrays in your head or on paper and you'll see.
Secondly: I think you are using your two index counters backwards in the second section. The count is supposed to be used in your new array, and i in your old one.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++) //
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) numbers2[count++] = numbers[i]; //
}
numbers = numbers2;
}
Run through a debugger and watch this line...
That -1 is suspicious
for(int i = 0; i < numbers.length-1; i++)
:)
Need to reverse your index variables in the second pass. Also the first loop had a length-1 instead of length. The second loop should go over the full length of the original array not the resulting array.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++)
if (numbers[i] < 0)
numberOfNegative++;
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) {
numbers2[count] = numbers[i];
System.out.println(numbers2[count]);
count++;
}
}
numbers = numbers2;
}
In
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
You are iterating as many times as numbers2 has positions, however, you increase i at every pass (in the for loop) regardless of whether you fund a positive number or not. Your output arrray would therefore have the first numbers2.length positive integers of numbers interleaved with a bunch of 0s!