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.
Related
It's about finding the prime numbers from 2 to 1000 using this method but I can't get the solution and I've been thinking and trying to solve this issue for three days. I'm desperate for help so if anyone can help me I would really appreciate it
I tried another for loop and an if statement since my teacher said that I only need another loop or just one more code line but I can't seem to get the solution. I'm really bad at this so I'm sorry if my code seems cringeworthy
public class Practica {
public static void main(String []
byte []marcado = new byte [1000];
for (int i = 2; i < 1000; i++);
if (marcado[i] == 1) {
for (int j = 2; i*j < 1000; j++) {
marcado [i*j] = 0;
}
}
I expect to have all the prime numbers printed
Give it a shot:
public static void main(String[] args) {
byte[] marcado = new byte[1000];
for (int i = 2; i*i < 1000; i++) {
if (marcado[i] == 0) {
for (int j = 2; i * j < 1000; j++) {
marcado[i * j] = 1;
}
}
}
// print the numbers:
for (int i = 1; i < 1000; i++) {
if(0 == marcado[i]){
System.out.print(" " + i);
}
}
}
Besides removing syntax errors, I reversed the logic such that marcado[i]==0 indicates a prime and noneprime otherwise.
The other possibility based on your aproach would be to initialize all the array elements with "1"(eg. with fill);
So, I'm new to programming and I have this exercise where I have to read an int[][] array with the age and a handicap level of people trying to start a membership in a Club, with two categories, Senior and Open.
My job is to read the array for example [[45, 12],[55,21],[19, -2]] where the first int is the age and the second the handicap level. If the age is at least 55 and the handicap level is higher than 7 then the person gets a Senior membership if not he gets an Open one. My idea was to see the int[][] as a matrix and add both numbers (age and level) and if the number is higher than 62 I would classify it as a Senior otherwise as open.
My method looks like this:
public class montecarlo {
static String[] openOrSenior(int[][] a) {
int i, j, sum;
String[] abo = new String[a[0].length];
for (i = 0; i < a.length; i++)
for (j = 0; j < a[0].length; j++ ) {
sum = 0;
int x = a[i][j];
sum = sum + x;
if (sum > 62)
abo[i] = "Senior";
else
abo[i] = "Open"; //this would be line 12
}
return abo;
}
public static void main(String[] args) {
int [][] a = {{42, 12},{55, 21},{19,-2}};
String[] x = openOrSenior(a); //this would be line 20
Out.print(x); //here was to see what i'd get if i let it run
}
}
This is the error i get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at montecarlo.openOrSenior(montecarlo.java:12) at
montecarlo.main(montecarlo.java:20)
I would really appreciate some help.
Here's a more straightforward version with syntax errors fixed.
public class montecarlo {
static String[] openOrSenior(int[][] a) {
String[] abo = new String[a.length]; // you had a[0] here instead of a
for (int i = 0; i < a.length; i++) {
if (a[i][0] >= 55 && a[i][1] > 7) {
abo[i] = "Senior";
} else {
abo[i] = "Open";
}
}
return abo;
}
}
This fixes all the array bounds problems, but as others mentioned, not the flaws in the semantics. It makes no sense to completely rewrite this answer, so I keep it as it is.
I noticed two major problems in your code that could cause said exception.
On line 12, your problem is, you define the array size wrong.
String[] abo = new String[a.length];
But there is one more problem like that, as the second cycle takes incorrect length, you need:
for (j = 0; j < a[i].length; j++ )
OK, this problem should never happen as all your arrays have same length. But should there be someone with no handicap as just {31} alongside someone with handicap, it crashes in the cycle.
For next practice - create a new class that has two int variables, age and handicap. That is how you do it in Java. An array of integers makes no difference what is age and what is handicap.
import java.util. * ;
import java.lang. * ;
import java.io. * ;
class montecarlo {
static String[] openOrSenior(int[][] a) {
int i,
j,
sum,
x;
/*Declare x here, otherwise in your code it will create a new variable everytime in your for loop*/
String[] abo = new String[a.length];
/* a.length not a[0].length */
for (i = 0; i < a.length; i++) {
sum = 0;
/* sum should initialised to zero here every time outside the inner for loop*/
for (j = 0; j < a[0].length; j++) {
x = a[i][j];
sum = sum + x;
}
/* check outside for loop whether the total sum is greater than 62 */
if (sum > 62) {
abo[i] = "Senior";
}
else {
abo[i] = "Open";
}
}
return abo;
}
public static void main(String[] args) {
int[][] a = {
{
42,
12
},
{
55,
21
},
{
19,
-2
},
{
72,
74
}
};
String[] x = openOrSenior(a);
System.out.print(x);
}
}
Here is the working demo of what you wanted.
I have pointed out your mistakes in comments.
You have done several mistakes, Please watch the code carefully and understand what you did wrong.
Also there is a flaw in your logic which you should fix yourself.
for example age=60, handicap level=3
total=60+3=63, which is greater than 62 and hence should be "Senior" according to your logic but it is wrong since the handicap level is below 7.
Try something like
public class montecarlo {
public static void main(String[] args) {
int [][] a = {{42, 12},{55, 21},{19,-2}};
String[] x = openOrSenior(a); //this would be line 20
System.out.println(Arrays.asList(x)); //here was to see what i'd get if i let it run
}
static String[] openOrSenior(int[][] a) {
int i, j, sum;
String[] abo = new String[a.length];
System.out.println(abo.length);
for (i = 0; i < a.length; i++)
for (j = 0; j < a[0].length; j++) {
sum = 0;
int x = a[i][j];
sum = sum + x;
if (sum > 62)
abo[i] = "Senior";
else abo[i] = "Open";
} //this would be line 12
return abo;
}
}
I need to find all the permutations for a given n(user input) without backtracking.
What i tried is:
import java.util.Scanner;
import java.util.Vector;
class Main {
private static int n;
private static Vector<Vector<Integer>> permutations = new Vector<>();
private static void get_n() {
Scanner user = new Scanner(System.in);
System.out.print("n = ");
n = user.nextInt();
}
private static void display(Vector<Vector<Integer>> permutations) {
for (int i = 0; i < factorial(n) - 1; ++i) {
for (int j = 0; j < n; ++j) {
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
}
System.out.println();
}
}
private static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
private static int max(Vector<Integer> permutation) {
int max = permutation.elementAt(0);
for (int i = 1; i < permutation.size(); ++i)
if (permutation.elementAt(i) > max)
max = permutation.elementAt(i);
return max;
}
// CHECKS FOR ELEMENT COUNT AND 0 - (n-1) APPARITION
public static int validate_permutation(Vector<Integer> permutation) {
// GOOD NUMBER OF ELEMENTS
if (max(permutation) != permutation.size() - 1)
return 0;
// PROPER ELEMENTS APPEAR
for (int i = 0; i < permutation.size(); ++i)
if (!permutation.contains(i))
return 0;
return 1;
}
private static Vector<Integer> next_permutation(Vector<Integer> permutation) {
int i;
do {
i = 1;
// INCREMENT LAST ELEMENT
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
// IN A P(n-1) PERMUTATION FOUND n. "OVERFLOW"
while (permutation.elementAt(permutation.size() - i) == permutation.size()) {
// RESET CURRENT POSITION
permutation.set(permutation.size() - i, 0);
// INCREMENT THE NEXT ONE
++i;
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
}
} while (validate_permutation(permutation) == 0);
// OUTPUT
System.out.print("output of next_permutation:\t\t");
for (int j = 0; j < permutation.size(); ++j)
System.out.print(permutation.elementAt(j) + " ");
System.out.println();
return permutation;
}
private static Vector<Vector<Integer>> permutations_of(int n) {
Vector<Vector<Integer>> permutations = new Vector<>();
// INITIALIZE PERMUTATION SET WITH 0
for (int i = 0; i < factorial(n); ++i) {
permutations.addElement(new Vector<>());
for(int j = 0; j < n; ++j)
permutations.elementAt(i).addElement(0);
}
for (int i = 0; i < n; ++i)
permutations.elementAt(0).set(i, i);
for (int i = 1; i < factorial(n); ++i) {
// ADD THE NEXT PERMUTATION TO THE SET
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
System.out.print("values set by permutations_of:\t");
for (int j = 0; j < permutations.elementAt(i).size(); ++j)
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
System.out.println("\n");
}
System.out.print("\nFinal output of permutations_of:\n\n");
display(permutations);
return permutations;
}
public static void main(String[] args) {
get_n();
permutations.addAll(permutations_of(n));
}
}
Now, the problem is obvious when running the code. next_permutation outputs the correct permutations when called, the values are set correctly to the corresponding the vector of permutations, but the end result is a mass copy of the last permutation, which leads me to believe that every time a new permutation is outputted by next_permutation and set into the permutations vector, somehow that permutation is also copied over all of the other permutations. And I can't figure out why for the life of me.
I tried both set, setElementAt, and an implementation where I don't initialize the permutations vector fist, but add the permutations as they are outputted by next_permutation with add() and I hit the exact same problem. Is there some weird way in which Java handles memory? Or what would be the cause of this?
Thank you in advance!
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
This is literally setting the vector at permutations(i) to be the same object as permutations[i-1]. Not the same value - the exact same object. I think this the source of your problems. You instead need to copy the values in the vector.
The task of exercise is to make a method that will work like in Example.( We must use for loop. But if you know how to do it in another way, it will be also very interesting.) Input number can be any.
Example:
Input: 3
Output:
**1**
*121*
12321
*121*
**1**
My example:
public static void main(String[] args) {
printMatrix(5);
}
public static void printMatrix (int n) {
int d = n +(n-1);
for (int i = 0; i < n ; i++)
{
for(int j = 1; j <=d; j++){
int abs = Math.abs(j-n);
System.out.print(abs>i ? "*" : i-abs+1);
}
System.out.println("");
}
My output:
****1****
***121***
**12321**
*1234321*
123454321
I can't make the next step, to turn it upside down. Dose anybody hava an ideas?
I have solved this exercise, but I think it is not a perfect solution. Does anybody have another way to solve this task?
public static void main(String[] args) {
printMatrix(5);
}
public static void printMatrix (int n) {
int d = n +(n-1);
int k = n*2;
int g = -1;
for (int i = 0; i < d ; i++)
{
if(i<n){
g++;
}
else{k=n*2;
g--;}
for(int j = 1; j <=d; j++){
if (i < n){
int abs = Math.abs(j-n);
System.out.print(abs>i ? "*" : i-abs+1);
}
else{
k--;
int abs = Math.abs(k-n);
System.out.print(abs>g ? "*" : g-abs+1);
}
}
System.out.println("");
}
}
}
Output:
****1****
***121***
**12321**
*1234321*
123454321
*1234321*
**12321**
***121***
****1****
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);
}