Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Can I rewrite this code without using any loops? and just if/then/else? package scramble; import java.util.Scanner; import java.lang.Math; public class Scramble{ public static void main(String[]

Can I rewrite this code without using any loops? and just if/then/else?

package scramble;

import java.util.Scanner;

import java.lang.Math;

public class Scramble{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter 5-letter word: ");

String word = input.next();

int wordLength = word.length();

if (wordLength == 5) {

word = word.toUpperCase(); //to uppercase

String scram_word = ""; //scrambled word

//variables

int i;

char c;

int j; //to iterate

//we need to generate random number 4 times (5 to 2)

for(j=5; j>=2; j--)

{

i = (int)(Math.random()*j); //generate random number between 0 and j

c = word.charAt(i); //get char to remove

scram_word = scram_word + c; //add char to scram_word

String before = word.substring(0,i); //string before c

String after = word.substring(i+1); //string after c

word = before + after; //word without c

}

scram_word = scram_word + word; //add last char

System.out.println("Scrambled word: " + scram_word); //print scram_word

String fake_word = ""; //fake word

String vowels = ""; //vowels

String consonants = ""; //consonants

//get all consonants and vowels

for(j=0; j

{

if(scram_word.charAt(j)=='A' || scram_word.charAt(j)=='E' || scram_word.charAt(j)=='I' || scram_word.charAt(j)=='O' || scram_word.charAt(j)=='U')

vowels = vowels + scram_word.charAt(j);

else

consonants = consonants + scram_word.charAt(j);

}

//add cons and vowels to fake_word alternatively

for(j=0; j

fake_word = fake_word + consonants.charAt(j) + vowels.charAt(j);

//if any vowles remained add them to fake_word

if(vowels.length()>j)

fake_word = fake_word + vowels.substring(j);

//if any consonants remained add them to fake_word

if(consonants.length()>j)

fake_word = fake_word + consonants.substring(j);

//print fake_word

System.out.println("Fake word: " + fake_word);

}

else{

System.out.println("Word must be 5 letters");

System.exit(1);

}

}

}

Thanks

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions