Random String Generator keeps adding to previous iterations - java

I am writing a program that takes a user's input for a string that must be of length 6, and creates a random version of that string. Then, it prints out 5-10 iterations of a randomised string. For example:
The input of 8 and abcdef would create 8 lines of random variations of abcdef. The program below does that, but it's adding strings together, as so:
abbdfe
abbdfeacbfed
and so on. Does anyone know how to change it so it would print abbdfe acbfed and so on.
I know there are some functional issues with my code but it works as a start.
package matrixMaker;
import java.util.Scanner;
import java.util.Random;
public class matrixMaker
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a number between 5 and 10, inclusively: ");
int userInput = in.nextInt();
in.nextLine();
System.out.print("Please enter a string of length 6 characters: ");
String textToChange = in.nextLine();
String randomText = "";
int length = 6;
// Print error if text is not 6 characters long.
while(textToChange.length() != 6)
{
System.out.println("Error! Enter a string of length 6.");
}
// If input is 6 characters, print out randomText X amount of times, depending on the user's specification of user.
if(textToChange.length() == 6)
{
for (int i = 1; i <= userInput; i++)
{
// Initialise array to create random order of chars.
Random rand = new Random();
char[] text = new char[length];
for(int a = 0; a < length; a++)
{
text[a] = textToChange.charAt(rand.nextInt(textToChange.length()));
}
// Take the chars from array and concatenate them into a string of the same size as the text variable.
for(int a = 0; a < text.length; a++)
{
randomText += text[a];
}
System.out.printf(randomText + "\n");
}
}
in.close();
}
}

You seem to be initializing the variable randomText at the top of the method, but keep adding to the same variable inside the loop, so it will keep adding to itself.
String randomText = "";
randomText += text[a];
Either initialize the randomText String inside the loop, or after your last line inside the loop, assign it back to an empty string again.
Btw, you seem to have another error here:
// Print error if text is not 6 characters long.
while(textToChange.length() != 6)
{
System.out.println("Error! Enter a string of length 6.");
}
This loop will go for infinite, you need to add a way to allow the user to change the input after the error is displayed.
while(textToChange.length() != 6)
{
System.out.println("Error! Enter a string of length 6.");
in.nextLine();
textToChange = in.nextLine();
}
--Edit added to OP comment:
To print the character of the odd generated text on the odd row number; one way to do it is to consider pushing your generated randomText to an empty ArrayList which you initialize outside the loop..then you can loop over your ArrayList separately. You can think of ways to refactor this and put in an outside method in the way you like. like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a number between 5 and 10, inclusively: ");
int userInput = in.nextInt();
in.nextLine();
System.out.print("Please enter a string of length 6 characters: ");
String textToChange = in.nextLine();
int length = 6;
// Print error if text is not 6 characters long.
while (textToChange.length() != 6) {
System.out.println("Error! Enter a string of length 6.");
in.nextLine();
textToChange = in.nextLine();
}
//new array list for results of random text generated
ArrayList<String> randomTextArray = new ArrayList<>();
// If input is 6 characters, print out randomText X amount of times, depending on the user's specification of user.
if (textToChange.length() == 6) {
for (int i = 1; i <= userInput; i++) {
String randomText = "";
// Initialise array to create random order of chars.
Random rand = new Random();
char[] text = new char[length];
for (int a = 0; a < length; a++) {
text[a] = textToChange.charAt(rand.nextInt(textToChange.length()));
}
// Take the chars from array and concatenate them into a string of the same size as the text variable.
for (int a = 0; a < text.length; a++) {
randomText += text[a];
}
randomTextArray.add(randomText);
System.out.printf(randomText + "\n");
}
System.out.printf("Odd Characters \n");
String oddCharsOfRandomText = "";
for (int i=0; i < randomTextArray.size(); i++) {
if (!(i%2 == 0)) { //resolve true only if we are in an odd line
for (int x=0; x <= randomTextArray.get(i).length(); x++ ){
if (!(x%2 == 0)) { //resolve true only if we are in an odd character
oddCharsOfRandomText += randomTextArray.get(i).charAt(x);
}
}
}
}
System.out.printf(oddCharsOfRandomText + "\n");
}
in.close();
}

Related

Need help ending a program with a do while loop

