Java - word scrambler [keeping first and last letter] - java

My assignment is to write a program to scramble a word while maintaining the same first and last letter and only swapping two letters, then prompt the user to continue if they wish.
Example: userInput = bacon | Output = bcaon
I've attached an imagine of my program, there may be several issues, but as it stands I can't really run it due to the errors in the image. I'm really confused because I got a TA to help me on this assignment, and they seemed to think this would definitely work, but as you can see it does not.
I would really appreciate if someone could tell me what exactly is wrong and why. And if you have anything to add to make this program work, I'd really, really appreciate that too, but bottom line is I just want to understand what's wrong and why.
import java.util.Scanner;
import java.util.Random;
public class FreeStyle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // Importing and initializing keyboard to 'in'
System.out.println("Please enter a word to be scrambled"); // Asking user for a word
String word = in.next(); // Initializing the user's input
System.out.println(swapLetters(word));
System.out.println("Would you like to enter another word? y/n");
String answer = in.next();
boolean userDone = true; //Using a Boolean statement to ask the user if they are done enter words or not
while (userDone) {
if (answer.equals('y')) {
System.out.println("Please enter a new word"); //Ask user for new word to scramble
word = in.nextLine(); //New initialization for 'word'
} else if (answer.equals('n')) { //If user types 'n', loops then breaks because while(userDone) is false
userDone = false;
} else {
System.out.println("Invalid input, please enter more than 3 letter words."); // The logic doesn't flow or apply to words that are less than 4 letters, so this catches that error and notifies the user
}
}
}
private static String swapLetters(String word) { //Private method used for the program only, no need to involve the user
Random r = new Random(); //Using random instead of math floor
//int arraysize = word.length();
int a = r.nextInt(word.length()-2)+1;
int b = r.nextInt(word.length()-2)+1;
//String word2 = word.substring(a, a+1);
String word2 = word.substring(0, a) + word.charAt(b)+word.substring(a+1, b)+word.charAt(a)+word.substring(b+1);
return word2;
}

Several points:
Why not use something already done exactly for what you are trying to do - Collections.shuffle? See comments in the code for understanding how it works.
You can't use equals() between a String and a char (' ' are for chars, " " are for Strings). Simple fix - just put your 'y' into "y", same for 'n'.
I've refactored the code at the beginning that we used to get user input and then scramble into a separate method, so we can reuse it again - getInputAndScramble.
And finally, I've used a do-while loop to keep looping until the user stops the loop with the "n" letter.
Please see my comments in the code, hopefully will clear things up.
public class Scrambler {
public static void main(String[] args) {
boolean userDone = true;
String word;
Scanner in = new Scanner(System.in);
getInputAndScramble(in); //Extracted method to get Scanner input and scramble
do {
System.out.println("Would you like to enter another word? y/n");
word = in.next();
while (userDone) {
if (word.equals("y")) {
getInputAndScramble(in);
break;
} else if (word.equals("n")) {
userDone = false;
} else {
System.out.println("Invalid input, please enter more than 3 letter words.");
}
}
} while (userDone); //continue until "n"
}
private static void getInputAndScramble(Scanner in) {
System.out.println("Please enter a word to be scrambled");
String word = in.next();
System.out.println(swapLetters(word));
}
private static String swapLetters(String word) {
/* Convert word into an ArrayList of characters.
Create ArrayList size of word,
convert String word into a char array and insert every char in
the char array into our ArrayList.
*/
ArrayList<Character> chars = new ArrayList<>(word.length());
for (char c : word.toCharArray()) {
chars.add(c);
}
//Shuffle, omitting first and last letters
Collections.shuffle(chars.subList(1, chars.size()-1));
//Add shuffled letters into an array to output as a word entity
char[] shuffled = new char[chars.size()];
for (int i = 0; i < shuffled.length; i++) {
shuffled[i] = chars.get(i);
}
//Return shuffled String
return new String(shuffled);
}
}

You are assuming that the two random number a and b have the property that a < b. What if a >= b? Then word.substring(a+1, b) will throw an error.
To fix it, just make sure that a < b is maintained (regenerating, swapping, etc.).
But to be sure, there are more than just this bug in your code. For example, using next(), comparing String with char, using wrong newline character, not striping newline character, and so on. You might want to add some print statements in your code you see what is actually happening.

