Printing asterisks using for loops in java - java

In python, to print
******
*****
****
***
**
*
*
**
***
****
*****
******
We would code the following:
for e in range (11,0,-1):
print((11-e) * ' ' + e * '*')
print ('')
for g in range (11,0,-1):
print(g * ' ' + (11-g) * '*')
My question is, can this be done in Java as well?
Java doesn't let you multiply a string (int) times, e.g. 4 * " ", so how can we implement this in java?

It wouldn't be a concise:
// top half..
for (int i=11;i>0;i--){
for (int a=0;a<11-i;a++){
System.out.print(' ');
}
for (int b=0;b<i;b++){
System.out.print('*');
}
System.out.println();
}

public class Loops {
public static void main(String[] args) {
//print first half
for(int i = 0; i < 6; i++) {
printChar(' ', i);
printChar('*', 6-i);
System.out.println();
}
//print second half
for(int i = 0; i <= 6; i++) {
printChar(' ', 6-i);
printChar('*', i);
System.out.println();
}
System.out.println();
}
//helper function to print a char n specific times
private static void printChar(char ch, int n) {
for(int i = 0; i < n; i++) {
System.out.print(ch);
}
}
}

To run through a string multiple times in Java, you can use a for loop.
for(int i = 0; i < yournum; i++){
System.out.print(" ");
}
yournum is the number of spaces you want

IntStream.range(0, 6).forEach(i -> {
IntStream.range(0, i)
.forEach(t -> System.out.print(" "));
IntStream.range(0, 6 - i)
.forEach(t -> System.out.print("*"));
System.out.println();
});
In Java8 you can use Stream to do the samething. Use IntStream to range and println

If you are open to using: Commons Lang StringUtils ...
using Commons Lang StringUtils.repeat() can help you repeat a string...
as an example:
StringUtils.repeat("*", 3) //produces ***

Here is a Core Java solution which can generate the entire output using a single for loop:
String before = "", after = "";
for (int i=0; i < 6; ++i) {
String starRepeat = String.format("%0" + (6-i) + "d", 0).replace("0", "*");
String spaceRepeat = (i>0) ? String.format("%0" + i + "d", 0).replace("0", " ") : "";
String line = spaceRepeat + starRepeat;
if (i == 0) {
before = line;
after = line;
}
else {
before = before + "\n" + line;
after = line + "\n" + after;
}
}
System.out.println(before + "\n\n" + after);
Output:
******
*****
****
***
**
*
*
**
***
****
*****
******

You can add the message you want to print on a String, then print out the string value by System.out.println(message);

Related

Two name combination using for loop in java

What I want is that asks the user to enter three (3) first names then display the following:
All the possible two-name combinations. For example I will input Mike Tyler Bryle
Mike Tyler Mike Bryle Tyler Mike Tyler Bryle Bryle Mike Bryle Tyler
Here is my code
import java.io.*;
import java.util.*;
public class Javacomprog{
public static void main(String[] args) {
//GET THE NAME FIRST
String name_1, name_2, name_3;
String prints =" ";
//STORING THE 3 NAMES
String[] a_names = new String[3];
//COMBINATION NAME
String[] c_names = new String[3];
Scanner sc = new Scanner(System.in);
//STORE IN ARRAY THE USER INPUT NAMES
System.out.println("Enter three first names:");
for(int i = 0; i < a_names.length; i++){
a_names[i] = sc.nextLine();
}
// STORE THE NAME COMBINATION
for(int j = 0; j < a_names.length; j++){
int a = 0;
//CHECK IF IT IS A REPEATED NAME USING EQUAL IGNORECASE
if(a_names[a].equalsIgnoreCase(a_names[j]) == true){
a++;
}
c_names[j] = a_names[a]+ " " + a_names[j];
}
//PRINT NAME COMBINATION
for(int l = 0; l < c_names.length; l++){
System.out.println(c_names[l] + " ");
}
}
}
Can you explain how do I do the name combination using for loop thank you.
You can do the combinations using nested for loops based on how many combinations you want to find. In this case, you want pairs so two loops (an outer and inner) will be sufficient.
String[] names = {"Mike", "Tyler", "Bryle"};
List<String> combinations = new ArrayList<>();
for(int i = 0; i < names.length - 1; i++) {
for(int j = i + 1; j < names.length; j++) {
combinations.add(names[i] + " " + names[j]);
combinations.add(names[j] + " " + names[i]);
}
}
for(String name : combinations)
System.out.println(name);
Solution
You can use two for-loops, both corresponding at the indice to have the same name.
We compare i == j in the inner loop, these are the same names.
If it is not equal than we will print the name.
Code:
String[] a_name = {"Max", " Moritz"};
for (int i = 0; i < a_name.length ; i++) {
for (int j = 0; j < a_name.length; j++) {
if(i != j){
System.out.println(a_name[i] + " " + a_name[j]);
}
}
}

