printing two different loops on the same line - java

hello everyone I can't figure out how to print these two statements on the same line.
for(int index = 1; index < word.length(); index++){
System.out.printf("\n%s", builder.charAt(index));
}
for(int index = word.length()-2; index >= 0; index--){
System.out.printf("\n%s%s",space ,backWards.charAt(index));
}
my objective is to give this method a word and it prints the rectangle, for example:
word = java
it will print:
java
a v
v a
avaj
please try to keep it as simple as possible because I'm still a beginner

The only way to print string vertically, is to loop through it's characters and print one of them on each line
String str = "JAVA";
System.out.println(str);
for(int i=1; i<str.length()-1; i++){
System.out.print(str.charAt(i));
for(int j=1; j<str.length()-1; j++){
System.out.print(' ');
}
System.out.println(str.charAt(str.length()-1-i));
}
for(int i=0; i<str.length(); i++){
System.out.print(str.charAt(str.length()-1-i));
}

Here is one way to do it:
String word = "java";
// print first line
System.out.println(word);
String spaces = getSpacesFor(word.length() - 2);
// print out middle lines
for(int i = 1; i < word.length() - 1; i ++) {
// first character is from the normal word order
String s = "" + word.charAt(i);
// add middle spaces
s += spaces;
// add last character which is backwards order
s += word.charAt(word.length() - i - 1);
// print out
System.out.println(s);
}
// print backwards word
for(int i = 0; i < word.length(); i ++) {
System.out.print(word.charAt(word.length() - i - 1));
}
getSpacesFor would be a method like:
public static String getSpacesFor(int num) {
String s = "";
for(int i = 0; i < num; i ++) {
s += " ";
}
return s;
}

Related

How to capitalize the common letters of two words?

I'm trying to capitalize the common letters of two words. Does anyone know why my code doesn't work?
It says:
Main.java:22: error: cannot find symbol
char character = words.charAt(i);
^
symbol: method charAt(int)
location: variable words of type String[]
The code is:
int word2;
int space_count = 0;
//get input
System.out.println ("Input two words: ");
int word = sameletters.nextInt();
String words[] = new String[word];
//find the begining of the second word
for(int i = 0, n = words.length; i<n; i++)
{
char character = words.charAt(i);
if(Character.isWhitespace(character))
{
word2 = i + 1;
space_count++;
}
}
//validate the input.
for(int i = 0, n = words.length; i<n; i++)
{
if(space_count != 1)
{
System.out.println ("MUST CONTAIN 2 WORDS\n");
break;
}
}
//loop for the first word
for (int i = 0, n = word2 - 1; i < n; i++)
{
//loop for the second word
for (int j = word2, x = words.length; j < x; j++)
{
//compare the letters
if(words[i] == words[j])
{
words[i] = words[i].toUpperCase();
words[j] = words[j].toUpperCase();
}
}
}
//print output
System.out.println ("\n" + words);
sameletters.close();
}
}

Triangle Word Pattern using Nested Loops in Java