Well, as for the swapping function, something like that should work:
private static String swapLetters(String word) {
char[] temp = word.toCharArray();
char swapHelper;
Random r = new Random();
int a = r.nextInt(word.length()-2)+1;
int b = r.nextInt(word.length()-2)+1;
swapHelper = temp[a];
temp[a] = temp[b];
temp[b] = swapHelper;
word = String.copyValueOf(temp);
return word;
}
Basically, im converting string to char array so i can operate on them with ease. A and B are variables that contain index of letters that should be swapped. After that, array is converted back to string and returned.

Related

Java Project Output

Hi I'm finishing an assignment, however I'm getting the wrong output.
The goal of the project is to reverse a string.
So it's supposed to take in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
the output is:
ereht olleH
yeH
My code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
while (true) {
str = scnr.nextLine();
if (str.equals("quit") || str.equals("Quit") || str.equals("q")) break;
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
}
My current code is that however output is coming back as:
Input
Hello there
Hey
done
Output
ereht olleH
yeH
enod
Expected output
ereht olleH
Cannot figure out what I'm doing wrong.
/*
I don't know what you know, so I am not sure how your professor
wants you to complete this, but I will do what comes to mind for myself.
*/
//Instead of while(true) I like to use do while, which runs once automatically, and continues running until a condition is met
do {
str = scnr.nextLine();
int i = 0;
//This isn't the cleanest way to solve this, especially because it doesn't remove the space before done.
//You could add more if statements for that, but the cleanest way would be to split the words into a String array
// and check if any of the values of the array equal done, and remove it before flipping it around
if(str.toLowerCase().contains("done"))
i = 4;
else if(str.toLowerCase().contains("d"))
i = 1;
while (i < str.length()) {
System.out.print(str.charAt(str.length() - i - 1));
i++;
}
System.out.println();
}
while (!str.toLowerCase().contains("done") || !str.toLowerCase().contains("d")); //This replaces that if statement from before
you are using .equals() to check if the line is equal to one of your break words, but you are giving it the input Hello there Hey done, so it will not detect the the break word (ignoring the fact that you gave it done, not quit, I'm assuming that was a typo), so to detect that, you would either have to check if the line contains that word and if so, toggle a boolean and remove the word and any text after it from the line, e.g:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
boolean end = false;
while (!end) {
str = scnr.nextLine();
if (str.contains("quit") || str.contains("Quit") || str.contains("q")) { // checks if str contains the word, so if you write "hello quit" it will still detect it.
str = str.substring(0,str.toLowerCase().indexOf("q")); // cuts off the string from the q.
end = true;
}
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
otherwise, you would just need to add the quit to the line after, and then it would work, so you would put in Hello there Hey then press enter, and then quit, and that will work.

Looping CharAt to convert a String to ASCII

Hi guys i made this
import java.util.Scanner;
//Creates a class
public class codeString {
public static void main(String[] arg) { //creates scanne/giving name
Scanner ImBack = new Scanner(System.in);
//print out "enter any String" and asks to put in data
System.out.print("Enter any String :");
String Word = ImBack.nextLine();
int ascii = (int) Word.charAt(0);
System.out.println(ascii);
System.out.println((char) Word.charAt(0));
}
}
But when i run it it converts only 1 letter, I know that i have to make a loop..
so then i went on google and made this
for (Word.charAt(0); Word = int; Word = Word) {
System.out.println("" + Word);
}
printing lots of errors, one of them was asking for toString, but it worked with out the toString for the one letter, so i know i did loop wrong 100%, could anyone help? and will i need a
length
in there?
You need something like this :
for (int i = 0; i < Word.length(); i++) {
System.out.println(Word.charAt(i));
}
Word.length() return to you the length of your word or text
Word.charAt(i) to get character by character
You can learn also the Oracle tutorials about Arrays and do...while Loop

Finding the number of occurances of a letter within a word in java

So first of all, hello everyone this is my first time stackoverflow as a question asker and I know you folks don't like people asking homework questions on here but I've been struggling with this for about a week now and have given it several reasonable attempts so I actually need help here and am not just trying to mooch answers off you amazing coders :)
So my task at hand is I'm trying (the language is java btw) to find the number of times a letter (which the user inputs) occurs in a word (which the user also picks, and then to output the number of time that word occurs, for example: the word hello has two 'l's in it.. it should be pretty easy but for some reason I can't get it :/
I believe using my current code the variable "let" gets turned into an ascii character and idk what to do with that, or rather how I should compare it with all the other characters in the word.
Please help :)
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word = "";
String letter;
int limit = 0;
String input = null;
String let;
int count = 0;
int j = 0;
while(limit == 0){
System.out.println("Type a word.");
word = scan.nextLine();
System.out.println("Type a single letter.");
letter = scan.nextLine();
let = letter.substring(0,1);
char car;
while(j<word.length()){
car = word.charAt(j);
for(int x=1; x==j; x++){
if(let.charAt(0)==car){
count ++;
}
}
j+=1;
}
System.out.println(count + " " + "occurances.");
}
}
}
Here is a sample code that should work
import java.util.Scanner;
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type a word.");
String word = scan.nextLine();
System.out.println("Type a single letter.");
String letter = scan.nextLine();
char let = letter.charAt(0);
int count = 0;
for (char char1: word.toCharArray()) {
if (char1 == let) {
count++;
}
}
System.out.println(count + " " + "occurrences.");
}
}
Here is the test output
Type a word.
letter
Type a single letter.
t
2 occurrences.

