Writing a word in a rhombus/diamond shape in Java - java

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

Related

Read, store and print user input

I have to get 4 user input from the user one by one on the next line like
Sample input:
65
66
67
68
Then the output has to displayed like
You have entered:
65-A
66-B
67-C
68-D
the program i have return is this:
import java.util.Scanner;
public class ASCII {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the digits:");
int no = sc.nextInt();
char ch= (char) no;
System.out.println(no + "-" + ch);
}
}
the one thing could not get is the 4 input for the user could someone help with that
You should loop it;
int[] numbers = new int[4];
for (int i = 0; i < 4; i++) {
numbers[i] = sc.nextInt();
}
numbers[n-1] will return number in your case 0 < n < 5;
and you can create another loop to print them.
chars[] characters = {'A','B','C','D'};
for (int i = 0; i < 4; i++) {
System.out.println(Integer.toString(numbers[i]) + characters[i]);
}
for loops works like;
for (DoAtStart; Condition; DoAtEndOfARepeat) {
}
This would work for you :
public class ASCII {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the digits:");
int array[]=new int[4];
for(int i=0; i<4;i++) {
int no = sc.nextInt();
array[i]=no;
}
System.out.println("You have entered:");
for(int j=0;j<array.length;j++) {
char ch= (char) array[j];
System.out.println(ch+"-"+array[j]);
}
}
}

I am generating a series of numbers delimited with space but I want to remove the space at end

I am generating the series of numbers using for loop, delimited with space but I want to remove trailing space at last. Unable to use trim() for the output.
import java.util.*;
public class Main {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
int str = s.nextInt();
for(int i=1; i<=str; i++) {
System.out.printf("%d", i);
System.out.print(" ");
}
}
}
1 2 3 4 5(space here)
but I want output without the space after 5.
int i;
for(i = 1; i < str.length(); i++) {
System.out.print(i + " ");
}
System.out.println(i);
Do an if test inside the for-loop like this
if (i == str) {
System.out.printf("%d", i);
} else {
System.out.printf("%d", i);
System.out.print(" ");
}
The logic you want is to print a space behind every number, except for the last number. You should have this conditional logic in your code somewhere. Like,
if (i < str)
System.out.print(" ");
Note: it's very confusing to call a variable str if it contains a number; everyone will assume that it's a String instead of a number. You could change code to something like this:
public static void main(String [] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for(int i = 1; i <= n; i++) {
System.out.print(i);
if (i < n)
System.out.print(" ");
}
}

How to print a distinct string in this pattern in Java?

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.

Java: Printing trailing spaces

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.

Finding all uppercase letters of a string in java

So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.
for(int y = 0; y <= z; y++){
should be
for(int y = 0; y < z; y++){
Remember array index starts from ZERO.
String length returns
the number of 16-bit Unicode characters in the string
Because loop started from ZERO, loop should terminate at length-1.
The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length
Most iterating for loops should be in the form:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
It's the same with a string.
Perhaps a cleaner way would be:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.
With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter(Character::isUpperCase)
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
Inspired by:
Adam Bien - Streaming A String
Simplest way to print anIntStream as a String
Try this...
Method:
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
Usage:
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}
Hi one of the easy step to find uppercase char in a given string...
Program
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
import java.util.Scanner;
public class P43 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
String x = in.next();
x.chars().filter(c -> Character.isUpperCase(c))
.forEach(c -> System.out.print((char) c + " "));
}
}
Sample input:
saveChangesInTheEditor
Sample output:
C I T E
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}
The simplest way I know is to use regex replacement.
isUp = x.replaceAll("[^A-Z]", "");
In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}
public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}

Categories

Resources