Java Vowel Counter Alternative Method

I'm writing a simple vowel-counter and was wondering if there's a cleaner alternative (possibly a loop?) to replace all of the else if's when comparing s to the various vowels.
I can't think of a simple way to do this effectively as the number of each vowel must be shown individually. It would be very simple if it was just a total vowel count.
I'm quite new to Java so I don't know what can be used to clean this up. If this is the best option, then I am contempt -- but I love cleaning up code where it can be!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int A = 0, E = 0, I = 0, O = 0, U = 0;
System.out.print("Type a single word > ");
String word = input.next();
for (int i = 0; i < word.length(); i++) {
String s = word.substring(i, i + 1);
if (s.equalsIgnoreCase("A")) { A++; }
else if (s.equalsIgnoreCase("E")) { E++; }
else if (s.equalsIgnoreCase("I")) { I++; }
else if (s.equalsIgnoreCase("O")) { O++; }
else if (s.equalsIgnoreCase("U")) { U++; }
}
int total = A + E + I + O + U;
System.out.println("\n'" + word + "' has...\n" + A + " A's\n" + E + " E's\n" + I + " I's\n" + O + " O's\n" + U + " U's\nTotal vowels: " + total + "\n");
input.close();
}
}
Input:
Coding
Output:
'Coding' has...
0 A's
0 E's
1 I's
1 O's
0 U's
Total vowels: 2
Here is a less repetitive way to code it, using an int array for the counts, and a string holding the sequence of vowels.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Type a single word > ");
String word = input.next();
String vowels = "AEIOU";
int[] counts = new int[vowels.length()];
int total = 0;
for (int i = 0; i < word.length(); i++) {
int index = vowels.indexOf(Character.toUpperCase(word.charAt(i)));
if (index >= 0) {
++counts[index];
++total;
}
}
System.out.printf("%n'%s' has...%n", word);
for (int i = 0; i < counts.length; ++i) {
System.out.printf("%s %s's%n", counts[i], vowels.charAt(i));
}
System.out.printf("Total vowels: %s%n", total);
}
}
Output:
Type a single word > Coding
'Coding' has...
0 A's
0 E's
1 I's
1 O's
0 U's
Total vowels: 2
You could avoid a lot of repetition by using a Map that associates vowels (keys) to their frequencies within the word passed at runtime (values).
It is worth noting that a LinkedHashMap is used in the below example as to preserve the insertion order of keys for printing at the end of the program - as would not be the case with a HashMap.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Define Map to map vowels to frequencies
Map<Character, Integer> vowels = new LinkedHashMap<Character, Integer>();
vowels.put('A', 0);
vowels.put('E', 0);
vowels.put('I', 0);
vowels.put('O', 0);
vowels.put('U', 0);
// Get input from user
System.out.print("Type a single word > ");
String word = input.next();
// Iterate across word
for (int i = 0; i < word.length(); i++) {
String c = word.substring(i, i+1); // Get current char
for (Character key : vowels.keySet()) { // Iterate across vowels
if (c.equalsIgnoreCase(key.toString())) {
vowels.put(key, vowels.get(key)+1); // Increment vowel frequency if matched
break; // Break inner loop and move to next char in word
}
}
// Sum total
int total = 0;
for (Character key : vowels.keySet()) {
total += vowels.get(key);
}
// Print results to console
System.out.println("\'" + word + "\'" + " has...");
for (Character key : vowels.keySet()) {
System.out.println(vowels.get(key) + " " + key + "\'s");
}
System.out.println("Total vowels: " + total);
input.close();
}
}
}

