java print text with square/frame of * - java

I am trying to figure out how to print text wrapped with a 80x80 square of *.
My code so far:
Scanner scanner = new Scanner(System.in);
String text = scanner.next();
int square = 80;
if(square > 0){
for(int i = 0; i<square; i++){
for(int j = 0; j<square; j++){
if(i == 0 || j == 0 || i == square-1 || j == square-1)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
However I cant figure out how to put the text in the square, any ideas? The frame/square must always be 80x80 *'s even if the text is longer.

Try this. Split the input into a character array and print each one.
Scanner scanner = new Scanner(System.in);
String text = scanner.next();
char[] characters = text.toCharArray(); //create character array of letters
int square = 80; //length of box
if (square > 0) {
int index = 0;
for (int i = 0; i < square; i++) {
for (int j = 0; j < square; j++) {
if (i == 0 || j == 0 || i == square - 1 || j == square - 1)
System.out.print("*");
else {
if (index < characters.length && index < square * square) //if index in bounds
System.out.print(characters[index++]); //print next letter
else {
System.out.print(" "); //else whitespace
}
}
}
System.out.println();
}
}

Alternative approach. More lines of code, but less convulted imho.
static int frameSize = 80;
public static void printTopOrBottom() {
char[] topAndBot = new char[frameSize];
Arrays.fill(topAndBot, '*');
System.out.println(topAndBot);
}
public static char[] createLine() {
char[] tmpArr = new char[frameSize];
Arrays.fill(tmpArr, ' ');
tmpArr[0] = '*';
tmpArr[frameSize-1] = '*';
return tmpArr;
}
public static char[] getInputText() {
char[] lotsOfText = new char[ (int)(Math.random() * (160*160))];
Arrays.fill(lotsOfText, 'r');
return lotsOfText;
}
public static void main(String[] args) {
char[] input = getInputText();
ArrayList<char[]> lines = new ArrayList<char[]>();
int lettersPrinted = 0;
for(int i = 1; i < (frameSize-1); i++) {
char[] tmpArr = createLine();
// find out how many letters on line i, - max 78, but less if no input text left.
int lettersToPrint = Math.min((input.length - lettersPrinted), (frameSize-2));
// if any?
if(lettersToPrint > 0) {
System.arraycopy(input, lettersPrinted, tmpArr, 1, lettersToPrint);
}
lettersPrinted += lettersToPrint;
// add line
lines.add(tmpArr);
}
printTopOrBottom();
for(char[] line : lines) {
System.out.println(line);
}
printTopOrBottom();
}

Here's another one, using printf. Its 3 times faster than the choosen answer.
public static void main(String[] args) {
long start = System.currentTimeMillis();
int intSquare = 80;
int textLength = intSquare - 2;
String square = String.valueOf(textLength);
String textLine = "Tess is very beautiful. Tess is very beautiful. Tess is very beautiful. Tess is very beautiful. Tess is very beautiful. ";
String toPrint = null;
for (int i = 0; i < intSquare; i++) {
System.out.print("*");
}
System.out.println();
for (int i = 0; i < textLength; i++) {
toPrint = textLine.length() > textLength ? textLine.substring(0, textLength) : textLine;
textLine = toPrint.length() == textLength ? textLine.substring(textLength) : "";
System.out.printf("*%-" + square + "s*\n", toPrint);
}
for (int i = 0; i < intSquare; i++) {
System.out.print("*");
}
long end = System.currentTimeMillis();
System.out.println();
System.out.println(end - start);
}

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

Integer variable does not update when if condition is true

public class test
{
static Scanner store = new Scanner(System.in);
public static void main(String[] args)
{
String str1 = args[0];
String str2 = args[1];
System.out.printf("%nThere are %d dissimilar characters in the two strings.%n", CountNotSim(str1, str2));
}
public static int CountNotSim(String str1, String str2)
{
String s1 = str1.toLowerCase();
String s2 = str2.toLowerCase();
char[] a1 = new char[s1.length()];
char[] a2 = new char[s2.length()];
for (int g = 0; g < s1.length(); g++)
a1[g] = s1.charAt(g);
for (int h = 0; h < s2.length(); h++)
a2[h] = s2.charAt(h);
int check = 0, stored;
char[] array = new char[26];
int ctr = s1.length() + s2.length();
for (int i = 0; i < a1.length; i++)
{
check = 0;
stored = 0;
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j])
{
check++;
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ')
if (stored == 0)
array[k] = a1[i];
if (a1[i] == array[k])
{
stored = 1;
break;
}
}
System.out.print(stored + "/ ");
}
}
if (check > 0)
{
if (stored == 0)
ctr -= (check + 1);
else if (stored == 1)
ctr--;
}
System.out.print(ctr + " "); //checker
}
System.out.println();
return ctr;
}
}
The program checks for dissimilar letters in two strings inputted from the command line. Variable "stored" is supposed to change to 1 whenever there's a match to avoid extra deductions to variable "ctr". However, for some reason, not only does "stored's" value not change, the array "array" also doesn't update its elements whenever there's a match. I'm at a loss on how to fix it--nothing looks incorrect.
You wrote this:
char[] array = new char[26];
...
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ') {
...
But you simply set the length of array not its content.
As a char array, it's filled with the default char value, which is not the character space but the value 0 (not the character 0, but the numeric value 0)
So array[k] == ' ' will never be true.
Try with that:
for (int k = 0; k < 26; k++)
{
if (array[k] == 0) {
...

How to include spaces inside a cypher program?

The code asks if you want to encode or decode a message, then it asks for the message. It will work by this reference:
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 "
"kngcadsxbvfhjtiumylzqropweKNGCADSXBVFHJTIUMYLZQROPWE,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 "
Therefore if you try to encode the letter 'a' for example, it will output the letter 'k'.
My problem is that I can't include any spaces when typing the message.
Here is my code:
import java.util.Scanner;
public class SecretMessage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter 1 to encode, 2 to decode, 3 to quit:");
int start = input.nextInt();
if (start == 3){
break;
}
System.out.println("Type your message:");
String test = input.next();
String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 ";
String enc = "kngcadsxbvfhjtiumylzqropweKNGCADSXBVFHJTIUMYLZQROPWE,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 ";
char[] array = test.toCharArray();
char[] decoded = letters.toCharArray();
char[] encoded = enc.toCharArray();
int[] position = new int[array.length];
char[] end = new char[array.length];
if (start == 1){
for (int i = 0; i < test.length(); i++){
for (int j = 0; j < decoded.length; j++){
if (array[i] == decoded[j]){
position[i] = j;
}
}
}
for (int f = 0; f < test.length(); f++){
end[f] = encoded[position[f]];
}
for (int x = 0; x < test.length(); x++){
System.out.print(end[x]);
}
System.out.println(" ");
} else {
for (int i = 0; i < test.length(); i++){
for (int j = 0; j < encoded.length; j++){
if (array[i] == encoded[j]){
position[i] = j;
}
}
}
for (int f = 0; f < test.length(); f++){
end[f] = decoded[position[f]];
}
String output = new String(end);
System.out.println(output);
}
System.out.println(" ");
} while (1 ==1);
}
}