For this assignment, after inputting any word, it will print it in a pattern shown below (in this case, the word is computer):
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Currently, my code is this:
String output = "";
for (int a = word.length()-1; a >= 1; a--)
{
for (int b = 0; b < word.length(); b++)
{
out.print(" ");
}
out.println(word.charAt(word.length()-1-a));
}
for (int c = 0; c < word.length(); c++)
{
out.print(word.charAt(word.length()-1-c));
}
out.print(word.substring(1));
return output + "\n";
The output for my code currently is:
C
O
M
P
U
T
E
RETUPMOCOMPUTER
Any advice or tips is much appreciated, thank you in advance!
The logic is simple, first try to create the last line, using reverse of StringBuilder. Then print each line from the first to the last line.
The last line case is simple.
From the first to the last line - 1, we only need to print those characters that has the distance equal 0, 1, 2 ... to the center of the last line.
public void printTriangle(String input) {
String tmp = input.substring(1);//Take the suffix
StringBuilder builder = new StringBuilder(tmp);
builder = builder.reverse().append(input);//Reverse, then append it
String line = builder.toString();//This is the last line
for(int i = 0; i < input.length(); i++){
for(int j = 0; j < line.length(); j++){
//Print the last line, or those that have distance equals i to the center of the last line
if(i + 1 == input.length() || Math.abs(j - line.length()/2) == i){
System.out.print(line.charAt(j));
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
Input
COMPUTER
Output
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Input
STACKOVERFLOW
Output
S
T T
A A
C C
K K
O O
V V
E E
R R
F F
L L
O O
WOLFREVOKCATSTACKOVERFLOW
You asked for nested loops, but there are a few other ways including padding it with spaces. If you are allowed to do that, you only need a single loop:
public static void printTriangle(String str){
int len = str.length()-1, idx = 1;
System.out.println(String.format("%"+(len+1)+"s", str.charAt(0)));
for(int x=0; x<str.length()-2; x++){
System.out.print(String.format("%"+(len--)+"s", str.charAt(idx)));
System.out.println(String.format("%"+(idx*2)+"s", str.charAt(idx++)));
}
System.out.println(new StringBuilder(str.substring(1)).reverse().toString() + str);
}
Output:
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Instead of doing a code that will magically work for every case, try using a code that addresses every case:
String someString = "COMPUTER";
switch(someString.length()) {
case 0: System.out.println();
break;
case 1: System.out.println(someString);
break;
default:
int _spaces_before_after = someString.length()-1;
int _spaces_middle = 0;
for(int i=0; i<someString.length(); i++){
if(i!=someString.length()-1){
if(i==0){
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.print(someString.charAt(0));
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.println();
_spaces_middle = 1;
}
else {
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.print(someString.charAt(i));
for(int j=0; j<_spaces_middle; j++)
System.out.print(" ");
System.out.print(someString.charAt(i));
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.println();
_spaces_middle+=2;
}
_spaces_before_after-=1;
}
else {
for(int j=someString.length()-1; j>=0; j--)
System.out.print(someString.charAt(j));
for(int j=1; j<someString.length(); j++)
System.out.print(someString.charAt(j));
}
}
break;
}
Suppose you have a string str of length n. You'll have a matrix of size n × 2n+1.
First, you need to define the center c of your triangle, which would be the position n
In your first line of the matrix, you draw only the first letter (str[0]) in the center and then go to the next line.
In the second line, you draw the second letter (str[1]) in the positions c-1 and c+1.
In the third line, you draw the third letter (str[2]) in the positions c-2 and c+2.
And so on.
The last line is the trickier. Starting from the center c, you have to draw the whole word str. From the center, you start writing your string forwards and backwards.
I've tried some implementation, it's really simple:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int n = str.length();
char[][] matrix = new char[n][2*n+1];
char[] chrArr = str.toCharArray();
// initializes the matrix with blank spaces
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*n+1; j++) {
matrix[i][j] = ' ';
}
}
// build the two sides of the triangle
for (int i = 0; i < n - 1; i++) {
matrix[i][n-i] = chrArr[i];
matrix[i][n+i] = chrArr[i];
}
// last line, build the base of the triangle
for (int i = 0; i < n; i++) {
matrix[n-1][n-i] = chrArr[i];
matrix[n-1][n+i] = chrArr[i];
}
// print
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*n+1; j++) {
System.out.print(matrix[i][j]);
}
System.out.print("\n");
}
Here is the sample code running in ideone.
You can try it with any string size.

Sorting characters inside String

