How to sum the index's of a <Character> ArrayList - java

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);
}
}

Related

How would I make this so the while/else statement correctly repeats itself when the user input is incorrect?

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.

How do I reroll the dice in Yahtzee

I am I very beginner programmer and I am stuck on how I can reroll the dice in my program. The project that I am working on is Yahtzee. In Yahtzee, you roll 5 dice and you can choose what dice to reroll ('r') and what dice to keep ('k'). In all, I am trying to roll 2 times.
package yahtzee1;
import java.util.Scanner;
public class Yahtzee1 {
/**
* Allows the get information from the user like to keep or reroll
* #param prompt
* #return
*/
public static char getcharFromUser(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
char c = sc.next().charAt(0);
return c;
}
/**
* generate 5 random numbers from 1 to 6, inclusive
* #param dice array to store the numbers
*/
public static void roll(int[] dice) {
for (int i = 0; i < 5; i++) {
dice[i] = (int) (Math.random() * 6 + 1);
}
}
/**
* generate 5 random numbers from 1 to 6, inclusive
*
* #param dice array to store the numbers
*/
public static void printDice(int[] dice) {
for (int i = 0; i < 5; i++) {
System.out.print(dice[i]);
}
}
/**
* After the 5 dice are "rolled" user picks which dice to re-roll or keep
* #param dice
* #param option
*/
public static void reRoll(int[] dice, String option) {
//help here
}
/**
*
* #param dice
*/
public static void playRound(int [] dice){
for (int i = 0; i < 2;i++){
reRoll(dice, option);
roll(dice);
printDice(dice);
}
}
/**
* play Yahtzee
* #param args the command line arguments
*/
public static void main(String[] args) {
int[] dice = new int[6];
playRound(dice);
}
}
the section in my code where I need help is in the method reRoll.
You can do something like this:
public static void reRoll(int[] dice, String option) {
//Change the split parameter to whatever you need the delimiter to be
for(String numString: option.split(" ")){
int die = Integer.parseInt(numString);
dice[die-1] = (int) (Math.random() * 6 + 1);
}
}
public static void playRound(int [] dice){
roll(dice);
printDice(dice);
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 2;i++){
System.out.print("Enter dice to reroll: ");
String option = sc.nextLine();
reRoll(dice, option);
printDice(dice);
}
sc.close();
}

