How to hide characters using for loops, respectively? - java

I want to basically hide characters following three constant dots (...), the pattern goes like this:
Inputs a phrase from the user and outputs the phrase followed by three dots (...), then the phrase minus one character followed by three dots (...), then the phrase minus two characters followed by the dots, and so on until only one dot is left.
Note: This has to be done using nested for loops only
Sample input
1
disappear
Expected output:
disappear...
disappea...
disappe...
disapp...
disap...
disa...
dis...
di...
d...
...
..
.
This is my attempt:
Problem: I am unable to make it so the phrase decreases each time (minus 1 each time)
I tried using the charAt(); method, but it wouldn't work, I am sure that you would need a for loop separate for each of the dots or a whole set of dots, in this case.
import java.util.Scanner;
public class Dissappear{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
String phrase = keyboard.next();
if (option == 1){
for (int x = 0; x <= phrase.length(); x++){
System.out.print(phrase + "...");
for (int y = 0; y <= phrase.length(); y++){
char n = phrase.charAt(y);
System.out.print(n+"...");
}
}
}
}
}

This is how I got it to work:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
System.out.println(word.substring(0, originalLength - i) + "...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
Without substring:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
for(int j = 0; j < originalLength - i; j++) {
System.out.print(word.charAt(j));
}
System.out.println("...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}

You can do it with StringBuilder:
StringBuilder stringBuilder = new StringBuilder(str);
System.out.println(str + "...");
for (int i = 0; i < length; i++) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
System.out.println(stringBuilder.toString() + "...");
if (i == length - 1) {
for (int j = 0; j < 2; j++) {
for (int k = j; k < 2; k++) {
System.out.print(".");
}
System.out.println();
}
}

Ok! Nested for loops. But the outer one is only included to meet the requirement. Probably not in the spirit of the assignment though. Just keep decrementing k until it is zero and then latch it there until the StringBuilder length is 0 and the inner loop terminates.
StringBuilder sb = new StringBuilder("disappear...");
for (;;) {
for (int k = sb.length() - 4; sb.length() > 0;) {
System.out.println(sb);
sb.delete(k, k + 1);
k = k > 0 ? --k : 0;
}
break;
}

Related

Count and print even flowers

We have n number of flowers that can be black or white. We have m number of months. At the end of each month, if the number of white flowers is even, we print B for the number of roses that are even, and print F for the rest of the characters.For example:(W=white,B=black)
input:3(n) 2(m)
WBW
BBW
output:FBB
My code just work well just for this example and dont give true answer for other examples.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of flowers: ");
int flower = input.nextInt();
System.out.println("Enter number of months : ");
int month = input.nextInt();
String[] arr = new String[month];
char ch = ' ';
int count = 0;
for (int j = 0; j < month; j++)
arr[j] = input.next();
for (int i = 0; i < month; i++) {
char[] s = arr[i].toCharArray();
for (int j = 0; j < flower; j++) {
if (s[j] == 'W') {
count++;
}
}
if (count % 2 == 0) {
for (int k = 0; k < flower - count; k++) {
System.out.print('F');
}
for (int b = 1; b <= count; b++) {
System.out.print('B');
}
}
}
}
}
In your for loop
for (int j = 0; j < flower; j++) {
if (s[j] == 'W') {
count++;
}
}
We must remember what s is referring to, char[] s = arr[i].toCharArray(); which means that s will not have a length of flower but will have a length of arr[i].length() or s.length.
So if you change the for loop to use that as its control, it should solve the index out of bounds exception that you get.
The fix would look like:
for (int j = 0; j < s.length; j++) {
if (s[j] == 'W') {
count++;
}
}

printing v shape in java

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);
}
}

Java: Printing two dimensional array in grid format

I'm having difficulty figuring out the code to print a two dimensional array in grid format.
public class TwoDim {
public static void main (String[] args) {
int[][] ExampleArray = new int [3][2];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
ExampleArray[i][j] = i * j;
System.out.println(j);
}
System.out.println(i);
}
}
}
System.out.println(s) prints s, then prints a line return character. So if you want multiple print calls to end up on the same line, you should use System.out.print(s) instead.
Additionally, you can use System.out.println() (with no argument) to print nothing, but move to the next line. Bringing all of that together:
public class TwoDim {
public static void main (String[] args) {
int[][] ExampleArray = new int [3][2];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 2; j++){
ExampleArray[i][j] = i * j;
System.out.print(j + " ");
}
System.out.println();
}
}
}
When you use System.out.println(...);, it prints a newline char ('\n') after the string you intended to print. This should only happen if your line is over (i.e., outside the innest for statement). So, your for loops should be:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
ExampleArray[i][j] = i * j;
System.out.print(ExampleArray[i][j] + ' '); //You can replace ' ' by '\t', if
//you want a tab instead of a space
}
System.out.println("");
}
Hope that helps.

Print an Ordered 2D Array - Single Line

I am trying to write a nested for loop that will print out the values of the following code in a specific order:
public static void main(String[] args) {
int[][] array2d = new int[3][5];
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
array2d[i][j] = (i * array2d[0].length) + j + 1;
}
}
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 2; y++) {
System.out.println(array2d[y][x]);
}
}
}
}
The current array prints the way I want it, but each printout on a separate line.
I want the output (on a single line) to be this:
1 6 11 2 7 12 3 8 13 4 9 14 5 10 15
Thanks for the help.
You can use System.out.print instead:
System.out.print(array2d[y][x] + " ");
Replace println with print and it should work
String s = "";
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[i].length; j++) {
s += array2d[i][j] + " ";
}
}
System.out.println(s);
public static void main(String[] args) {
int[][] array2d = new int[3][5];
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
array2d[i][j] = (i * array2d[0].length) + j + 1;
}
}
StringBuilder builder = new StringBuilder();
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 2; y++) {
builder.append(array2d[y][x]);
if(!(x == 4 && y == 2)){
builder.append(" ");
}
}
}
System.out.println(builder.toString());
}
You basically had it right, except for changing the println to be print and formatting the string how you want. I changed it a little to show how the StringBuilder works. Whenever possible I use a StringBuilder because it is more convenient.

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}

Categories