How to remove one charachter from a string

With the scanner I want to read the index of a char and then remove it from the string. There is only one problem: If the char comes multiple times in the string, .replace() removes all of them.
For example I want to get the index of first 't' from the String "Texty text" and then remove only that 't'. Then I want to get index of second 't' and then remove it.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String text = "Texty text";
Scanner sc = new Scanner(System.in);
int f = 0;
int x = 0;
while(f<1){
char c = sc.next().charAt(0);
for(int i = 0; i<text.length();i++){
if(text.charAt(i)==c){
System.out.println(x);
x++;
}
else{
x++;
}
}
}
System.out.println(text);
}
}
You could use replaceFirst:
System.out.println(text.replaceFirst("t", ""));
Probably you are looking for something like the following:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String text = "Texty text";
String copy = text;
Scanner sc = new Scanner(System.in);
while (true) {
text = copy;
System.out.print("Enter a character from '" + text + "': ");
char c = sc.next().charAt(0);
for (int i = 0; i < text.length(); i++) {
if (Character.toUpperCase(text.charAt(i)) == Character.toUpperCase(c)) {
System.out.println(c + " was found at " + i);
text = text.substring(0, i) + "%" + text.substring(i + 1);
System.out.println("After replacing " + c + " with % at " + i + ": " + text);
}
}
}
}
}
A sample run:
Enter a character from 'Texty text': x
x was found at 2
After replacing x with % at 2: Te%ty text
x was found at 8
After replacing x with % at 8: Te%ty te%t
Enter a character from 'Texty text': t
t was found at 0
After replacing t with % at 0: %exty text
t was found at 3
After replacing t with % at 3: %ex%y text
t was found at 6
After replacing t with % at 6: %ex%y %ext
t was found at 9
After replacing t with % at 9: %ex%y %ex%
Enter a character from 'Texty text':
Try using txt.substring(x,y)
x = usually 0 , but x is first start index
y = this is what you want to delete for example for the last word of string write this code:
txt.substring(0, txt.length() - 1)
Since you are specifying indices, it is possible that you may want to replace the second of a particular character. This does just that by ignoring the ones before it. This returns an Optional<String> to encase the result. Exceptions are thrown for appropriate situations.
public static void main(String[] args) {
// Replace the first i
Optional<String> opt = replace("This is a testi", 1, "i", "z");
// Replace the second i (and so on).
System.out.println(opt.get());
opt = replace("This is a testi", 2, "i", "z");
System.out.println(opt.get());
opt = replace("This is a testi", 3, "i", "z");
System.out.println(opt.get());
opt = replace("This is a testi", 4, "i", "z");
System.out.println(opt.get());
}
public static Optional<String> replace(String str, int occurrence, String find, String repl) {
if (occurrence == 0) {
throw new IllegalArgumentException("occurrence <= 0");
}
int i = -1;
String strCopy = str;
while (occurrence-- > 0) {
i = str.indexOf(find, i+1);
if (i < 0) {
throw new IllegalStateException("insufficient occurrences of '" + find + "'");
}
}
str = str.substring(0,i);
return Optional.of(str + strCopy.substring(i).replaceFirst(find, repl));
}

How would format this in a single while loop so that it would print as four columns?

I need to make this into four separate columns
public class Lab7aCelsiustoFahrenheit
{
public static void main(String[] args)
{
//variables
double orig = -40.0;
double cels = orig;
double fahr = cels;
final int MAX_TEMP = -1;
//loop that prints asingle column on celsius to F conversions
while(cels <= MAX_TEMP)
{
System.out.println(cels + "C " + "is " + fahr + "F" + "\t");
cels++;
fahr = (((9.0 * cels) + 160) / 5);
}
}
}
You can make a linebreak after 4 entries, in counting how many items u wrote and then start in the next line.
Also to have each "cell" below the other you should use System.out.printf for writing the entry to format the double-values
If you really want to do this in a single while-loop, a possibilty would be:
int column = 1;
while(cels <= MAX_TEMP) {
fahr = (((9.0 * cels) + 160) / 5);
System.out.printf("%8.2fC is %8.2fF" + "\t", cels, fahr);
cels++;
column++;
if(column > 4) {
column = 1;
System.out.println();
}
}
I think you should also do the calculation before System.out.printf(...)

