I am trying to make a program in java which would give a pattern for an inputted string as follows
C O M P U T E R
O E
M T
P U
U P
T M
E O
R E T U P M O C
Here is my program code
import java.util.Scanner;
class pandapattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a word : ");
String s=sc.nextLine();
System.out.println();
int l=s.length();
for(int i=0;i<+l;i++)
{
System.out.print(s.charAt(i)+" ");
}
char[][] frwd = new char[l][1];
char[][] bcwd = new char[l][1];
for(int f=1;f<l;f++)
{
frwd[f][0]=s.charAt(f);
}
for(int b=l-2;b>=0;b--)
{
bcwd[b][0]=s.charAt(b);
}
for(int p=1;p<l;p++)
{
System.out.print("\n"+frwd[p][0]);
}
for(int p1=l-1;p1>=0;p1--)
{
System.out.print(bcwd[p1][0]+" ");
}
}
}
I get this pattern:
C O M P U T E R
O
M
P
U
T
E
R E T U P M O C
How would I get the whole pattern printed out?
Please help me to figure it out.
You onle need one char[] array, not more.
The trick is to take the problem "row-by-row".
See below:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter word for Panda Pattern: ");
String word = scanner.nextLine();
String wspace = " ";
//convert user input from String to char[]
char[] wordLetters = word.toCharArray();
//define array's length, for ease of reference
int length = wordLetters.length;
//initially print the sentence in a horizontal line
for (char wordLetter : wordLetters) {
System.out.print(wordLetter + wspace);
}
//insert new line to start printing for the pattern
System.out.print("\n");
/*A for loop that will print the left-most letters vertically
We start the loop from 1, because the first letter was already printed*/
for(int i=1; i<length; i++){
System.out.print(wordLetters[i]);
/*now we have an inner loop that will print the spaces and the
rest of the letters in reverse order*/
for(int j=1; j<length; j++){
//conditional for IF we are at final line
if(i == length-1 && j != length-1)
System.out.print(wspace + wordLetters[i-j]);
//conditional for printing right-most letters
else if(j == length-1) {
System.out.print(wspace + wordLetters[j-i]+"\n");
}
//THIS WILL PRINT 2 WHITE-SPACES.
else
System.out.print(wspace + wspace);
}
}
}
Why didn't I need a second array ?
Since this pattern requires only one word, then printing in reverse, means that there is still the same amount of letters to process, so any additional arrays would have the same length.
Ergo, we can omit creating new arrays altogether!
Why not manipulate the power that for-loops & arrays give us?
Firstly, for this task you need one-dimension arrays frwd and bcwr
Secondly, you fill array bcwd in the same way as frwd.
Rewritten part of your method correctly for the task:
int length = s.length();
//printing first line
for (int i = 0; i < +length; i++) {
System.out.print(s.charAt(i) + " ");
}
System.out.println();
//filling arrays
char[] frwd = new char[length];
char[] bcwd = new char[length];
for (int f = 1; f < length; f++) {
frwd[f] = s.charAt(f);
}
for (int b = 0; b < length; b++) {
bcwd[b] = s.charAt(length-1 - b);
}
for (int p = 1; p < length-1; p++) {
System.out.print(frwd[p]);
//filling spaces to line by length of input string
for (int p3 = 1; p3 < frwd.length-1; p3++) {
System.out.print(" " + " ");
}
System.out.print(" " + bcwd[p]);
System.out.println();
}
for (int p = 0; p <= length - 1; p++) {
System.out.print(bcwd[p] + " ");
}
System.out.println();
And you can use just input string without extra char arrays. Just get characters from string (s.charAt(i)) in straight and backwar loops.
Related
I have to write a program that asks a word and then prints it in a rhombus/diamond shape, like this:
Word: Hello
H
He
Hel
Hell
Hello
ello
llo
lo
o
I tried something but I really could use some help if someone could, I tried something like this:
import java.util.Scanner;
public class Rhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Word: ");
String word = sc.nextLine();
int wordLength = word.length();
for (int i = 0; i < wordLength; i++) {
System.out.println(word.substring(0, i));
}
}
}
Here you are:
public static void main(String[] args) {
printRhombusText("yolobird");
}
public static void printRhombusText(String s) {
// top part
for (int i = 1; i <= s.length(); ++i) {
System.out.println(s.substring(0, i));
}
// bottom part
for (int i = 1; i <= s.length(); ++i) {
// print out the space
for (int y = i; y > 0; --y) {
System.out.print(" ");
}
System.out.println(s.substring(i));
}
}
output:
y
yo
yol
yolo
yolob
yolobi
yolobir
yolobird
olobird
lobird
obird
bird
ird
rd
d
Want to add user input? Here:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Input your text: ");
String input = scanner.nextLine();
printRhombusText(input);
scanner.reset();
System.out.print("You want to do one more? (y/n): ");
} while (scanner.nextLine().trim().equals("y"));
}
output:
Input your text: kiet
k
ki
kie
kiet
iet
et
t
You want to do one more? (y/n): y
Input your text: ahihi
a
ah
ahi
ahih
ahihi
hihi
ihi
hi
i
You want to do one more? (y/n): n
You can use this code to output a word in a rhombus shape.
Try it online!
public static void main(String[] args) {
String str = "RhOmBuS";
int h = str.length();
// two parts: negative and positive, i.e.
// upper increasing and lower decreasing
for (int i = 1 - h; i < h; i++) {
// white space padding for the positive part
for (int j = 0; j < i; j++) System.out.print(" ");
// negative part: str.substring(0, h + i);
// positive part: str.substring(i, h);
String sub = str.substring(Math.max(0, i), Math.min(h, h + i));
// output the line
System.out.println(sub);
}
}
Output:
R
Rh
RhO
RhOm
RhOmB
RhOmBu
RhOmBuS
hOmBuS
OmBuS
mBuS
BuS
uS
S
See also: Print a rhombus pattern from user input
I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:
4
1 4 3 2
The code will need to reverse the second input to the following:
2 3 4 1
My solution is as follow:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
System.out.print(arr[reverse_i]);
if(reverse_i != 0){System.out.print(" ");}
}
}
My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.
The easy way to reverse a string is using the StringBuilder class:
One option is to remove the spaces at the end of the string eg. remove last char
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
Another option is to check whether you are at the last arr_i of your loop.
If so, then don't add a space
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
if (arr_i != 3
sb.append(" ");
}
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
First reverse the array and then print it with a for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++)
{
arr[arr_i] = in.nextInt();
}
for(int i = 0; i < arr.length / 2; i++)
{
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
It is all about output formatting. You may use this examples and become familiar with all possible approaches.
Your code can be improved in next two ways :
1) Use \t instead of Empty Space (\t is a tabulation)
2) Create a constant with output format like this private static final String output = "%d " and use it in output line like this : String.format(output, number) where number is your number that should be printed.
I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}
I need to display only one type of the vowel that have check from a string
but it keeps on display the repeated vowel.
Input: I am in you all day and wathc you over.
Output:
Vowels : I a o u e
Consonants : m n y l d w t h c r
this means it will display the vowel that was used in the sentence.
the same goes for the consonant
import java.util.Scanner;
public class aaaa {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
System.out.println ("Enter a string:");
String s = input.nextLine();
char[] sChars = s.toCharArray();
char[] vowels = {'a','e','i','o','u','A','E','I','O','U'};
char[] consonant = {'b','c','d','f','g','h','k','j','l','m','n','p','q','r','s','t','x','v','w','y','z'};
for (int j = 0 ; j < sChars.length ; j++ ) {
for (int i = 0; i < vowels.length ; i++ ) {
if ( sChars[j] == vowels[i]) {
System.out.print(vowels[i]+ " ");
}
}
}
System.out.print("\n");
for(int m = 0 ; m < sChars.length ; m++){
for(int n = 0; n < consonant.length ; n++){
if ( sChars[m] == consonant[n]){
System.out.print(consonant[n]+" ");
}
}
}
}
}
Try this:
System.out.println("Vowels: " + s.toLowerCase().replaceAll("[^aeiou]|(.)(?=.*\\1)", "")
+ "\nConsonants: " + s.toLowerCase().replaceAll("[aeiou]|(.)(?=.*\\1)", ""));
This gets the entire job done in one line by using regex to select the characters of interest to delete.
FYI, the regex [aeiou]|(.)(?=.*\1) means "any vowel, or any character that does not reappear". The first match of an alternation stops there, that's why I didn't need to code the character class for consonants in the right hand side - the dot will only match for non-vowels.
A similar approach is used for printing vowels, except it's a negated character class.
There are way more efficient ways of doing this, but I will try to change as little of your solution as possible.
Keep track of the letters already printed, and don't print them a second time:
char[] vowels = {'A','E','I','O','U'};
char[] consonant = {'B','C','D','F','G','H','K','J','L','M','N','P','Q','R','S','T','X','V','W','Y','Z'};
// create a collection to store the letters already used
List<Character> lettersUsed = new ArrayList<Character>();
for (int j = 0 ; j < sChars.length ; j++ ) {
for (int i = 0; i < vowels.length ; i++ ) {
if ( Character.toUpperCase(sChars[j]) == vowels[i]) {
// if the collection of used letters does not contain this one
if(!lettersUsed.contains(Character.toUpperCase(sChars[j]))) {
System.out.print(sChars[j]+ " ");
// add this letter to the collection of letters used
lettersUsed.add(Character.toUpperCase(sChars[j]));
}
// now that you've found a match, break out of the inner loop
break;
}
}
}
System.out.print("\n");
for(int m = 0 ; m < sChars.length ; m++){
for(int n = 0; n < consonant.length ; n++){
if ( Character.toUpperCase(sChars[m]) == consonant[n]){
// if the collection of used letters does not contain this one
if(!lettersUsed.contains(Character.toUpperCase(sChars[m]))) {
System.out.print(sChars[m]+" ");
// add this letter to the collection of letters used
lettersUsed.add(Character.toUpperCase(sChars[m]));
}
// now that you've found a match, break out of the inner loop
break;
}
}
}
The program supposed to ask the user to enter a string then the program will reverse it and display it, but the code only return the first letter
import java.util.*;
public class ReverseString {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
int x = s.length();
char c = ' ';
for(int i=x-1; i>=0;i--){
c = s.charAt(i);
}
System.out.print("The reverse of String " + s + " is ");
System.out.print(c);
}
}
Output:
Enter a String: Welcome
The reverse of String Welcome is W
You're overwriting value of c in each iteration, change it to string and add to it in the loop
String c = "";
for(int i=x-1; i>=0;i--){
c += s.charAt(i);
}
Change char c = ' '; to String reverse=""; and append the character to it for each iteration.
The problem in your code is char c can hold only one character at a time.
Do like this
String reverse ="";
for(int i=s.length()-1; i>=0;i--){
reverse += s.charAt(i);
}
System.out.print(reverse);
A character is one letter; not a string.... the easiest way to do this, would be to use a StringBuilder like so -
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
// int x = s.length();
// char c = ' ';
// for (int i = x - 1; i >= 0; i--) {
// c = s.charAt(i);
//}
StringBuilder c = new StringBuilder(s);
c = c.reverse();
System.out.print("The reverse of String " + s + " is ");
System.out.print(c);
}
Or, if you want to use your current approach you can (by printing one character at time) like this -
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = scan.next();
System.out.print("The reverse of String " + s + " is ");
int x = s.length();
for (int i = x - 1; i >= 0; i--) {
char c = s.charAt(i);
System.out.print(c);
}
System.out.println();
}
If you want to make laugh your teacher (or maybe not) ;)
org.apache.commons.lang.StringUtils.reverse(s)
or without lib:
new StringBuffer(s).reverse().toString();
More efficient approach:
char[] strArray = s.toCharArray();
int len = strArray.length;
int max = (int)Math.ceil(len / 2.0);
char t;
for (int i = 0; i < max; ++i) {
t = strArray[i];
strArray[i] = strArray[len - i - 1];
strArray[len - i - 1] = t;
}
System.out.println(String.valueOf(strArray));