I am creating a wordle project, where the word is set to "tyler". The user's guess is saved as a string, as is the wordle word, "tyler". Both the strings are saved as characters in an array, then the program checks whether each character in the arrays match.
My code is here:
// Nelson's work
import java.util.Scanner;
class FinalProject {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Nelson's work
int counter = 0;
do {
String word = "tyler";
System.out.println("Press enter to begin");
// Saves userInput as a string
String userInput = input.nextLine();
while (userInput.length() != 5) {
System.out.println("Enter a 5 letter word: ");
userInput = input.nextLine();
counter++;
}
// End of Nelson's work
// Tyler's work
// Creates an array of length equal to string length
char[] ch = new char[userInput.length()];
// For loop to put characters into array
for (int i = 0; i < userInput.length(); i++) {
ch[i] = userInput.charAt(i);
}
// 'For each' loop to print each element of the array
for (char c : ch) {
System.out.println(c);
}
// Creates an array of the size of the wordle word
char[] wordle = new char[word.length()];
System.out.println(" ");
// Characters of string wordle word which is 'tyler' are in an array
for (int i = 0; i < word.length(); i++) {
wordle[i] = word.charAt(i);
// System.out.println(wordle[i]);
if (wordle[i] == ch[i]) {
System.out.println("Letter " + ch[i] + " is correct");
} else {
System.out.println("Letter " + ch[i] + " is not correct");
}
}
System.out.println(" ");
} while (counter <= 5);
System.out.println("You lost!");
// End of Tyler's work
}
}
I am trying to make a do while loop that reprompts the user for a word, giving the user 5 tries, and the program would end if A) the user has had all 5 tries, or B) the user gets the word right. Please help with the loop, or if there is additional code I should try.
I tried to put the variables inside the dowhile loop, but one of the variables is from a scanner (it is user input), but I need that inside the do while loop so it reprompts the user while the counter is less than or equal to 5.

How would I validate User input (names only / no numbers) using an if statement