Printing Diamond Pattern in Correct Format in Java using Recursion

My program reads in values from a file and uses a recursive method to print patterns of asterisks based on those values. I'm just having a problem getting everything to line up properly.
The output is supposed to look like this:
*
* *
* * *
* *
*
Regarding the format of the output, the directions are:
"Note that the pattern is aligned symmetrically (vertically) about the center line. The pattern should be aligned symmetrically on each line (horizontally) as well- hint: use the line value to help space."
But my output looks like this:
*
* *
* * *
* *
*
The code I'm using to get this pattern:
public static void makePattern(int thisRow, int num) {
if(thisRow >= num) {
for(int i = 0; i < num; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
}
else {
for(int i = 0; i < thisRow; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
makePattern(thisRow + 1, num);
for(int i = 0; i < thisRow; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
}
}
Also my main method:
import java.util.Scanner;
import java.io.*;
public class Program3 {
public static void main(String[] args) throws Exception {
int num = 0;
int thisRow = 1;
java.io.File file = new java.io.File("../instr/prog3.dat");
Scanner fin = new Scanner(file);
while(fin.hasNext()) {
num = fin.nextInt();
if(num >=0 && num <= 25)
makePattern(thisRow, num);
System.out.println();
}
fin.close();
}
Any suggestions on how to edit my code to make my output appear like the example pattern I included?
Let's analyse the output first!!
First step is to analyse the output
Conclusions:
The total number of characters on every line is always n (=3)
Number of Spaces has the following pattern:
1st line 3 - 1 spaces
2nd line 3 - 2 spaces
3rd line 3 - 3 spaces
4th line 4 - 3 spaces
5th line 5 - 3 spaces
So
if(num < thisRow) {
numberOfSpaces = thisRow - num;
} else {
numberOfSpaces = num - thisRow;
}
Number of Stars is always [n - the number of spaces]
So
int numberOfStars = num - numberOfSpaces;
And the recursion should end on the 6th line, i.e. when current line number is n*2
So the return condition in your recursive method should be
if(thisRow == num * 2)
return;
Final Code : Putting the peices together
When we put the peices together, we get:
public static void makePattern(int thisRow, int num) {
//the termination condition
if(thisRow == num * 2)
return;
//the number of spaces
int numberOfSpaces = 0;
if(num < thisRow) {
numberOfSpaces = thisRow - num;
} else {
numberOfSpaces = num - thisRow;
}
//the number of stars
int numberOfStars = num - numberOfSpaces;
//compose the string before printing it
StringBuffer outputBuffer = new StringBuffer(num);
for (int i = 0; i < numberOfSpaces; i++){
outputBuffer.append(" ");
}
for (int i = 0; i < numberOfStars; i++){
outputBuffer.append("* ");
}
//print the string
System.out.println(outputBuffer.toString());
//recursion
makePattern(thisRow + 1, num);
}
This is code for printing diamond shaped pattern using recursion technique.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class patternRecursion {
static int n,k;
public static void main(String[] args) throws IOException{
try(Scanner s = new Scanner(System.in)){
n=Integer.parseInt(reader.readLine());
k=n-1;
printPattern(n);
}
}
public static void printChar(int m,char c){
if(m==0) return;
try{
printChar(m-1,c);
System.out.print(c);
}catch(StackOverflowError s){return;}
}
public static void printPattern(int m){
if(m==0){
return ;
}else{
printChar(m-1,' ');
printChar(n-m,'#');
printChar(n-m+1,'#');
System.out.println();
printPattern(m-1);
printChar(m,' ');
printChar(k-m,'#');
printChar(k-m+1,'#');
System.out.println();
}
}
}

Categories

Resources