I'm working on a code in java that will swap a random letter inside of a word with another random letter within that word.
I need to apply this code to an entire string. The issue I'm having is my code can't identify white space and therefore runs the method for once per string instead of once per word. How can I split the input string and apply the method to each word individually. Here's what I have so far.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args {
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
System.out.print(scramble(word));
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
Check the inline comments:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
//Split your input phrase
String[] wordsArray = word.split(" ");
//For each word in the phrase call your scramble function
// and print the output plus a space
for (String s : wordsArray){
System.out.print(scramble(s) + " ");
}
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
As destriped in teh String.split(); you can define a regrex for instance " " and then a return array of String[] for all substrings split on the input is returned
see String split
example
String in = "hello world";
String[] splitIn = in.split(" ");
The same way you can test for other things such as "," "." ";" ":" etc
Related
Please run the code if possible
input: "wooooow"
output:
w:2
o:5
o:5
o:5
o:5
o:5
w:2
I want the results to be : w:2 o:5
I have tried several ifs and loops to make it happen but I can't is there a syntax for it? or anything
import java.util.Scanner;
public class test {
public static void main( String[] args ){
String sWord= new String();
int nCtr,nCtr2,nTemp=0,n,n1=0,n2=0,n3=0;
char cTemp=' ',cTemp2=' ';
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
n = sWord.length();
char[] cArray = new char[n];
cArray = sWord.toCharArray();
for(int ctr=cArray.length;ctr>0;ctr--){
for(nCtr=0;nCtr<cArray.length;nCtr++){
if(cArray[nCtr]==sWord.charAt(n1)){
nTemp++;
}
}//for
cTemp = cArray[n2];
for(nCtr2=0;nCtr2<n;nCtr2++){
if(sWord.charAt(nCtr2)=='$'){
n3++;
}
}//for
System.out.println("# of occurence of " + cTemp + " is " + nTemp);
n1++;
n2++;
nTemp=0;
}//for minus
}//
}//class
You could try something like this:
import java.util.HashMap;
import java.util.Scanner;
public class test {
public static void main( String[] args ){
String sWord= new String();
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
HashMap<Character, Integer> charCount = new HashMap<Character, Integer>();
for(Character c : sWord.toCharArray()) {
if(charCount.containsKey(c)) {
charCount.put(c, charCount.get(c)+1);
} else {
charCount.put(c, 1);
}
}
for(Character key : charCount.keySet()) {
System.out.print(key + ":" + charCount.get(key) + " ");
}
}
}
This will print the following lines:
Enter a Word
wooooow
w:2 o:5
Should work for Uppercase, Lowercase, Numbers, ... everything you can save in a String.
edit:
Without using a HashMap:
public static void main( String[] args ){
String sWord= new String();
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
int[] cArr = new int[1024];
for(char c : sWord.toCharArray()) {
if((int) c <= cArr.length) {
cArr[(int) c]++;
}
}
for(int x = 0; x < cArr.length; x++) {
if(cArr[x] > 0) {
System.out.print((char) x + ":" + cArr[x]);
}
}
}
This works because you can cast a char to an integer and use it as an index for the array. Also you can do this reverse integer -> char.
This will work for the first 1024 Chars in your Charset. Normaly theese are all uppercase, lowercase, numbers and special characters.
This answer works only for lowercase input. For uppercase as well, use an array of size 46.
You will have to keep track of the occurrences yourself by creating a new array or some other data structure. Also, I dont think that your loops are very efficient.
import java.util.Scanner;
public class Temp {
public static void main( String[] args ){
String sWord= new String();
int nCtr,nCtr2,nTemp=0,n,n1=0,n2=0,n3=0;
char cTemp=' ',cTemp2=' ';
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
n = sWord.length();
char[] cArray = new char[n];
cArray = sWord.toCharArray();
int[] countsOfChars = new int[26];
for(int ctr=cArray.length;ctr>0;ctr--){
for(nCtr=0;nCtr<cArray.length;nCtr++){
if(cArray[nCtr]==sWord.charAt(n1)){
nTemp++;
}
}//for
cTemp = cArray[n2];
for(nCtr2=0;nCtr2<n;nCtr2++){
if(sWord.charAt(nCtr2)=='$'){
n3++;
}
}//for
// System.out.println("# of occurence of " + cTemp + " is " + nTemp);
countsOfChars[cTemp - 'a'] = nTemp;
n1++;
n2++;
nTemp=0;
}//for minus
for(int i=0; i<26; i++){
if(countsOfChars[i] != 0) {
System.out.println("# of occurence of " + (char)('a'+i) + " is " + countsOfChars[i]);
}
}
}//
}//class
You can try something like this
string str = "wooooow";
Dictionary<char, int> table = new Dictionary<char, int>();
foreach (char ch in str.ToCharArray())
{
int count = 0;
if (table.TryGetValue(ch, out count))
{
table[ch] = count + 1;
}
else
{
table.Add(ch, 1);
}
}
foreach (var item in table)
{
Console.Write(item.Key + ":" + item.Value+" ");
}
I present three random letters to the user, lets say ' J U D ' and my user has to give a word for each letter starting with the assigned random letter, for example:
"Just Use Data".
I have been unsuccessful searching for how to validate that the user's input starts with the assigned random letter.
My code
public static void generateLetters(){
Random randomLetter = new Random();
int i;
char[] letter = {'A', 'B', 'C', 'D', 'E', 'F'};
// It's A-Z, but for typing sake... you get the point
char[] letters = new char[26];
for(i = 0; i <= 3; i++){
letters[i] = letter[randomLetter.nextInt(26)];
System.out.printf(letters[i] + " ");
}
}
The above block will generate letters randomly and works fine. Below, I'll enter basically what I have for the user input.
public static String[] getWord(String[] word){
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
return word;
}
Simple thus far and this is my main function:
public statc void main(String[] args){
generateLetters();
getWord();
}
I need to take the string returned from getWord() and verify that each word input does begin with the randomly assigned letters. I've been unsuccessful in doing this. All of the syntax I find during my online research just gets me confused.
generateLetters() should return the generated letters.
getWord() doesn't actually do anything with the user input. Make it return a String that contains the user input.
You can use a separate method to validate the input.
Here's a fixed version of your code.
public static void main(String[] args) {
char[] letters = generateLetters();
System.out.println(letters);
String input = getWord();
System.out.println("Input is " + (isValid(letters, input) ? "valid" : "invalid"));
}
public static boolean isValid(char[] letters, String input) {
String[] words = input.split(" ");
for (int n = 0; n < words.length; n++)
if (!words[n].startsWith("" + letters[n]))
return false;
return true;
}
// Here're the fixed versions of your other two methods:
public static String getWord(){
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
wordInput.close();
return inputWord;
}
public static char[] generateLetters(){
Random randomLetter = new Random();
char[] letter = new char[26];
char c = 'A';
for (int i = 0; i < 26; i++)
letter[i] = c++;
char[] letters = new char[26];
for(int i = 0; i < 3; i++)
letters[i] = letter[randomLetter.nextInt(26)];
return letters;
}
You can try this one.
public static String getWord() {
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
wordInput.close();
return inputWord;
}
public static void main(String[] args) {
char[] letters = generateLetters();
String input = getWord();
StringTokenizer st = new StringTokenizer(input, " ");
int counter = 0;
boolean isValid = true;
while (st.hasMoreTokens()) {
String word = st.nextToken();
if (!word.startsWith(String.valueOf(letters[counter]))) {
isValid = false;
break;
}
counter++;
}
if (isValid) {
System.out.println("valid");
} else {
System.out.println("Invalid");
}
}
This code will only work for the input you have provided, i am assuming thats what you need i.e. if the random letters are ' J U D ' only the input "Just Use Data". will qualify as correct input and not Use Just Data. I have also not checked the boundaries of input.
import java.util.Random;
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
char[] letters = generateLetters();
String input = getWord();
String[] words = input.split(" ");
if (words.length == letters.length) {
if (check(letters, words)) {
System.out.println("Yeah");
} else {
System.out.println("Oops");
}
} else {
System.out.println("INVALID");
}
}
public static Boolean check(char[] letters, String[] words) {
for (int i = 0; i < letters.length; i++) {
if (words[i].charAt(0) != letters[i]) {
return false;
}
}
return true;
}
public static String getWord() {
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
return inputWord;
}
public static char[] generateLetters() {
Random randomLetter = new Random();
char[] letters = new char[3];//Make it varaible length
for (int i = 0; i < letters.length; i++) {
letters[i] = (char) ((int) randomLetter.nextInt(26) + 'A');
System.out.printf(letters[i] + " ");
}
return letters;
}
}
Method 2 Regex
public static Boolean check(char[] letters, String word) {
return word.matches(letters[0]+"(\\S)*( )"+letters[1]+"(\\S)*( )"+letters[2]+"(\\S)*");
}
I am to create a program that checks for palindromes in a sentence and display the palindromes that have been found. My following code keeps giving me a "String is out of bounds" error. What am i doing wrong?
My Program:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
//Split string
spacePos = input.indexOf(" ");
String word = input.substring(0, spacePos);
//Get palindromes
System.out.println("Your Palindromes are:");
for (int counter = 0; counter < input.length(); counter++) {
//Reverse first word
wordlength = word.length();
for (int i = wordlength - 1; i >= 0; i--) {
Rinput = Rinput + word.charAt(i);
//Add word to An array of Palindromes
if (Rinput.equalsIgnoreCase(word)) {
Palin = word;
System.out.println("Palin:" + Palin);
break;
}
//Move on to the next word in the string
input = input.substring(input.indexOf(" ") + 1) + " ";
word = input.substring(0, input.indexOf(" "));
}
}
}
}
If you know functions you can use a recursive function to build the palindrome version of a string (it's a common example of how recursion works).
Here's an example:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
String[] words = input.split(" +"); // see regular expressions to understand the "+"
for(int i = 0; i < words.length; i++) { // cycle through all the words in the array
Rinput = makePalindrome(words[i]); // build the palindrome version of the current word using the recursive function
if(Rinput.equalsIgnoreCase(words[i])) {
Palin = words[i];
System.out.println("Palin: " + Palin);
}
}
}
// this is the recursive function that build the palindrome version of its parameter "word"
public static String makePalindrome(String word) {
if(word.length() <= 1) return word; // recursion base case
char first = word.charAt(0); // get the first character
char last = word.charAt(word.length()-1); // get the last character
String middle = word.substring(1, word.length()-1); // take the "internal" part of the word
// i.e. the word without the first and last characters
String palindrome = last + makePalindrome(middle) + first; // recursive call building the palindrome
return palindrome; // return the palindrome word
}
}
You should have done is
public static void main(String[] args) {
String Palin, input, Rinput = "";
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
for (int counter = str.length()-1; counter >= 0; counter--) {
Rinput = Rinput + str.charAt(counter);
}
if (Rinput.equalsIgnoreCase(str)) {
Palin = str;
System.out.println("Palin:" + Palin);
}
Rinput="";
}
}
I don't know if you are aware but StringBuilder has a reverse method to it. Which can be used like this :
public static void main(String[] args) {
String input;
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
if (new StringBuilder(str).reverse().toString().equalsIgnoreCase(str)) {
System.out.println("Palin:" + str);
}
}
}
How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}
Ok, so i have created a program that defines if the inserted word is a palindrome or not.
But i need help on removing numbers that where to be inserted in the string.
import java.util.*;
import java.util.Scanner;
class Palindrome
{
public static void main(String args[])
{
String reverse = "";
Scanner scan = new Scanner(System.in);
System.out.print("Type a sentence and press enter: ");
String input = scan.nextLine();
// use regex to remove the punctuation and spaces
String Input = input.replaceAll("\\W", " ");
System.out.println(Input);
int length = input.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse.replaceAll("\\W", "") + input.charAt(i);
System.out.println(reverse);
if (input.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
If you want to remove digits, try input.replaceAll("[0-9]","")
Try this........
public class T1 {
public static void main(String[] args){
String s = "1234ajhdhols233adfjal";
String[] arr = s.split("\\d");
String sx = new String();
for(String x : arr){
sx = sx+x;
}
System.out.println(sx);
}
}
Example:
public static void main(String[] args) {
String s = "1234ajhdhols233adfjal";
String str = s.replaceAll("\\d", "");
System.out.println(str);
}