Skip to content

Instantly share code, notes, and snippets.

@SoPat712
Created June 27, 2021 23:17
Show Gist options
  • Save SoPat712/5edbed75fb0385d8b35897ba9f3c43c7 to your computer and use it in GitHub Desktop.
Save SoPat712/5edbed75fb0385d8b35897ba9f3c43c7 to your computer and use it in GitHub Desktop.
Java Intermediate: 6/27/2021
package com.javafx.test;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = scanner.nextLine().trim().toLowerCase();
palindrome(word);
System.out.print("Enter a sentence: ");
String str = scanner.nextLine();
wordReverse(str);
System.out.print("Enter a string: ");
String str1 = scanner.nextLine();
System.out.print("Enter a number of times to concacenate it: ");
int int1 = scanner.nextInt();
String resultV1 = repeat_str(str1, int1);
System.out.println("\nAfter repeating "+int1+" times: "+resultV1);
}
public static void power(){
// create a 5x4 array
int[][] array = new int[5][4];
for (int power = 2; power < 7; power++) {
for (int base = 2; base < 6; base++) {
// assign the correct element based on the pattern
array[power - 2][base - 2] = (int) (Math.pow(base, power));
// print the current element
System.out.print(array[power - 2][base - 2] + "\t\t");
}
System.out.println(); // move to next row
}
}
public static void wordReverse(String str){
String[] words = str.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
/* The charAt() function returns the character
* at the given position in a string
*/
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println(reversedString);
}
public static void palindrome(String word){
int low = 0; // low index of the word
int high = word.length() - 1; // high index of the word
boolean isPalindrome = true;
if (word.isEmpty()) {
isPalindrome = false;
} else {
while (low < high) {
// check if chars at low and high indices are matching
if (word.charAt(low) != word.charAt(high)) {
isPalindrome = false;
break;
}
low++;
high--;
}
}
if (isPalindrome) {
System.out.println("The word is a palindrome.");
} else {
System.out.println("The word is NOT a palindrome.");
}
}
public static String repeat_str(String str1, int n) {
if (str1 == null || str1.isEmpty()) {
return "";
}
if (n <= 0) {
return str1;
}
String newString = "";
for(int i = 1; i <= n; i++){
newString = newString + str1;
}
return newString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment