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
Related
I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.
I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.
Here am finding the middle letter of each element of the array and making it upper case and merge it so that it'll give me a result like e:g- {bOy, inDia, apPle}
Following is the code am trying till now.
public class FindMiddle {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
System.out.println(c[j]);
}
newar[i] += c[j];
}
}
}
}
It's only giving me O D P.
I want them merged with the original elements like bOy inDia apPle.
that's because you print only the middle char (the println is inside the if statement)
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
System.out.println(c[j]);
}
I would suggest using StringBuilder.setCharAt
for (int i = 0; i < newar.length; i++) {
StringBuilder updateString = new StringBuilder(newar[i]);
int middleIndex = newar[i].length /2;
updateString.setCharAt(middleIndex, Character.toUpperCase(newar[i].charAt(middleIndex));
System.out.println(updateString);
}
you could use the charAt function of the String object and replace function
using the full String.length is not accurate when you will be accessing the middle index of the String since index are length - 1 (because it starts with 0) so you need to deduct 1 from the length and then divide it by half.
for(int i=0;i<newar.length;i++){
int index = (newar[i].length()-1)/2;
newar[i] = newar[i].replace(newar[i].charAt(index), Character.toUpperCase(newar[i].charAt(index)));
System.out.println(newar[i]);
}
output:
bOy
inDia
aPPle
Try this :
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
//System.out.print(c[j]); <--- you keep getting O D P because you
print them here
}
// newar[i] += c[j]; <-- here you just concat changed elements to newar
System.out.print(c[j]); <--- print the value of array none middle and middle one
}
if (i != newar.length-1) { <-- avoid printing , for last item
System.out.print(",");
}
}
output:
bOy,inDia,apPle
My explanations are as comment inside the code.
Note: when you are in a for loop, you are checking whether you ecnounter the middle character. if you encountered, you will make it uppercase other wise nothing is changed, and each character is printed out on the console.
import java.util.ArrayList;
public class Test
{
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
// System.out.println(c[j]);
// (1)
}
System.out.print(c[j]);
// (2)
newar[i] += c[j];
}
System.out.println();
// (3)
}
}
}
(1) - I got rid of this because it would only print out the uppercase letter. You had set the middle characters in all 3 words to uppercase, but, you need to print out the whole word, not just one letter.
(2) - You do, however, want to print out the whole word, which is what this line is doing. Instead of doing println, it only does print. Reason is because we are taking advantage of that for loop that is going through each character in the specific word to be able to print out each letter after we are done checking if it's the middle letter.
(3) - We have this line here because we want to be able to separate between words. I am not sure how you want these words separated so change this as you feel it's necessary, I just separated them so you could see.
There are a lot of things wrong with your code, so here is a simplified rewrite:
public static void main(String[] args) {
String s = "boy india apple";
String[] split = s.split( " " );
String[] toReturn = new String[split.length];
for (int i = 0; i < split.length;i++)
{
String word = split[i];
char[] chars = word.toCharArray();
chars[chars.length/2] = Character.toUpperCase( chars[chars.length/2] );
toReturn[i] = String.valueOf( chars );
}
System.out.println(Arrays.toString( toReturn ));
}
In order to correct your code you can start by removing the useless ArrayList and moving the System.out outside of the for loop. There are some other issues like you are appending the new result to the original so newar after this runs will look like {boybOy, indiainDia, appleapPle}.
EDIT:
For teaching purposes, here is your code modified so that it will work; however inefficient.
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
System.out.print("{");
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
}
System.out.print(c[j]);
}
newar[i] = String.valueOf(c);
if (i < newar.length - 1)
System.out.print(",");
}
System.out.println("}");
}
String temp = ""; //define temp string as "" (don't assign null)
for (int j = 0; j < c.length; j++) {
...
//newar[i] += c[j]; //don't append to existing String in array
temp += c[j];
newar[i] = temp;
}
//after replacement is done
//now can print replaced string in array by looping
for (String string : newar) {
System.out.println(string);
}
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);
}
}
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();
}
}
}