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);
}
}
Related
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++;
}
}
I'm trying to get a program that checks if a string input from the user is a palindrome (task from CodeAbbey). When I type myself input data, it works well, but if strings are put automatically by the site, I'm getting this error:
Exception:
Exception in thread "main" java.util.NoSuchElementException: No line
found at java.util.Scanner.nextLine(Scanner.java:1540) at
Palindromes.main(Palindromes.java:13)
The code:
public class Palindromes {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanStr = new Scanner(System.in);
//Number of tests
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
//Getting string
String s = scanStr.nextLine();
//Variable for number of letters in string
int letters = 0;
//Getting number of letters in string
for (int j = 0; j < s.length(); j++) {
if (Character.isLetter(s.charAt(j)))
letters++;
}
//Array with string characters
char[] characters = new char[letters];
//Counter
int a = 0;
//Put chars from string to array
for (int j = 0; j < s.length(); j++) {
if (Character.isLetter(s.charAt(j))) {
characters[a] = s.toLowerCase().charAt(j);
a++;
}
}
//Counters
int x = 0;
int y = characters.length - 1;
//Variable for result
char res = 'Y';
//If the string is a palindrome
do {
if (characters[x] != characters[y])
res = 'N';
x++;
y--;
} while (x <= y);
//Prints result
System.out.print(res + " ");
}
}
}
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.
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);
}
So I have to fill a 2D array with chars, print out the array, let people search for words, and then print out the number of instances of that word and the array with the instances of that word highlit.
here is my code so far:
import java.util.Scanner;
import java.util.*;
public class testSearchMatrix {
public static void printArray(char[][] myArray){
for(int i = 0; i < myArray.length; i++){
for(int j = 0; j < myArray.length; j++){
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
queryNum += 1;
}
}
}
System.out.println(queryNum);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
//Create an alphabet array so I can use this to fill in the searchBox array
char[] alphabet = {'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("Please choose an array size: ");
int a = keyboard.nextInt();
//Create a square array
char[][] searchBox = new char[a][a];
//Fill in the array with random chars
for(int i = 0; i < searchBox.length; i++){
for(int j = 0; j < searchBox[i].length; j++){
int randNum = random.nextInt(25);
searchBox[i][j] = alphabet[randNum];
}
}
//Implement my method to print the array to the screen
System.out.println("Here is the square matrix with random letters: ");
printArray(searchBox);
System.out.println("Enter a query to search: ");
searchArray(searchBox);
}
}
This will print out my array but I can't seem to get the search to work.
Modified Your searchArray function
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
String out = null;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
//System.out.println(i+":"+j+a[i][j]);
//w+=1;
if(out==null)
{
out=String.valueOf(a[i][j]);
}else
out=out+a[i][j];
for(int f = 1; f < query.length(); f++){
if(j+f<5){
if(a[i][j+f] == query.charAt(w+f)){
// System.out.println(i+"Index:w+f"+w+f+query.charAt(w+f)+"query.charAt(w+f)Index"+query.indexOf(query.charAt(w+f)));
// System.out.println(i+":"+j+a[i][j+f]);
out=out+a[i][j+f];
System.out.println(out+":"+query+"here"+out.length()+query.length());
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
}
}
} if(out!=null)
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
out=null;
}
}
}
System.out.println(queryNum);
}
OuptPut