Searching for chars from a String in a 2d char array?

I want to be able to search through my array and find chars that are in a String the user has input? so if the user types "message" I want it to return the index of 'm' 'e' 's' and so on. How would I do this? Heres my code so far:
import java.util.ArrayList;
import java.util.Scanner;
public class Matrix {
private char[][] matrix = new char[6][6];
private int[] usedNumbers = new int[50];
{for(int x = 0; x < usedNumbers.length; x++) usedNumbers[x] = -1;}
private final char[] CIPHER_KEY = {'A','D','F','G','V','X'};
private final String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public Matrix() {
int random;
for(int i = 0; i < CIPHER_KEY.length; i++) {
for(int j = 0; j < CIPHER_KEY.length; j++) {
validation: while(true) {
random = (int)(Math.random()*validChars.length()-1);
for(int k = 0; k < usedNumbers.length; k++) {
if(random == usedNumbers[k]) continue validation;
else if(usedNumbers[k]==-1) usedNumbers[k] = random;
}
break;
}
matrix[i][j] = validChars.split("")[random].charAt(0);
}
}
}
public void searchMatrix(){
Scanner console = new Scanner (System.in);
String phrase = "";
System.out.println("\n Enter the message you would like "
+ "to encrypt with the cipher: \n");
phrase = console.nextLine();
char[] phraseSplit = phrase.toCharArray();
console.close();
}
public String toString() {
String output = " A D F G V X\n";
for(int i = 0; i < CIPHER_KEY.length; i++) {
output += CIPHER_KEY[i] + " ";
for(int j = 0; j < CIPHER_KEY.length; j++) {
output += matrix[i][j] + " ";
}
output += "\n";
}
return output;
}// toString end
}
I have looked for tutorials online but cant find one that would help me in this situation! help? I dont know what to do next.
If I am not mistaking, you are almost there. All you have to do is to add nested loops after you got phraseSplit.
for (int k=0; k<phraseSplit.length; k++) {
for (int i=0; i<matrix.length; i++) {
for (int j=0; j<matrix[i].length; j++) {
if (phraseSplit[k] == matrix[i][j]) {
System.out.printf("%c at %d, %d\n", phraseSplit[k], i, j);
}//end if
}//end for j
}//end for i
}//end for k
There may be better way to do it. Also, Sasha's shuffle() is a very good suggestion.