The following takes in 10 names and then prints them using System.out.println later. I have an if statement below when I enter a number it warns me "do no enter numbers".
The problem is that after the warning prompt I enter 10 names but the number prints off as the first item in the Array? Then the names print afterwards?
import java.io.*;
public class Input {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] myarray = new String[10];
System.out.println("Enter a 10 names");
for (int i = 0; i < 10; i++) {
myarray[i] = br.readLine();
if (!myarray[i].matches("[a-zA-Z_]+")) {
System.out.println("Invalid name,please do not enter numbers");
}
}
System.out.println("Here are your names");
for (int i = 0; i < 10; i++) {
System.out.println(myarray[i]);
}
}
}
The problem is that when you're rejecting a value you're incrementing the loop counter as if you'd accepted it.
Instead of writing the input to the array, check whether it is valid first:
int i = 0;
while (i < 10) {
String line = br.readLine();
if (line.matches("[a-zA-Z_]+") {
myarray[i++] = line;
} else {
System.out.println("Invalid name");
}
}
Note that i is only incremented when a value is written to the array, and while is used in preference to for since the number of iterations is unknown.

Prevent JUnit test from getting stuck in while-loop

I'm currently writing some JUnit tests for some assignments on Replit.com's Teams for education. I have a test that's getting stuck, I believe, because of a while loop in the main method. If the first input is valid, according to the program, the test runs. If the first input is invalid, the test gets stuck.
Here's the test:
#Test
public void validPW(){
String correctOutput = "Enter a password >> Not enough uppercase letters!\nNot enough digits!\nReEnter a password >> Valid password\nGoodbye!";
try{
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//PrintStream ps = new PrintStream(baos);
System.setOut(new PrintStream(baos, false, "UTF-8"));
// IMPORTANT: save old Sytem.in!
InputStream is = System.in;
// Set new System.in
System.setIn(new ByteArrayInputStream("Iljvm4\nVaGN76js\n".getBytes()));
// Calling main method should save main method's output as string literal to baos.
String[] requiredArray = {"Hello", "There"};
ValidatePassword.main(requiredArray);
// Put things back
System.out.flush();
System.setOut(old);
//Restore
System.setIn(is);
assertEquals(correctOutput, baos.toString());
}catch(IOException ioe){
new IOException("i/o problem - test not executed\n");
}
}
Here's the program:
import java.util.*;
public class ValidatePassword {
public static void main(String[] args) {
String passWord;
boolean Valid = false;
final int NUM = 2; // two digits and two Upper case letters
// counters to count the required digits and letters
int upperCount = 0;
int lowerCount = 0;
int digitCount = 0;
while (!Valid) {
Scanner in = new Scanner(System.in);
int numSpaces = 0;
System.out.print("Enter a password >> ");
passWord = in.next();
in.nextLine(); // capture dangling newline char.
// Using a for loop to iterate over each character in the String
for (int i = 0; i < passWord.length(); i++) {
char ch = passWord.charAt(i);
if (Character.isUpperCase(ch)){ // Using the Character class's methods
upperCount++;
}
else if (Character.isLowerCase(ch)){
lowerCount++;
}
else if (Character.isDigit(ch)){
digitCount++;
}
}
if (upperCount >= NUM && lowerCount >= 3 && digitCount >= NUM) {
System.out.println("Valid password\nGoodbye!");
Valid = true;
} else {
if (upperCount < NUM)
System.out.println("Not enough uppercase letters!");
if (lowerCount < 3)
System.out.println("Not enough lowercase letters!");
if (digitCount < NUM)
System.out.println("Not enough digits!");
System.out.print("Re");
// Resetting the counters if not a valid password
upperCount = 0;
lowerCount = 0;
digitCount = 0;
}
}
}
}
First, the code in ValidatePassword tries to read the input stream beyond its end, so the scanner initialization needs to be moved out of the loop and a condition in.hasNextLine() needs to be checked.
Also, it's better to use a single reading of the line passWord = in.nextLine(); instead of a pair in.next(); in.nextLine();.
These two fixes should resolve the issue with incorrect loop.
Scanner in = new Scanner(System.in);
while (!Valid && in.hasNextLine()) {
int numSpaces = 0;
System.out.print("Enter a password >> ");
passWord = in.nextLine();
//in.nextLine(); // capture dangling newline char.
// ... keep the rest as is
And the last, correctOutput needs to be fixed for assertEquals to complete successfully.

String of only even numbers and only odd numbers

I know there are already questions asking something similar to my question, but despite reading those, they don't quite do what I want.
I am creating a code that takes a users input of a number between 0-100 (inclusive). Whatever the number, it will print all the numbers leading up to that number and that number
EX: user input = 25
output = 012345678910111213141516171819202122232425
I have that part working. Now I am supposed to use that string and create two new strings, one for only the odd and the other one for the even numbers.
EX: user input = 25
output: odd numbers: 135791113151719212325 & even numbers = 024681012141618202224
Here is my code so far:
import java.util.Scanner;
public class OddAndEven{
public String quantityToString() {
Scanner number = new Scanner(System.in);
int n = number.nextInt();
String allNums = "";
if ((n >= 0) && (n <= 100)) {
for (int i = 0;i <= n; ++i)
allNums = allNums + i;
return allNums;
}
else {
return "";
}
}
public void oddAndEvenNumbers(int num) {//Start of second method
String allNums = ""; //String that quantityToString returns
String odd = "";
String even = "";
if ((num >= 0) && (num < 10)) { //Looks at only single digit numbers
for (int i = 0; i <= allNums.length(); i++) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) { //trying to get the allNums string to be broken into individual numbers to evaluate
even = even + allNums.charAt(i); //adding the even numbers of the string
}
else {
odd = odd + allNums.charAt(i);
}
}
}
else { //supposed to handle numbers with double digits
for (int i = 10; i <= allNums.length(); i = i + 2) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) {
even = even + allNums.charAt(i);
}
else {
odd = odd + allNums.charAt(i);
}
}
}
System.out.println("Odd Numbers: " + odd);
System.out.println("Even Numbers: " + even);
}
public static void main(String[] args) {
System.out.println(new OddAndEven().quantityToString());
//System.out.println(new OddAndEven().oddAndEvenNumbers(allNums));
//Testing
OddAndEven obj = new OddAndEven();
System.out.println("Testing n = 5");
obj.oddAndEvenNumbers(5);
System.out.println("Testing n = 99");
obj.oddAndEvenNumbers(99);
I know my problem is at the part when its supposed to take the string apart and evaluate the individual numbers, but I don't know what to do. (I've also tried substring() & trim()) Also I have not learned how to use arrays yet, so that is why I did not try to use an array.
I think you can make it that way:
int x = 20;
StringBuilder evenNumberStringBuilder = new StringBuilder();
StringBuilder oddNumberStringBuilder = new StringBuilder();
for(int i =0 ; i<x+1; i++){
if(i % 2 == 0)evenNumberStringBuilder.append(i);
else oddNumberStringBuilder.append(i);
}
System.out.println(evenNumberStringBuilder);
System.out.println(oddNumberStringBuilder);
Output:
02468101214161820
135791113151719
you are already taking the input as integer, so don't work with strings. I recommend that to use this loop;
Scanner number = new Scanner(System.in);
System.out.print("Even Numbers: ");
for (int i = 0; i <= number; i=i+2) {
System.out.print(i);
}
System.out.println("");
System.out.print("Odd Numbers: ");
for (int i = 1; i <= number; i=i+2) {
System.out.print(i);
}
You can simply evaluate numbers while storing them in an allnumbers string, here's a functioning code:
int x = 23; //user input
String s=""; //contains all numbers from 0 to userinput
String odd =""; //contains all odd numbers from 0 to userinput
String even = ""; //contains all even numbers from 0 to userinput
for(int i = 0 ; i< x+1 ; i++){
s += i;
if(i%2==0) //if i is an even number
even += i;
else //if i is an odd number
odd += i;
}
System.out.println(s); //displaying all numbers from 0 to user input
System.out.println(odd); //displaying odd numbers from 0 to user input
System.out.println(even); //displaying even numbers from 0 to user input

Counting Upper and Lower characters in a string using an array

I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'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'};
int Alph [] = {'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("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}

Categories

Resources