Java - Hangman Game - trouble with charAt on StringBuffer variable

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)) {

Counting the amount of Whitespace in String

OK, now that I have change the public static String to public static int the last function does not print out.
Thank you all for you're help.
Here is the full program. The last function does not seem to print.
import java.lang.String;
import java.util.Scanner;
public class stringFuncts{
/**
* #param <String> <str> <Takes in a String and reverses it.>
* #return <rev> <returns the reversed string>
*/
public static String reverseString (String str){
String rev = "";
int length = str.length();
for ( int i = length - 1 ; i >= 0 ; i-- ){
rev = rev + str.charAt(i);
}
return rev;
}
/**
* #param <int> <n> <It will sum up the odds of a set number>
* #return <results> <Will print out the total of the odds values>
*/
public static int sumOfOdds (int n){
int results = 0;
for(int i = 1; i <= n*2; i += 2){
results = results + i;
}
return results;
}
/**
* #param <int> <blanks> <Will count the amount of whitespace in the phrase>
* #return <numBlanks> <Will return the amount of whitespace found in the String>
*/
public static int numberOfBlanks(String blanks){
int numBlanks = 0;
for(int i = 0; i < blanks.length(); i++) {
if(Character.isWhitespace(blanks.charAt(i)))
numBlanks++;
}
return numBlanks;
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str;
int n = 0;
String blanks;
System.out.println("Enter a string to reverse");
str = input.nextLine();
System.out.println("The reverse output is: " + reverseString(str));
System.out.println("");
System.out.println("Enter a value to sum the odds");
n = input.nextInt();
System.out.println("The sum of the odds " + sumOfOdds(n));
System.out.println("");
System.out.println("Enter a string to find the amount of blanks");
blanks = input.nextLine();
System.out.print("The number od blanks in the string is: " + numberOfBlanks(blanks));
}
}
In your numberOfBlanks() return type is of String data type
change it to int data type
Your function is declared as public static String. You're trying to return a number, so the correct declaration would be public static int.
import java.lang.String;
import java.util.Scanner;
public class stringFuncts{
/**
* #param <String> <str> <Takes in a String and reverses it.>
* #return <rev> <returns the reversed string>
*/
public static String reverseString (String str){
String rev = "";
int length = str.length();
for ( int i = length - 1 ; i >= 0 ; i-- ){
rev = rev + str.charAt(i);
}
return rev;
}
/**
* #param <int> <n> <It will sum up the odds of a set number>
* #return <results> <Will print out the total of the odds values>
*/
public static int sumOfOdds (int n){
int results = 0;
for(int i = 1; i <= n*2; i += 2){
results = results + i;
}
return results;
}
/**
* #param <int> <blanks> <Will count the amount of whitespace in the phrase>
* #return <numBlanks> <Will return the amount of whitespace found in the String>
*/
public static int numberOfBlanks(String blanks){
int numBlanks = 0;
for(int i = 0; i < blanks.length(); i++) {
if(Character.isWhitespace(blanks.charAt(i)))
numBlanks++;
}
return numBlanks;
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str;
int n = 0;
String blanks;
System.out.println("Enter a string to reverse");
str = input.nextLine();
System.out.println("The reverse output is: " + reverseString(str));
System.out.println("");
System.out.println("Enter a value to sum the odds");
n = input.nextInt();
System.out.println("The sum of the odds " + sumOfOdds(n));
System.out.println("");
input.nextLine();
System.out.println("Enter a string to find the amount of blanks");
blanks = input.nextLine();
System.out.print("The number od blanks in the string is: " + numberOfBlanks(blanks));
}
}
Output:
Enter a string to reverse
this
The reverse output is: siht
Enter a value to sum the odds
3
The sum of the odds 9
Enter a string to find the amount of blanks
this is spartan!
The number od blanks in the string is: 2

Basic Java questions Scanning

This is very basic java that i'm struggling with n00b style. it just prints out this
Please enter '.' when you want to calculate
1 2 3
.
Numbers are 1 2 3
The Sum is0The Product is1
when it is supposed to calculate the sum and product of those consecutive numbers. something is wrong id appreciate any help!
main method
import java.util.*;
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to calculate");
Scanner keyboard = new Scanner(System.in);
String scannedString = keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
while(!keyboard.nextLine().equals("."))
{
scanz.set(scannedString);
}
keyboard.close();
System.out.println("Numbers are"+scannedString);
scanz.printState();
}
}
Class Scanning
public class Scanning {
int num;
int sum;
int product;
String userInput;
public Scanning(String userInput)
{
num=0;
sum=0;
product=1;
this.userInput=userInput;
}
public void set(String userInput)
{
for(int index=0; index<userInput.length(); index++)
{
if(Character.isDigit(userInput.charAt(index))==true)
{
num=userInput.charAt(index);
sum+=num;
product*=num;
}
else
{
index++;
}
}
}
public void printState()
{
System.out.println("The Sum is"+sum+"The Product is"+product);
}
}
A few things to look at:
We know keyboard.nextLine() gets the input from the console, but where are you checking it's validity (more importantly, when do you check it?). Are you looking at all input or just the last line?
isDigit will return true if the passed in character is a number. Do you want to operate on numbers or characters in your for loop?
(a side note, What happens if I enter "1 10" in the console?)
A for loop will automatically increment its index at the end of a loop, so an additional ++ is unnecessary
You might find this helful in case you just need the sum and product values of a user entered
values.
public class ProductSumCalculator{
private static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
getInputs();
calculateSumAndProduct();
}
private static void getInputs() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter numbers or ctrl+z to end inputs");
while(scanner.hasNext()){
numbers.add(scanner.nextInt());
}
}
private static void calculateSumAndProduct() {
Iterator<Integer> iterator = numbers.iterator();
int sum=0;
int product=1;
int nextVal;
while(iterator.hasNext()){
nextVal = iterator.next();
sum+=nextVal;
product*=nextVal;
}
System.out.println("Value entered are: "+numbers+".\nThe sum is "+
sum+".The product is "+product);
}
}
You can also try this. You can calculate the sum and product of all the int from your string line input like this:
import java.util.Scanner;
public class Scanning {
/*
* This method returns the integer. If while
* conversion an Exception is thrown it returns
* null. Otherwise the integer.
*/
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
/*
* Next String line is scanned. It is split by space.
* Stores String tokens in an String array from one String variable.
* Then passed to tryParse() class method. null or auto Boxed Integer
* is returned accordingly. It is auto unboxed from Integer
* object to int variable. Then sum and product is calculated and
* the final result is printed on the console Or Integrated
* Development Environment.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String strInts = keyboard.nextLine();
String[] splits = strInts.split("\\s+");
int i = 0;
Integer anInteger = null;
int total = 0;
int product = 1;
while((i < splits.length)) {
anInteger = tryParse(splits[i]);
if(anInteger != null) {
total = total + anInteger;
product = product * anInteger;
}
++i;
}
System.out.println("The sum is: " + total);
System.out.println("The product is: " + product);
}
}

Categories

Resources