So I am trying to make a hang man game using a website that returns random word. I'm using that random word for the hangman game.
What I am stuck on is validating a guess the user makes. Here is the code, I am just putting everything in main first then making separate methods to do the work for me after this works.
public static void main(String[] args) throws Exception {
randomWord = TestingStuff.sendGet();
int totalTries = 1;
char[] guesses = new char[26];
int length = randomWord.length();
Scanner console = new Scanner(System.in);
System.out.print("* * * * * * * * * * * * * * *"
+ "\n* Welcome to Hangman! *"
+ "\n* * * * * * * * * * * * * * *");
System.out.println("\nYou get 10 tries to guess the word by entering in letters!\n");
System.out.println(randomWord);
/*
Cycles through the array based on tries to find letter
*/
while (totalTries <= 10) {
System.out.print("Try #" + totalTries);
System.out.print("\nWhat is your guess? ");
String guess = console.next();
char finalGuess = guess.charAt(0);
guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array
for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (finalGuess != guesses[i]) {
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess.equals(randomWord.charAt(j))) {
}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
}
}
What I am stuck on is inside of the while loop where it says:
for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (finalGuess != guesses[i]) {
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess.equals(randomWord.charAt(j))) {
}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
It is giving me an error saying "char cannot be dereferenced". Am I missing something here?
finalGuess is a primitive char - you can't use methods, such as equals on it. You could just compare the two chars using the == operator:
if (finalGuess == randomWord.charAt(j)) {
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
how do I pair the student array with the grade array? When I find the highest grade the corresponding student should also show, and same with the lowest graded student. I cant figure out how to make this program perform as such with two separate arrays.
import java.util.Scanner;
public class Asm7 {
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.println("How many students do you have?: ");
int AMOUNT = 0;
AMOUNT = Scan.nextInt();
String[] STUDENT = new String [AMOUNT];
int COUNTER = 0;
int GRADE [] = new int [AMOUNT];
if (AMOUNT <= 0) {
System.out.println("Invalid student amount");
}
else {
for(int i = 0; i < AMOUNT; i++){
System.out.println("Enter student's first name: " + (i+1));
STUDENT[i] = Scan.next();
System.out.println("Enter student's grade in order added: ");
GRADE[i] = Scan.nextInt();
}
for(int i = 0; i < AMOUNT; i++){
System.out.println(STUDENT[i] + " received the final grade of " + GRADE[i]);}
System.out.println();
int [] Results = MinMax(GRADE);
System.out.println("The highest grade in the class was " + Results[1]);
System.out.println("The lowest grade in the class was "+ Results[0]);
}}
public static int[] MinMax(int[] value) {
int[] Result = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
for (int i : value) {
Result[0] = i < Result[0] ? i : Result[0];
Result[1] = i > Result[1] ? i : Result[1];
}
return Result;
}
}
Your while loop validation for number of students is a little late. You want to do this before you declare and initialize your arrays. However, the fact that the while loop was actually used in an attempt towards some form of validation is a really good sign. It's more than most new programmers tend to do. All input should be validated and provide a User the opportunity to supply a correct solution. This can only lead to a smoother, trouble free application and a much better experience for the User. Take a look at this while loop which is in your code:
while (amount < 0) {
System.out.println("Invalid student amount");
}
What is going to happen if the User supplies -1 (this is a valid integer value as is +1)? That's right...your application will end up in an infinite loop spitting out Invalid student amount to the Console Window. Your validation scheme should encompass the entire prompt and then the means to exit it should be more logically defined. With a while loop the best exit is done through its conditional statement, if the condition is false then exit the loop, for example:
Scanner scan = new Scanner(System.in);
// Number Of Students...
String inputString = "";
while (inputString.isEmpty()) {
System.out.print("How many students do you have?: --> ");
inputString = scan.nextLine().trim();
/* Is the supplied Number Of Students valid and within
range (1 to 50 inclusive)? */
if (!inputString.matches("\\d+") || Integer.valueOf(inputString) < 1
|| Integer.valueOf(inputString) > 50) {
// No...
System.err.println("Invalid entry (" + inputString + ") for Student "
+ "amount! Try again...");
inputString = ""; // Empty inputString so we loop again.
System.out.println();
}
}
// Valid amount provided.
int amount = Integer.valueOf(inputString);
String[] student = new String[amount];
int grade[] = new int[amount];
Right away you will notice some obvious changes here. The entire How many students do you have? prompt is contained within a while loop block. If the User does not supply a valid response then that User is asked to try again. The student and grade parallel arrays are declared and initialized only after a valid response for the number of students is provided.
You will also notice that the while loop condition doesn't rely on a integer value but instead it relies on actual string content (regardless of what it is) instead. If the variable is empty ("") then loop again. This is because the Scanner#nextLine() method is used to collect the Users input instead of the Scanner#nextInt() method. The prompt still expects an integer value to be supplied, just a string representation of an integer value and this is validated using the String#matches() method along with a small Regular Expression (regex).
I personally prefer to use the Scanner#nextLine() method for a number of reasons. I personally find it more flexible especially if you want to accept both Alpha and Numerical input from a single prompt. If the prompt above stated:
How many students do you have? (q to quit)
you would just need to add another if statement above the numerical validation code to see if 'q' or 'Q' was supplied, for example:
// If either q or Q is entered then quit application.
if (amountString.matches("[qQ]")) {
System.out.println("Bye-Bye");
System.exit(0);
}
Also, with a good expression passed to the matches() method, there is no need to trap exceptions in order to carry out validations, not that there is anything wrong with this, many people do it, I especially don't however when I have no need to do so.
Side Note: I'm going to state the obvious here and I'm sure you've heard it a hundred times before and you're sick of hearing it but I'm going to tell you again:
Your class methods should start with a lowercase letter (see Java Naming
Conventions).
I know you don't hear the compiler complaining but it does make it a
little more difficult (at times) to read the code. Everyone that reads
your code will appreciate you for it.
Because the student and grade arrays are parallel arrays you would want the minGrade() and maxGrade() methods to return a specific array index value to either the lowest or highest grade so that a referential relationship can be made toward the student that contains that specific grade determined. So, this would be far more useful:
public static int minGrade(int[] arr, int size) {
// Initialize min to have the highest possible value.
int min = Integer.MAX_VALUE;
int returnableIndex = -1;
// loop to find lowest grade in array
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
public static int maxGrade(int[] arr, int size) {
int max = Integer.MIN_VALUE;
int returnableIndex = -1;
// loop to find highest grade in array
for (int i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
With everything in play your code might look like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Number Of Students...
String amountString = "";
while (amountString.isEmpty()) {
System.out.print("How many students do you have?: --> ");
amountString = scan.nextLine().trim();
// Is the supplied Number Of Students valid and within
// range (1 to 50 inclusive)?
if (!amountString.matches("\\d+") || Integer.valueOf(amountString) < 1
|| Integer.valueOf(amountString) > 50) {
// No...
System.err.println("Invalid entry (" + amountString + ") for Student "
+ "amount! Try again...");
amountString = ""; // Empty inputString so we loop again.
System.out.println();
}
}
// Valid amount provided.
int amount = Integer.valueOf(amountString);
// Declare and initialize parallel arrays
String[] student = new String[amount];
int grade[] = new int[amount];
// Student Names and Grade...
for (int i = 0; i < amount; i++) {
// Student Name...
String name = "";
while (name.isEmpty()) {
System.out.print("Enter student #" + (i + 1) + " name: --> ");
name = scan.nextLine().trim();
/* Is the name valid (contains upper or lower case letters from
A-Z and a single whitespaces separating first and last name?
Whitespace and last name is optional. */
if (!name.matches("(?i)([a-z]+)(\\s{1})?([a-z]+)?")) {
// No..
System.err.println("Invalid Student #" + (i + 1) + " name ("
+ name + ")! Try Again...");
System.out.println();
name = ""; // Empty name so we loop again.
}
}
// Valid Student name provided...
student[i] = name;
// Student Grade...
String gradeString = "";
while (gradeString.isEmpty()) {
System.out.print("Enter student #" + (i + 1) + " grade: --> ");
gradeString = scan.nextLine().trim();
// Is the supplied grade valid and within range (0 to 100 inclusive)?
if (!gradeString.matches("\\d+")
|| Integer.valueOf(gradeString) < 0
|| Integer.valueOf(gradeString) > 100) {
// No...
System.err.println("Invalid entry (" + gradeString + ") for "
+ "Student #" + (i + 1) + " grade! Try again...");
gradeString = "";
System.out.println();
}
}
// Valid Student grade provided...
grade[i] = Integer.valueOf(gradeString);
}
// Display everyone's grade
System.out.println();
for (int i = 0; i < amount; i++) {
System.out.println(student[i] + " received the final grade of " + grade[i]);
}
System.out.println();
//Display who is highest and lowest...
int index = maxGrade(grade, amount);
System.out.println("The highest grade in the class was by '" + student[index]
+ "' with a grade of: " + grade[index]);
index = minGrade(grade, amount);
System.out.println("The lowest grade in the class was by '" + student[index]
+ "' with a grade of: " + grade[index]);
}
public static int minGrade(int[] arr, int size) {
// Initialize min to have the highest possible value.
int min = Integer.MAX_VALUE;
int returnableIndex = -1;
// loop to find lowest grade in array
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
public static int maxGrade(int[] arr, int size) {
int max = Integer.MIN_VALUE;
int returnableIndex = -1;
// loop to find highest grade in array
for (int i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
If the data are not sorted, it would be better to find both min and max grades in the same loop, after printing the students and their grades.
Then no loop is needed to print min and max grades:
for (int i = 0; i < amount; i++) {
System.out.println(student[i] + " received the final grade of " + grade[i]);
}
int min = grade[0];
int max = grade[0];
for (int i = 1; i < amount; i++) {
if (grade[i] < min) {
min = grade[i];
} else if (grade[i] > max) {
max = grade[i];
}
}
System.out.println("The highest grade in the class was " + max);
System.out.println("The lowest grade in the class was " + min);
If the index of min/max is sought, it would be possible to print the name of the students who get the min and max grades.
public static void main(String[] args) {
int[] grades = new int[]{50, 51, 52, 50, 60, 22, 53, 70, 60, 94, 56, 41};
int[] result = getMinMax(grades);
System.out.println("Min: " + result[0] + ", Max: " + result[1]);
}
public static int[] getMinMax(int[] values) {
int[] result = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
for (int i : values) {
result[0] = i < result[0] ? i : result[0];
result[1] = i > result[1] ? i : result[1];
}
return result;
}
You'll need to handle the case of int[] values being null or empty. You can decide that (Throw an exception, return null... or whatever)
I dont want it to say attempts remaining -1, i want it saying the 2 attempts after the 1st attempt is done, and it repeats the prompt of the user input.
I already tried looking on how to correctly do the 3 attempt thing, but for some reason, my program is not successfully doing it.
import java.util.*;
import java.util.Collections;
public class Anagrams extends ShuffleWord{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
int score1 = 0;
int score2 = 0;
int score3 = 0;
int attempts = 3;
Random r = new Random();
System.out.println("Your face looks familiar, what is your name?");
String name = input.nextLine();
System.out.println("Welcome " + name + " to Anagrams, a game where the word is shuffled and you have to unscramble the word correctly!");
System.out.println(" Please select a difficulty " + name + ", 1 being easy, 2 being normal, and 3 being hard.");
int difficulty = input.nextInt();
switch (difficulty) {
case 1:
// 6 letter words
final String[] wordlist1 = {"string", "switch", "system" , "static" , "public" , "python" , "method" };
String word1 = wordlist1[r.nextInt(wordlist1.length)];
System.out.println("Your scrambled word is:" + shuffle(word1));
System.out.println("Please type the word");
String thisisjustsoitworks1 = input.nextLine();
String userword1 = "";
final List<String> wordy1 = Arrays.asList(wordlist1);
while (attempts -- > 0 && !wordy1.contains(userword1));
{
userword1 = input.nextLine();
if (wordy1.contains(userword1))
{
score1 += 50;
System.out.println(name + ", Your current score is:" + score1);
}
else
{
System.out.println("Incorrect. Number of attempts remaining:" + attempts);
}
}
break;
case 2:
// 15-16 letterwords
final String[] wordlist2 = {"computerscience" , "primitivedatatype" , "booleandatatype" ,};
String word2 = wordlist2[r.nextInt(wordlist2.length)];
System.out.println("Your scrambled word is:" + shuffle(word2));
System.out.println("Please type the word");
String thisisjustsoitworks2= input.nextLine();
String userword2 = input.nextLine();
List<String> wordy2 = Arrays.asList(wordlist2);
if (wordy2.contains(userword2))
{
score2 += 150;
System.out.println(name +", Your current score is:" + score2);
}
else
{
System.out.println("game over");
}
break;
case 3:
final String[] wordlist3 = {"objectorientatedprogramming" , "primitivedatatype" , "booleandatatype" ,};
String word3 = wordlist3[r.nextInt(wordlist3.length)];
System.out.println("Your scrambled word is:" + shuffle(word3));
System.out.println("Please type the word");
String thisisjustsoitworks3 = input.nextLine();
String userword3 = input.nextLine();
List<String> wordy3 = Arrays.asList(wordlist3);
if (wordy3.contains(userword3))
{
score3 += 300;
System.out.println (name + ", you gained" + score3 + "points, your total score is;" + score3);
}
else
{
System.out.println("game over");
}
break;
default:
System.out.println("Invalid Difficulty");
}
}
}
Suffle method code
import java.util.concurrent.ThreadLocalRandom;
/* Java program to shuffle a word randomly5
*/
public class ShuffleWord {
//public static void main(String[] args) {
// ShuffleWord sw = new ShuffleWord();
//
// String word = "Hello";
//
// String shuffled = sw.shuffle(word);
//
// System.out.println("Original word:"+word);
//
// System.out.println("Shuffled word:"+shuffled);
/*
* Shuffles a given word. Randomly swaps characters 10 times.
* #param word
* #return
*/
public static String shuffle(String word) {
String shuffledWord = word; // start with original
int wordSize = word.length();
int shuffleCount = 10; // let us randomly shuffle letters 10 times
for(int i=0;i<shuffleCount;i++) {
//swap letters in two indexes
int position1 = ThreadLocalRandom.current().nextInt(0, wordSize);
int position2 = ThreadLocalRandom.current().nextInt(0, wordSize);
shuffledWord = swapCharacters(shuffledWord,position1,position2);
}
return shuffledWord;
}
/**
* Swaps characters in a string using the given character positions
* #param shuffledWord
* #param position1
* #param position2
* #return
*/
private static String swapCharacters(String shuffledWord, int position1, int position2) {
char[] charArray = shuffledWord.toCharArray();
// Replace with a "swap" function, if desired:
char temp = charArray[position1];
charArray[position1] = charArray[position2];
charArray[position2] = temp;
return new String(charArray);
}
}
Output
Your face looks familiar, what is your name?
thomas
Welcome thomas to Anagrams, a game where the word is shuffled and you have to unscramble the word correctly!
Please select a difficulty thomas, 1 being easy, 2 being normal, and 3 being hard.
1
Your scrambled word is:static
Please type the word
a
Incorrect. Number of attempts remaining:-1
attempts remaining -1 is getting printed because of ; at the end of while loop(case 1:) in your code.
while (attempts -- > 0 && !wordy1.contains(userword1));
Due to this, attempts is getting decremented to -1, and after that program is taking user input.
I'm trying to make a histogram from an arrayList containing student grades. I have already made a grade breakdown as shown here:
/**
* Returns a simple, 5-element array with the counts for each of the letter grades,
* (A, B, C, D, and F), based on the 10-point scale
* #return 5-element array
*/
private int[] calculateGradingBreakdown() {
int[] breakdown;
breakdown = new int[7];
for (Student kids: this.students) {
int grade = kids.getNumericGrade();
if (grade >= 90) {
breakdown[0] += 1;
} else if (grade >= 80) {
breakdown[1] += 1;
} else if (grade >= 70) {
breakdown[2] += 1;
} else if (grade >= 60) {
breakdown[3] += 1;
} else {
breakdown[4] += 1;
}
}
return breakdown;
}
/**
* Returns a string that lists the grade letter and the count of students
* receiving the grade on the roster
* #return grade breakdown
*/
public String getGradeBreakdown() {
String gradeBreakdown = null;
int[] breakdown = this.calculateGradingBreakdown();
gradeBreakdown = ("A: " + breakdown[0] + "\nB: " + breakdown[1] + "\nC: " + breakdown[2]
+ "\nD: " + breakdown[3] + "\nF: " + breakdown[4]);
return gradeBreakdown;
}
The code I have for the histogram has changed a few times, but needs to include the methods listed below. I have left my current code in, but am struggling as to how to get the histogram to work as listed.
/**
* Accepts a number of stars (*) to be created, creates a String with that
* number of *'s side-by-side, and then returns that string.
*/
private String makeStarRow(int number) {
int[] breakdown = this.calculateGradingBreakdown();
number = breakdown[];
String stars =
}
/**
* Returns a string holding a horizontal histogram of *'s
*/
public String getGradeHistogram() {
String gradeHistogram = null;
int[] breakdown = this.calculateGradingBreakdown();
gradeHistogram = (this.makeStarRow(breakdown[0]));
gradeHistogram += (this.makeStarRow(breakdown[1]));
gradeHistogram += (this.makeStarRow(breakdown[2]));
gradeHistogram += (this.makeStarRow(breakdown[3]));
gradeHistogram += (this.makeStarRow(breakdown[4]));
return gradeHistogram;
}
The output should look like this to end for the grade breakdown and histogram (with the numbers being according to the input in another class):
A: 2
B: 2
C: 2
D: 0
F: 1
**
**
**
*
For your interest and reference, here's a solution using Java 8 streams:
void printHistogram(List<Integer> scores) {
scores.stream().collect(Collectors.groupingBy(n -> n < 60 ? 5 : n / 10));
.entrySet().stream().sorted(Map.Entry::comparingByKey)
.map(entry -> entry.getValue().size());
.map(size -> Stream.iterate(() -> "*").limit(size).collect(Collectors.joining()))
.forEach(System.out::println);
}
One of the ways to create the string of repeating symbols is to use Arrays.fill:
private String makeStarRow(int number) {
char[] starChars = new char[number];
Arrays.fill(starChars, '*');
String stars = new String(starChars) + '\n';
return stars;
}
Note that according to the getGradeHistogram method it's likely that you need a '\n' appended to the end of the stars String.
Thanks for the help guys. I actually got a working solution:
/**
* Accepts a number of stars (*) to be created, creates a String with that
* number of *'s side-by-side, and then returns that string.
*/
private String makeStarRow(int number) {
while (number > 0) {
System.out.print("*");
number--;
}
if (number < 1) {
System.out.println();
}
return null;
}
/**
* Returns a string holding a horizontal histogram of *'s
* #return histogram
*/
public String getGradeHistogram() {
int[] histogram = this.calculateGradingBreakdown();
for (int xi = 0; xi < this.students.size(); xi++) {
int meh = histogram[xi];
this.makeStarRow(meh);
}
return "";
}
It prints out what I was looking for. Hopefully this helps someone in the future.
A: 2
B: 2
C: 2
D: 0
F: 1
**
**
**
*
My program reads in values from a file and uses a recursive method to print patterns of asterisks based on those values. I'm just having a problem getting everything to line up properly.
The output is supposed to look like this:
*
* *
* * *
* *
*
Regarding the format of the output, the directions are:
"Note that the pattern is aligned symmetrically (vertically) about the center line. The pattern should be aligned symmetrically on each line (horizontally) as well- hint: use the line value to help space."
But my output looks like this:
*
* *
* * *
* *
*
The code I'm using to get this pattern:
public static void makePattern(int thisRow, int num) {
if(thisRow >= num) {
for(int i = 0; i < num; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
}
else {
for(int i = 0; i < thisRow; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
makePattern(thisRow + 1, num);
for(int i = 0; i < thisRow; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
}
}
Also my main method:
import java.util.Scanner;
import java.io.*;
public class Program3 {
public static void main(String[] args) throws Exception {
int num = 0;
int thisRow = 1;
java.io.File file = new java.io.File("../instr/prog3.dat");
Scanner fin = new Scanner(file);
while(fin.hasNext()) {
num = fin.nextInt();
if(num >=0 && num <= 25)
makePattern(thisRow, num);
System.out.println();
}
fin.close();
}
Any suggestions on how to edit my code to make my output appear like the example pattern I included?
Let's analyse the output first!!
First step is to analyse the output
Conclusions:
The total number of characters on every line is always n (=3)
Number of Spaces has the following pattern:
1st line 3 - 1 spaces
2nd line 3 - 2 spaces
3rd line 3 - 3 spaces
4th line 4 - 3 spaces
5th line 5 - 3 spaces
So
if(num < thisRow) {
numberOfSpaces = thisRow - num;
} else {
numberOfSpaces = num - thisRow;
}
Number of Stars is always [n - the number of spaces]
So
int numberOfStars = num - numberOfSpaces;
And the recursion should end on the 6th line, i.e. when current line number is n*2
So the return condition in your recursive method should be
if(thisRow == num * 2)
return;
Final Code : Putting the peices together
When we put the peices together, we get:
public static void makePattern(int thisRow, int num) {
//the termination condition
if(thisRow == num * 2)
return;
//the number of spaces
int numberOfSpaces = 0;
if(num < thisRow) {
numberOfSpaces = thisRow - num;
} else {
numberOfSpaces = num - thisRow;
}
//the number of stars
int numberOfStars = num - numberOfSpaces;
//compose the string before printing it
StringBuffer outputBuffer = new StringBuffer(num);
for (int i = 0; i < numberOfSpaces; i++){
outputBuffer.append(" ");
}
for (int i = 0; i < numberOfStars; i++){
outputBuffer.append("* ");
}
//print the string
System.out.println(outputBuffer.toString());
//recursion
makePattern(thisRow + 1, num);
}
This is code for printing diamond shaped pattern using recursion technique.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class patternRecursion {
static int n,k;
public static void main(String[] args) throws IOException{
try(Scanner s = new Scanner(System.in)){
n=Integer.parseInt(reader.readLine());
k=n-1;
printPattern(n);
}
}
public static void printChar(int m,char c){
if(m==0) return;
try{
printChar(m-1,c);
System.out.print(c);
}catch(StackOverflowError s){return;}
}
public static void printPattern(int m){
if(m==0){
return ;
}else{
printChar(m-1,' ');
printChar(n-m,'#');
printChar(n-m+1,'#');
System.out.println();
printPattern(m-1);
printChar(m,' ');
printChar(k-m,'#');
printChar(k-m+1,'#');
System.out.println();
}
}
}
I have a program that I have been working on for quite awhile now. I am need to make a program that solves a user specified summation puzzle through backtracking.
The user enters three separate strings, the first two strings added together should equal the third string.
example:
java + next = scala
4656 + 7980 = 12636
I believe I am on the right track, but I need to take the index's of each value on the <Character> ArrayList and have them sum to a number less than 20,000. How would I go about doing this?
below is the code I have so far:
import java.util.*;
public class SummationPuzzle
{
public static ArrayList<Character> fsList = new ArrayList<Character>();
public static ArrayList<Character> lastW = new ArrayList<Character>();
public static ArrayList<Character> finaList = new ArrayList<Character>();
/**
* Reads in 3 words entered by user and converts the first two string into a single <Character> ArrayList
* takes the third string entered and converts it into it's own <Character>ArrayList
* #param firstW
* #param secondW
* #param thirdW
*/
public static void convertStr(String firstW, String secondW, String thirdW)
{
String combined = firstW + secondW;
for(int i = 0; i< combined.length(); i++)
{
fsList.add(combined.charAt(i));
}
for(int j = 0; j< thirdW.length(); j++)
{
lastW.add(thirdW.charAt(j));
}
System.out.println( fsList +" "+lastW);
swapAdd(fsList, lastW);
//feeds the resulting lists into the swapAdd method
}
/**#param
* This method Swaps the first char of fsList with the char at fsList[1]to make sure it matches the char at lastW[1]
* #param fsList
* #param lastW
*/
public static void swapAdd(ArrayList<Character> fsList, ArrayList<Character> lastW)
{
Collections.swap(lastW, 0,1);
System.out.println(lastW + " lastW swap first char");
char temp = lastW.get(1);
int j= 0;
System.out.println(fsList+ " before swap");
if(!fsList.get(1).equals(temp) && fsList.contains(temp))
{
j = fsList.indexOf(temp);
Collections.swap(fsList,1,j);
}
System.out.println(fsList+ " after swap");
removeDuplicate(fsList, lastW);
}
/**
* Combines two <Character> ArrayList into a one <Character> ArrayList with single instances of the char
* #param fsList
* #param lastW
*/
public static void removeDuplicate(ArrayList<Character> fsList, ArrayList<Character> lastW)
{
ArrayList<Character> tempList = new ArrayList<Character>();
tempList.addAll(fsList);
tempList.addAll(lastW);
for(char dupLetter : tempList)
{
if(!finaList.contains(dupLetter))
{
finaList.add(dupLetter);
}
}
System.out.println(finaList + "This is the list with duplicates removed");
System.out.println(lastW);
}
//main method
public static void main(String[] args)
{
//Receive user input
Scanner userIn = new Scanner(System.in);
System.out.println("Please enter your first word");
String firstW = userIn.next().trim();
System.out.println("Please enter your Second word");
String secondW = userIn.next().trim();
System.out.println("Please enter your Third word");
String thirdW = userIn.next().trim();
//print the summation puzzle
System.out.println(firstW+ " + " + secondW + " = "+ thirdW);
convertStr(firstW, secondW, thirdW);
}
}