Java - How do i make a string read and count amounts in another string (

I'm having trouble activating my counter++. So far s2 is able to read s1, but cannot count amount of occurrences. Any help would be appreciated. (I realize that I am working in the wrong string, but it helps me to create the solution here first and then send it to a second string, is this poor logic?)
Sorry for the dumb question I am very new at programming
//i need a scanner that reads what i write that scanner should count
occurrences of a char another scanner declared scanner a would ask " write something" string s. = nextline etc new scanner asks for a letter string s1 = next line blb that input = something int count = StringUtils.countMatches(s1); System.out.print(amount ) i
//
public class Task07 {
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
System.out.println("write something");
String text = s1.nextLine(); //reads user input value
Scanner s2 = new Scanner(System.in); // missing smth that limits length of s2
System.out.println("geb a letter");
String letter = s2.nextLine();
int counter = 0;
boolean found;
found = text.contains(letter);
if (found == true) {
counter++;
} else {
System.out.println(counter);
}
// could use counter from 6 here but need a way to tell counter
// that it should add +1 for every time something occurs in
// the other scanner
/*
Problems: text recognizer is boolean only
- doesnt activate counter
- doesnt activate counter based on X times occurence
- doesnt limit "letter" to only one char
-
*/
}
}
Basically a loop is the simple way to count character occurrences in a string. You would use something like
int counter = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == letter.charAt(0)) {
counter++;
}
}

For loop doesn't loop my else statement (Java)?

I am writing a simple code that takes an input read by the scanner and saved into a variable word.
It is required for an assignment to create a separate method that will take that string and convert all the letters to a '?' mark. At the spaces, however, there should be a space.
The problem is that every time I run this code, it stops at the space.
Here is my code:
import java.util.Scanner;
public class commonPhrase {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String word;
System.out.print("Welcome to the Guessing Game.");
System.out.println("");
System.out.println("Please enter a common phrase");
word = input.next();
createTemplate(word);
}
public static String createTemplate(String word) {
String sPhrase = "";
for (int i=0; i < word.length(); i++) {
if (word.charAt(i) == ' '){
sPhrase += " ";
}
else {
sPhrase += "?";
}
}
System.out.println(sPhrase);
return sPhrase;
}
}
And here is a sample run of it:
Welcome to the Guessing Game.
Please enter a common phrase.
Why wont it add spaces!!!!!!!
???
You call next() on the Scanner, but that method grabs the next token, and by default it's separating tokens by whitespace. You only gathered one word.
Call nextLine() instead, to grab the text of the entire line.
word = input.nextLine();
Sample run with fix above:
Welcome to the Guessing Game.
Please enter a common phrase
Stack Overflow
????? ????????

Categories

Resources