I did an exercise in one of my books to get this output. We are supposed to use nested loops and basic java. I could not format the output in here but the code below produces the correct output. I got it to print the correct output but I feel like it is very redundant, mainly with the loops regarding the * and spaces if you have a better method for doing this please share!
private static void printDesign(){
int astrickStopper = 1;
int slashStopper = 1;
for (int lines = 1; lines <= 7; lines++) {
for (int firstAstrick = 6; firstAstrick >= astrickStopper; firstAstrick--) {
System.out.print("*");
}
for (int spaces = 1; spaces <= slashStopper; spaces++) {
System.out.print(" ");
}
for (int forwardSlash = 6; forwardSlash >= slashStopper; forwardSlash--) {
System.out.print("//");
}
for (int backSlash = 1; backSlash < slashStopper ; backSlash++) {
System.out.print("\\\\");
}
for (int spaces = 1; spaces <= slashStopper; spaces++) {
System.out.print(" ");
}
for (int secondAstrick = 6; secondAstrick >= astrickStopper; secondAstrick--) {
System.out.print("*");
}
astrickStopper = astrickStopper + 1;
slashStopper = slashStopper + 1;
System.out.println();
}
}
The code you wrote seems like it meets the problem description. You could move the inner loop into a function that outputs a given sequence of characters a certain number of times, then you would just be calling the function 6 times instead of having 6 inner loops.
public void printChars(int count, String chars) {
for (int i = 0; i < count; i++) {
System.out.print(chars);
}
}
Related
I am new to Java and just start my journey but i have problem with this simple function.
I am should have result like that
*2345
**345
***45
****5
But my function return something else :D What should I have to change?
public class Main08 {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
String row = "";
for (int j = 0; j < n; j++) {
if (j < n) {
System.out.println(row += "*");}
else {
System.out.print(n);}
}
}
}
}
You can try like this:
public class MyClass {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n; j++) {
if (j <= i) {
System.out.print("*");
} else {
System.out.print(j + 1);
}
}
System.out.print(" ");
}
}
}
Your issue is, that you prolonged the string multiple times and every time print it out again. I changed it such, that I only print out the numbers and asterisks depending on how the i and j relate to each other.
Also i limit the outer loop to n-1, because otherwise you will print 6 blocks (because you are starting from zero) and have a block of only asterisks at the end.
Output: *2345 **345 ***45 ****5
What you are asking is a way to replace some characters in an existing string.
The easiest way is to use the StringBuilder class because you can manage the characters, while a String is an unmodifiable sequence of characters:
A mutable sequence of characters.
In particular you need to use the method replace that:
Replaces the characters in a substring of this sequence with characters in the specified String
So to pass from an original string 12345 to **345 for example you need to do the following:
// THe original string
String original = "12345";
// THe StringBuilder populated with the original string
StringBuilder stringBuilder = new StringBuilder(original);
// Replacing the first two characters (so 12) with the string **
// to obtain the stringbuilder holding **345
stringBuilder.replace(0, 2, "**");
// Get the string **345
String result = stringBuilder.toString();
You can put this logic in your loop and apply it multiple times.
Eventually you can reuse the same StringBuilder, so in this case you need to replace a single character for each step of your for loop.
public class Main08 {
public static void main(String[] args) {
int n = 4;
int countStar=0;
int startNum=1;
for (int i = 1; i <= n; i++) {
//for displaying the "*"
countStar++;
startNum++;
for (int j = 1; j <= countStar; j++)
System.out.print("*");
//for displaying the digit
for (int k = startNum; k <= 5; k++)
System.out.print(k);
}
}
}
You can take a outer loop and inside the outer loop take two inner loops . one for printing * and the other for printing the digit. This can help you in solving other design problems if you understand the logic.
You could try this :
public static void main(String[] args) {
int n = 5;
String row = "";
for (int i = 1; i <= n; i++) {
row += i;
}
for (int i = 1; i < n; i++) {
StringBuffer buf = new StringBuffer(row);
buf.replace(0, i, "*".repeat(i));
System.out.println(buf);
}
}
The first loop create the initial row you want, and the second loop will replace the characters by stars.
The repeat appends * with same long as iterator i dynamically
I got a school assignment that I have to create a program that prints the first recurring character in a given string.
For example, if the input is "helloo", then it should output as "l". I wrote the following code but it prints "l" and "o" both.
String text = "helloo";
int length = text.length();
for (int i = 0; i <= length - 1; i++) {
char curChar = text.charAt(i);
for (int j = i + 1; j <= length - 1; j++) {
if (curChar == text.charAt(j)) {
System.out.println(curChar);
break;
}
}
}
Can someone help me out with this? Thanks for any answers!
You're breaking just the inner loop but not the outer loop. You can use break with a label for the outer loop. For example:
String text = "helloo";
int length = text.length();
outerloop:
for (int i = 0; i <= length - 1; i++) {
char curChar = text.charAt(i);
for (int j = i + 1; j <= length - 1; j++) {
if (curChar == text.charAt(j)) {
System.out.println(curChar);
break outerloop;
}
}
}
Get more information here - How to break out of nested loops in Java?
Hope this helps, but you should try doing your school assignments yourself.
I realize that you are asking for a direct fix to your current approach. But for those who might read this question in the future, there is a very sleek approach here using regular expressions:
String text = "helloo";
String match = text.replaceAll("^.*?(.)\\1.*", "$1");
System.out.println(match);
l
Demo
The basic idea of the pattern ^.*?(.)\1 is to consume the least number of characters in the string until we hit a single character which is followed by that same character.
Here's another variant:
String text = "helloo";
ArrayList<String> a = new ArrayList<String>(Arrays.asList(text.split(Pattern.quote(""))));
for(int i = 0; i < a.size()-1;i++) {
if(a.get(i).compareTo(a.get(i+1)) == 0) {
System.out.println(a.get(i));
break;
}
class FirstRepeatingChar
{
public static void main(String args[])
{
String s="hello";
for(int i=0;i<s.length();i++)
{
for(int j=0;j<s.length();j++)
{
if(s.charAt(i)==s.charAt(j))
{
System.out.println(" the First non repeating character is " +s.charAt(i));
break;
}
}
}
}
}
How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}
I have a small project to complete on my course but I'm a little stuck on solving this, basically I need to print the unicode characters in a multidimensional array to a table, 12 rows and 5 columns. So far I have this:
public class MultiArrTest {
public static void main(String[] args0) {
char[][] uc = new char[12][5];
int x = 64;
for (int i = 0; i < uc.length; i++) {
for (int j = 0; j < uc[i].length; j++) {
uc[i][j] = (char) x++;
System.out.print(uc[i][j] + " ");
System.out.println();
}
}
}
}
This prints the unicode but only in one column, I feel a bit silly here but could anyone give me a suggestion?
Thanks a lot.
Move the System.out.println(); outside the second for-loop and inside the first one, just after the for-loop:
for (int i = 0; i < uc.length; i++) {
for (int j = 0; j < uc[i].length; j++) {
uc[i][j] = (char) x++;
System.out.print(uc[i][j] + " ");
}
System.out.println();
}
I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}