I'm trying to sort the characters alphabetically in a String and when I run my code with the following example: hello, then I get: heeeeeeeeeheeeelheeellhee instead of ehllo. Could smb suggest me what I should fix in my code? Thanks in advance!
public static void main(String[] args)
{
String result = "";
Scanner kbd = new Scanner(System.in);
String input = kbd.nextLine();
char[] myArray = input.toCharArray();
for(int i = 0; i < myArray.length; i++)
for(int j = 0; j < myArray.length; j++)
{
if(myArray[i] > myArray[j])
{
char temp = myArray[j];
myArray[j] = myArray[i];
myArray[i] = temp;
result += myArray[i];
}
else
result += myArray[i];
}
System.out.println(result);
}
Why so complicated?
public String sortByChar(String s)
{
char[] cs = s.toCharArray();
Arrays.sort(cs);
return new String(cs);
}
On each iteration of your loop, you appending the character at i within the array to result, but the array is not sorted yet
The loop will perform n * (n - 1) loops, so, for a String of 5 characters, that's going to be 5 * (5 - 1) (or 20) iterations.
Instead, sort the array and then create a new String based on it's content...
String input = "hello";
char[] myArray = input.toCharArray();
for (int i = 0; i < myArray.length; i++) {
for (int j = 1; j < myArray.length; j++) {
if (myArray[i] > myArray[j]) {
char temp = myArray[j];
myArray[j] = myArray[i];
myArray[i] = temp;
}
}
}
System.out.println(new String(myArray));
Also note, for (int j = 0; j < myArray.length; j++) { is wrong and should be for (int j = 1; j < myArray.length; j++) {, otherwise you'll be comparing the same character at the same position, which isn't what you want to do...
A more "accurate" bubble sort might look something like...
for (int i = 0; i < (myArray.length - 1); i++) {
for (int j = 0; j < myArray.length - i - 1; j++) {
if (myArray[j] > myArray[j + 1]) {
char swap = myArray[j];
myArray[j] = myArray[j + 1];
myArray[j + 1] = swap;
}
}
}
You keep modifying result as you go. This is wrong: result collects a record of characters as you modify them, which is not what you want.
You should remove result += ... from your code, and use this after the loop:
String result = new String(myArray);

Getting each letter in a String only once

I'm writing a Java program for Horspool's algorithm, and am having a bit of trouble. I'm trying to create an array of chars that will hold each letter in a string, but I don't want duplicates of the letters. Right now this is my code:
public static void main(String[] args)
{
Scanner scanIn = new Scanner (System.in);
int count = 0;
int count2 = 0;
int inc = 0;
//The text to search for the phrase in
String t = "";
//The phrase/pattern to search for
String p = "";
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Harspool's Algorithm: ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" ");
System.out.println("Please enter the full text: ");
t = scanIn.nextLine();
System.out.println("Please enter the pattern to search for: ");
p = scanIn.nextLine();
char[] text = new char[t.length()];
char[] pattern = new char[p.length()];
char[] alphabet = new char[t.length()];
for (int i = 0; i < alphabet.length; i++)
{
alphabet[i] = ' ';
}
for (int i = 0; i < text.length; i++)
{
text[i] = t.charAt(i);
}
for (int i = 0; i < pattern.length; i++)
{
pattern[i] = p.charAt(i);
}
while (inc < text.length)
{
for (int j = 0; j < text.length; j++)
{
if (text[inc] != alphabet[j])
{
count++;
}
if (count == p.length() - 1 && count2 < text.length)
{
alphabet[count2] = text[inc];
count2++;
count = 0;
inc++;
}
}
}
for (int i = 0; i < alphabet.length; i++)
{
System.out.print(alphabet[i]);
}
}
I believe the problem is in the while loop, but I can't figure out what exactly is going wrong. Right now, it will print out the entire string passed in, when it should be printing each letter only once. Could someone please help?
Instead of counting the occurrences of each character, Use Set<Character>. A set contains unique elements and so you will not have duplicates that way.
You can also convert a Set to an array by doing mySet.toArray(new String[mySet.size()]); or just mySet.toArray(new String[0]);
Your code is not easy to read. You might consider using the following algorithm instead.
int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
if(ccount[ii]>0) System.out.printf("%c", ii);
}
EDIT - made sure ccount was initialized, and captured characters outside of range 0-255 with % operator.

java for loop pyramid

I want to create a loop with a string so that with each successive loop, the last and first characters from the previous line will not be displayed. I'm also trying to print the length of each loop next to each line. It will look like an upside-down pyramid.
I had this:
for(int scounter = fullName.length(); scounter > 0; scounter--)
for (String name : fullName)
for(int counter = 0; counter < fullName.length(); counter++)
System.out.println(scounter + "[ " + fullName.substring(0, fullName.length() counter)+ " ]");
It prints something like this:
24******
24****
24**
24*
Yet I'm looking for something similar to this:
7*******
5*****
4***
1*
String str = "*******";
for (int i = 0, l = str.length(); i <= l/2; i++) {
String line = str.substring(i, l - i);
System.out.printf("%" + (i + 1) + "d%s\n", line.length(), line);
}
This will print:
7*******
5*****
3***
1*
I'm assuming you meant 3 instead of 4 in your example, that is, that you want to decrement by 2.
I started working on this problem and found my solution to be slightly different from Joao's. Hope this helps!
public class pyramid
{
public static void main(String[] args)
{
for(int i=0, sz=args[0].length();i<sz; ++i,--sz)
{
System.out.printf("%"+(i+1)+"d%s\n", sz-i, args[0].substring(i,sz));
}
}
}
Invocation as per request:
java pyramid abcdefg
7abcdefg
5bcdef
3cde
1d
java pyramid abcdef
6abcdef
4bcde
2cd
Your example does not match the words of your question, so here's a method that behaves according to your words as I understand them:
public void pyramid(String text) {
int len = text.length();
int start = 0;
while (start < len) {
for (int i = 0; i < start; ++i) {
System.out.print(" ");
}
System.out.println(text.substring(start, len));
++start;
--len;
}
}
for(int i = 1; i<=4; i++) {
for(int k = 3;k>=i; k--){
System.out.print(" ");
}
for(int j = 1; j<=i; j++){
System.out.print("*");
}
for(int n = 2; n<=i;n++){
System.out.print("*");
}
System.out.println(" ");
}
for(int m = 1 ;m<=3; m++){
for(int o = 1;o<=m; o++){
System.out.print(" ");
}
for(int p = 3;p>=m;p--){
System.out.print("*");
}
for(int q = 2;q>=m;q--){
System.out.print("*");
}
System.out.println();
}
}
}

Categories

Resources