Checking characters in a string

I want to wrote a program which checks every character in a string. If the two characters are same in a row I want to increase count by 1. The program should scan all the characters and give us a value. T is for deciding how many String's we will enter.
For example: (input)
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Ouput
3
4
0
0
4
But I get 0
3
4
0
0
Could you help? What I have done wrong?
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args)
{
int i,T,j,count;
String S;
char K;
count = 0;
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
for (i = 0; i <= T - 1; i++)
{
count = 0;
S = scan.nextLine();
char[] list = new char[S.length()];
for(j = 0; j <= S.length() - 1; j++)
{
list[j] = S.charAt(j);
}
for(j = 1; j <= S.length() - 1; j++)
{
if(list[j - 1] == list[j])
{
count++;
}
}
System.out.println(count);
}
}
}
I think something like the below should help you out, It first requires a number of strings that will be entered and then in the entered string will count the number of times a character is the same as the previous character. It wont take a series of strings though, it will do them one by one, see the example output below:
public static void main(String[] args){
int numInput;
String inputString;
Scanner scanner = new Scanner(System.in);
numInput = scanner.nextInt();
for(int y = 0; y < numInput;y++){
inputString = scanner.next();
char[] chars = inputString.toCharArray();
int counter = 0;
char curr;
for(int x = 0; x < chars.length;x++){
curr = chars[x];
if(x>0){
if(chars[x-1] == curr){
counter++;
}
}
}
System.out.println("Count for string " + inputString + " was " + counter);
}
scanner.close();
}
Testing:
5
AASAAB
Count for string AASAAB was 2
AAAAAA
Count for string AAAAAA was 5
AAVAAD
Count for string AAVAAD was 2
MOOMOO
Count for string MOOMOO was 2
MAAAAAA
Count for string MAAAAAA was 5
Try this...
public static void main(String[] args) {
int i, T, j, count;
String S;
char K;
count = 0;
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
for (i = 0; i <= T - 1; i++) {
scan = new Scanner(System.in);
count = 0;
S = scan.nextLine();
char[] list = new char[S.length()];
for (j = 0; j <= S.length() - 1; j++) {
list[j] = S.charAt(j);
}
for (j = 1; j <= S.length() - 1; j++) {
if (list[j - 1] == list[j]) {
count++;
}
}
System.out.println(count);
}
}

Categories