How to return a string? - java

import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
Ok, so this is my code for a hangman game, the only thing I have left to do is to get my program to randomize one of the words, which it should do in the method successfully. But the only problem I'm having is getting the String variable "word" to go back to the main class (there are errors underlining all the "word" variables in the main class).
If I could get help with either this or another way to produce a random word from a list, that would be amazing.

In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.
In your case, you need to do:
public static String getRandomWord() {
switch(new Random().nextInt(5)) {
case 0:
return "Peace";
case 1:
return "Nuts";
// ...
default:
throw new IllegalStateException("Something went wrong!");
}
}
And in main:
// ...
String word = getRandomWord();
int len = word.length();
// ...

You can't modify the caller's reference.
RandomWord(word);
needs to be something like
word = RandomWord(word);
Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like
private static Random rand = new Random();
public static String randomWord() {
String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
return words[rand.nextInt(words.length)];
}
And then call it like
word = randomWord();

Related

Using variables form other classes in java

I am trying to use two int variables from other classes in another class and then add them together into another variable and print the result. When I try this though, I always get a result of zero like the values are not being brought over into the new class and I can't figure out what the problem is.
Here is some example code:
class1
public static int finished = (match2.totalpoints + match3.iq);
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
EDIT: class2
public class match2 {
public static int totalpoints;
int a;
int b;
int c;
int d;
int e;
int f;
String guess;
String group;
String countdown[] = {
"3...",
"2...",
"1...",
""
};
String memorize[] = {
""
};
public match2() throws InterruptedException
{
int x = set2();
int y = set3();
int z = set4();
total(x, y, z);
System.out.println("For the next part of your IQ ASSesment\njust type back the words in CAPSLOCK in CAPSLOCK");
System.out.println("");
match3 n = new match3();
}
public void set1() throws InterruptedException
{
//Scanner s = new Scanner(System.in);
for (int i = 0; i < countdown.length; i++)
{
Thread.sleep(750);
System.out.println(countdown[i]);
}
}
public int set2() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("press ENTER for your first set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
group = "" + a + b + c + d;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(guess.equals(group))
{
System.out.println("nice +1 bruh");
rv = 1;
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set3() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your next set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f;
System.out.println(group);
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("good");
}
else if(!guess.equals(group))
{
System.out.println("almost");
}
return rv;
}
public int set4() throws InterruptedException
{
Random r = new Random();
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("press ENTER for your final set...");
s.nextLine();
set1();
int rv = 0;
a = r.nextInt(9) + 1;
b = r.nextInt(9) + 1;
c = r.nextInt(9) + 1;
d = r.nextInt(9) + 1;
e = r.nextInt(9) + 1;
f = r.nextInt(9) + 1;
group = "" + a + b + c + d + f + e;
System.out.println(group);
System.out.println("");
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
guess = "" + s.nextLine();
if(group.equals(guess))
{
rv = 1;
System.out.println("great");
}
else if(!group.equals(guess))
{
System.out.println("eeeh buzer sound");
}
return rv;
}
public int total(int x, int y, int z)
{
System.out.println("");
int totalpoints = (x + y + z);
if(totalpoints == 3)
{
System.out.println("YOU GOT THEM ALL");
}
if(totalpoints <= 2 && totalpoints >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalpoints));
}
if(totalpoints == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
return totalpoints;
}
}
EDIT: class3
public class match3 {
public static int iq;
String countupdown [] = {
"READY...",
"SET.....",
""
};
String memorize [] = {
""
};
public match3() throws InterruptedException
{
int mem1 = memory1();
int mem2 = memory2();
int mem3 = memory3();
totalMemory(mem1, mem2, mem3);
}
public void methodCountdown() throws InterruptedException
{
for(int i = 0; i < countupdown.length; i++)
{
Thread.sleep(1000);
System.out.println(countupdown[i]);
}
}
public int memory1() throws InterruptedException
{
int rv = 1;
Scanner s = new Scanner(System.in);
System.out.println("Press ENTER when ready");
s.nextLine();
methodCountdown();
String a = word1();
String b = word2();
System.out.println("The " + a + " ate the " + b);
String wordgroup = "" + a + " " + b;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory2() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String c = word3();
System.out.println("The " + a + " drove the " + c);
String wordgroup = "" + a + " " + c;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public int memory3() throws InterruptedException
{
int rv = 0;
Scanner s = new Scanner(System.in);
System.out.println("");
System.out.println("Press ENTER for your next set");
s.nextLine();
methodCountdown();
String a = word1();
String d = word4();
System.out.println("The " + a + " visited the " + d);
String wordgroup = "" + a + " " + d;
for (int i = 0; i < memorize.length; i++)
{
Thread.sleep(1500);
System.out.println(memorize[i]);
}
System.out.println("\n\n\n\n\n\n\n\n\n\n");
String wordguess = "" + s.nextLine();
if(wordgroup.equals(wordguess))
{
System.out.println("awesome cock muncher a match");
rv = 1;
}
else if(!wordgroup.equals(wordguess))
{
System.out.println("nope");
}
return rv;
}
public static String word1()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "DOG";
}
else if(cv == 2)
{
word = "CAT";
}
else if(cv == 3)
{
word = "BIRD";
}
return word;
}
public static String word2()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "FOOD";
}
else if(cv == 2)
{
word = "MUD";
}
else if(cv == 3)
{
word = "GRAINS";
}
return word;
}
public static String word3()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "TRAM";
}
else if(cv == 2)
{
word = "BUS";
}
else if(cv == 3)
{
word = "BICYCLE";
}
return word;
}
public static String word4()
{
String word = "";
Random r = new Random();
int cv = r.nextInt(3) + 1;
if(cv == 1)
{
word = "MALL";
}
else if(cv == 2)
{
word = "PARK";
}
else if(cv == 3)
{
word = "POOL";
}
return word;
}
public void totalMemory(int mem1, int mem2, int mem3)
{
int iq = (mem1 + mem2 + mem3);
System.out.println("");
if(iq == 3)
{
System.out.println("YOU GOT THEM ALL");
}
else if(iq <= 2 || iq >= 1)
{
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
}
else if(iq == 0)
{
System.out.println("HA! YOU MISSED THEM ALL");
}
}
}
total points is a variable from match2 class and iq from match3 class. Any help with any methods I could use to make this happen would be much appreciated. Thank You
Well ... besides the fact you are not following any code convention, Like class names should start with a capital letter and public static final fields (like totalpoints and iq) should be all Uppercase (code conventions, you are not sharring match2 and match3 codes, without it we can't understand what is happening inside those classes.
But you can do a simple test and assign a value to match2.totalpoints and match3.iq and you are going to see the summing of these two values being printed by the last system.out you put.
good luck and good Java studies!
Are the int variables you're trying to use inside child classes of your main parent class? Did you extend the child classes in your main parent class?
Class #1:
public int firstVar(int someNum) {
//code here
return someNum;
}
Class #2:
public int secondVar(int otherNum) {
//code here
return otherNum;
}
Class #3 Class with Main Method -
public class mainClass extends class#1; //etc
//code here and finally print out the finished number
You could try extending one of the classes that has an int you need into another one of the classes with the other int you need and then just extending that second class into your main, OR you could try completely redefining your classes and just placing all the ints you need into one separate class and then extending that single one into your main.
So I finally got it to work. The problem, I guess, was that I was trying to add together the variables from the other classes(match2 and match3) outside the main function within the class(match1) I was trying to add them together. All I did was move the expression adding the variables together from the top to inside the main function like this:
public static int finished;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println("");
System.out.println("When taking the quiztest you have only two seconds before making each guess");
match2 m = new match2();
finished = (match2.totalpoints + match3.iq);
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + finished + " POINTS");
}
}
Thanks for all the help from everyone.
Smth. like this. You have lot's of code duplication
public class MatchRunner {
public static void main(String... args) throws InterruptedException {
new MatchRunner().start();
}
public void start() throws InterruptedException {
System.out.println("THIS IS YOUR OWN EXCLUSIVE IQ TEST OR MEMORY QUIZ OR WHATEVER....");
System.out.println();
System.out.println("When taking the quiztest you have only two seconds before making each guess");
int totalPoints = new Match2().getTotalPoints();
System.out.println("For the next part of your IQ Assesment");
System.out.println("just type back the words in CAPSLOCK in CAPSLOCK");
int iq = new Match3().getIQ();
System.out.println("THAT MEANS ACCORDING TO YOUR QUIZTEST YOU'VE GOT AN IQ OF " + (totalPoints + iq) + " POINTS");
}
}
public class Match2 {
public int getTotalPoints() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
int totalPoints = calc(scan, "first", "nice +1 try", "almost");
totalPoints += calc(scan, "next", "good", "almost");
totalPoints += calc(scan, "final", "great", "eeeh buzer sound");
printTotalPoints(totalPoints);
return totalPoints;
}
}
private static void countdown() throws InterruptedException {
for (int i = 5; i > 0; i--) {
Thread.sleep(750);
System.out.println(i + "...");
}
}
private static int calc(Scanner scan, String strSet, String strEqual, String strNotEqual) throws InterruptedException {
System.out.println("press ENTER for your " + strSet + " set...");
Random random = new Random();
scan.nextLine();
countdown();
int sum = 0;
for (int i = 0; i < 4; i++)
sum += random.nextInt(9) + 1;
System.out.println(sum);
for (int i = 0; i < 10; i++)
System.out.println();
int guess = scan.nextInt();
System.out.println(guess == sum ? strEqual : strNotEqual);
return guess == sum ? 1 : 0;
}
private static void printTotalPoints(int totalPoints) {
System.out.println();
if (totalPoints == 3)
System.out.println("YOU GOT THEM ALL");
else if (totalPoints <= 2 && totalPoints >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - totalPoints));
else if (totalPoints == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}
public class Match3 {
public int getIQ() throws InterruptedException {
try (Scanner scan = new Scanner(System.in)) {
Random random = new Random();
Supplier<String> getWord1 = () -> getWord(random, "DOG", "CAT", "BIRD");
Supplier<String> getWord2 = () -> getWord(random, "FOOD", "MUD", "GRAINS");
Supplier<String> getWord3 = () -> getWord(random, "TRAM", "BUS", "BICYCLE");
Supplier<String> getWord4 = () -> getWord(random, "MALL", "PARK", "POOL");
int iq = calc(scan, getWord1, getWord2, "ate the");
iq += calc(scan, getWord1, getWord3, "drove the");
iq += calc(scan, getWord1, getWord4, "visited the");
printIq(iq);
return iq;
}
}
private static void countdown() throws InterruptedException {
System.out.println("READY...");
Thread.sleep(1000);
System.out.println("SET...");
Thread.sleep(1000);
}
public int calc(Scanner scan, Supplier<String> wordOne, Supplier<String> wordTwo, String strMsq) throws InterruptedException {
System.out.println("Press ENTER when ready");
scan.nextLine();
countdown();
String a = wordOne.get();
String b = wordTwo.get();
System.out.println("The " + a + ' ' + strMsq + ' ' + b);
String wordGroup = a + ' ' + b;
for (int i = 0; i <= 10; i++)
System.out.println();
String wordGuess = scan.nextLine();
System.out.println(wordGroup.equals(wordGuess) ? "awesome cock muncher a match" : "nope");
return wordGroup.equals(wordGuess) ? 1 : 0;
}
private static String getWord(Random random, String one, String two, String three) {
int cv = random.nextInt(3) + 1;
if (cv == 1)
return one;
if (cv == 2)
return two;
if (cv == 3)
return three;
return "";
}
public void printIq(int iq) {
System.out.println();
if (iq == 3)
System.out.println("YOU GOT THEM ALL");
else if (iq <= 2 || iq >= 1)
System.out.println("YOU MISSED A TOTAL OF " + (3 - iq));
else if (iq == 0)
System.out.println("HA! YOU MISSED THEM ALL");
}
}

Keeping a total score in Java hangman game

import java.util.Scanner;
import javax.swing.JOptionPane;
public class Hangman {
public static void main(String[] args) {
String playAgainMsg = "Would you like to play again?";
String pickCategoryMsg = "You've tried all the words in this category!\nWould you like to choose another category?";
int winCounter = 0, loseCounter = 0, score = 0;
String[] words;
int attempts = 0;
String wordToGuess;
boolean playCategory = true, playGame = true;
int totalCounter = 0, counter;
while (playCategory && playGame)
{
while (playCategory && playGame) {
words = getWords();
counter = 0;
while (playGame && counter < words.length) {
wordToGuess = words[counter++];
if (playHangman(wordToGuess)) {
winCounter++;
System.out.println("You win! You have won " + winCounter + " game(s)." + " You have lost " + loseCounter + " game(s).");
} else {
loseCounter++;
System.out.println("You lose! You have lost " + loseCounter + " game(s)." + " You have won " + winCounter + " game(s).");
}
if (counter < words.length) playGame = askYesNoQuestion(playAgainMsg);
}
if (playGame) playCategory = askYesNoQuestion(pickCategoryMsg);
}
}
}
public static boolean playHangman(String wordToGuess) {
String[] computerWord = new String[wordToGuess.length()];
String[] wordWithDashes = new String[wordToGuess.length()];
for (int i = 0; i < computerWord.length; i++) {
computerWord[i] = wordToGuess.substring(i, i+1);
wordWithDashes[i] = "_";
}
Scanner in = new Scanner(System.in);
int attempts = 0, maxAttempts = 7;
boolean won = false;
int points = 0;
while (attempts < maxAttempts && !won) {
String displayWord = "";
for (String s : wordWithDashes) displayWord += " " + s;
System.out.println("\nWord is:" + displayWord);
System.out.print("\nEnter a letter or guess the whole word: ");
String guess = in.nextLine().toLowerCase();
if (guess.length() > 1 && guess.equals(wordToGuess)) {
won = true;
} else if (wordToGuess.indexOf(guess) != -1) {
boolean dashes = false;
for (int i = 0; i < computerWord.length; i++) {
if (computerWord[i].equals(guess)) wordWithDashes[i] = guess;
else if (wordWithDashes[i].equals("_")) dashes = true;
}
won = !dashes; // If there are no dashes left, the whole word has been guessed
} else {
drawHangmanDiagram(attempts);
System.out.println("You've used " + ++attempts + " out of " + maxAttempts + " attempts.");
}
}
int score = 0;
score = scoreGame(attempts);
System.out.println("Your score is: " + score);
return won;
}
//should take in a failure int from the main method that increments after every failed attempt
public static void drawHangmanDiagram(int failure)
{
if (failure == 0)
System.out.println("\t+--+\n\t| |\n\t|\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 1)
System.out.println("\t+--+\n\t| |\n\t| #\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 2)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 3)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| / \\\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 4)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 5)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| /\n\t|\n\t|\n\t+--");
else if (failure == 6)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| / \\\n\t|\n\t|\n\t+--");
}
// Asks user a yes/no question, ensures valid input
public static boolean askYesNoQuestion(String message) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println(message + " (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
public static boolean askForCategory(int category) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("\nWould you like to play again? (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
// Asks the user to pick a category
public static String[] getWords() {
String[] programming = {"java", "pascal", "python", "javascript", "fortran", "cobol"};
String[] sports = {"gymnastics", "badminton", "athletics", "soccer", "curling", "snooker", "hurling", "gaelic", "football", "darts"};
String[] result = {""};
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("Pick a category:\n1. Programming\n2. Sports");
answer = in.nextLine().toLowerCase();
if (answer.matches("[1-2]")) validAnswer = true;
else System.out.println("Invalid input! Enter the number of the category you want.");
} while (!validAnswer);
int selection = Integer.parseInt(answer);
switch (selection) {
case 1: result = randomOrder(programming); break;
case 2: result = randomOrder(sports); break;
}
return result;
}
// Sorts a String array in random order
public static String[] randomOrder(String[] array) {
int[] order = uniqueRandoms(array.length);
String[] result = new String[array.length];
for (int i = 0; i < order.length; i++) {
result[i] = array[order[i]];
}
return result;
}
// Generates an array of n random numbers from 0 to n-1
public static int[] uniqueRandoms(int n) {
int[] array = new int[n];
int random, duplicateIndex;
for (int i = 0; i < n; ) {
random = (int) (Math.random() * n);
array[i] = random;
for (duplicateIndex = 0; array[duplicateIndex] != random; duplicateIndex++);
if (duplicateIndex == i) i++;
}
return array;
}
public static int scoreGame(int attempts)
{
int score = 0;
switch (attempts)
{
case 0: score = 70; break;
case 1: score = 60; break;
case 2: score = 50; break;
case 3: score = 40; break;
case 4: score = 30; break;
case 5: score = 20; break;
case 6: score = 10; break;
case 7: score = 0; break;
}
return score;
}
}
I have got it working so that it keeps count of the games won and lost, as well as assigning a score based on the amount of attempts/lives saved but I haven't been able to find a way to get it to keep a total score for all of the games played. Each game unfortunately has a seperate score. If anyone can advise me on a way of doing this, it would be greatly appreciated.
Create an int totalScore variable where winCounter, loseCounter and score are defined. Then increment it after each call to scoreGame()
score = scoreGame(attempts);
totalScore += score;
System.out.println("Your score is: " + score);
If you want to permanently save statistics between sessions then it's a whole nother story. You would need to write your scores to a file after each round and then start your program by reading this score file. It's hardly impossible, but requires a bit more code.

NumberFormatException: For input string: "[memorylocation" java

I'm doing an assignment where the goal is to, among other things, to add two large integers. Here is my code, spread out into four files.
Main that we cannot change:
import java.util.*;
import MyUtils.MyUtil;
public class CSCD210HW7
{
public static void main(String [] args)throws Exception
{
int choice;
String num;
LargeInt one, two, three = null;
Scanner kb = new Scanner(System.in);
num = HW7Methods.readNum(kb);
one = new LargeInt(num);
num = HW7Methods.readNum(kb);
two = new LargeInt(num);
do
{
choice = MyUtil.menu(kb);
switch(choice)
{
case 1: System.out.println(one + "\n");
break;
case 2: System.out.println("The value of the LargeInt is: " + two.getValue() + "\n");
break;
case 3: num = HW7Methods.readNum(kb);
one.setValue(num);
break;
case 4: if(one.equals(two))
System.out.println("The LargeInts are equal");
else
System.out.println("The LargeInts are NOT equal");
break;
case 5: three = two.add(one);
System.out.printf("The results of %s added to %s is %s\n", one.getValue(), two.getValue(), three.getValue());
break;
case 6: HW7Methods.displayAscendingOrder(one, two, three);
break;
default: if(two.compareTo(one) < 0)
System.out.printf("LargeInt %s is less than LargeInt %s\n", two.getValue(), one.getValue());
else if(two.compareTo(one) > 0)
System.out.printf("LargeInt %s is greater than LargeInt %s\n", two.getValue(), one.getValue());
else
System.out.printf("LargeInt %s is equal to LargeInt %s\n", two.getValue(), one.getValue());
break;
}// end switch
}while(choice != 8);
}// end main
}// end class
LargeInt Class(Custom Class We Created)
public class LargeInt implements Comparable<LargeInt>
{
private int[]myArray;
private LargeInt()
{
this("0");
}
public LargeInt(final String str)
{
this.myArray = new int[str.length()];
for(int x = 0; x < this.myArray.length; x++)
{
this.myArray[x] = Integer.parseInt(str.charAt(x)+ "");
}
}
public LargeInt add(final LargeInt passedIn)
{
String stringOne = myArray.toString();
String stringTwo = passedIn.myArray.toString();
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
return new LargeInt(""+s);
}
public void setValue(final String arrayString)
{
this.myArray = new int[arrayString.length()];
for(int x = 0; x < myArray.length; x++)
{
this.myArray[x]=arrayString.charAt(x);
}
}
#Override
public int compareTo(LargeInt passedIn)
{
if(passedIn == null)
{
throw new RuntimeException("NullExceptionError");
}
int ewu = 0;
int avs = 0;
if(this.myArray.length != passedIn.myArray.length)
{
return this.myArray.length - passedIn.myArray.length;
}
for(int i = 0; i < this.myArray.length -1; i++)
{
if(this.myArray[i] != passedIn.myArray[i])
{
return this.myArray[i]-passedIn.myArray[i];
}
}
return ewu-avs;
}
public int hashCode()
{
String p = "";
for(int f = 0; f < this.myArray.length; f++)
{
p += myArray[f];
}
return p.hashCode();
}
public String getValue()
{
String h = "";
for(int t = 0; t < this.myArray.length; t++)
{
h += myArray[t];
}
return h;
}
#Override
public boolean equals(Object jbo)
{
if(jbo == null)
{
return false;
}
if(!(jbo instanceof LargeInt))
{
return false;
}
LargeInt k =(LargeInt)jbo;
if(k.myArray.length != this.myArray.length)
{
return false;
}
for(int d = 0; d < this.myArray.length; d++)
{
if(k.myArray[d] != myArray[d])
{
return false;
}
}
return true;
}
#Override
public String toString()
{
String c = "";
for(int q = 0; q < this.myArray.length; q++)
{
c += myArray[q];
}
return "The LargeInt is: " + c;
}
}
HW7Methods File
import java.util.*;
import java.io.*;
public class HW7Methods
{
public static String readNum(Scanner kb)
{
String num = "";
System.out.print("Enter Your Large Int: ");
num = kb.nextLine();
return num;
}
public static void displayAscendingOrder(final LargeInt first, final LargeInt second, final LargeInt third)
{
String highestInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) >= 0)
{
highestInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) >= 0)
{
highestInt = second.getValue();
}
else
{
highestInt = third.getValue();
}
String middleInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) <= 0)
{
middleInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) <= 0)
{
middleInt = second.getValue();
}
else
{
middleInt = third.getValue();
}
String lowestInt;
if(first.compareTo(second) <= 0 && first.compareTo(third) <= 0)
{
lowestInt = first.getValue();
}
else if(second.compareTo(first) <= 0 && second.compareTo(third) <= 0)
{
lowestInt = second.getValue();
}
else
{
lowestInt = third.getValue();
}
System.out.println("The LargeInts in order are: " + lowestInt + ", " + middleInt + ", " + highestInt);
}
}
MyUtil file
package MyUtils;
import java.io.*;
import java.util.Scanner;
public class MyUtil
{
public static int menu(Scanner kb)
{
int userChoice;
System.out.println("1) Print First Int");
System.out.println("2) Print Second Int");
System.out.println("3) Add Different Int");
System.out.println("4) Check If Equal");
System.out.println("5) Add Large Ints");
System.out.println("6) Display In Ascending Order");
System.out.println("7) Compare Ints");
System.out.println("8) Quit");
kb = new Scanner(System.in);
System.out.print("Please Select Your Choice: ");
userChoice = kb.nextInt();
while(userChoice < 1 || userChoice > 8)
{
System.out.print("Invalid Menu Choice. Please Re-Enter: ");
userChoice = kb.nextInt();
}
return userChoice;
}
}
When I go to run this code, it prompts me for two Large Integers like it's supposed to. However, when I choose option 5 to add them, this is what I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[I#55f96302"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at LargeInt.add(LargeInt.java:24)
at CSCD210HW7.main(CSCD210HW7.java:41)
I've never seen that type of error before. Can someone tell me what is going on?
For input string: "[I#55f96302
That is not a "proper" String you are trying to parse here.
This is what an int[] looks like when you call toString() on it.
String stringOne = myArray.toString();
Why do you do that? What is that supposed to do?
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
From the looks of it, you try to handle "large" ints with your LargeInt class by somehow storing them in an array of ints. That's okay, BigInteger also works like that (more or less), but you cannot just do calculations by trying to convert back to int (after all those numbers are too big for int arithmetic to handle, even if you do the string parsing properly).

Palindrome coding

I am trying to create a Palindrome tester in java using a method.. This is what I have so far. It is so close I just can't figure out why it won't say that it IS a palindrome and reverse it.
System.out.println("Fun with Palindromes!!");
Scanner in = new Scanner(System.in);
System.out.println("Enter the potential palindrome (or enter exit to quit): ");
String x = in.nextLine();
while(!x.equals("exit"))
{
String t = x.toLowerCase();
String u = CleanUpString(t);
Boolean wordCheck = checkPalindrome(u);
int wordCount = x.length();
String rev = "";
for(int i = 0; i <x.length(); i++)
{
rev = x.charAt(i)+rev;
}
if(wordCheck == true)
{
System.out.println("The orginal string\"" + u + "\" contains" + wordCount + "characters." );
System.out.println("The converted string\"" + rev + "\"is a palindrome");
}
else if(wordCheck == false)
{
System.out.println("The string \"" + u + "\" contains " + wordCount + " characters");
System.out.println("\"" + rev + "\" is not a palindrome");
}
System.out.println("\nEnter the potential palindrome, or enter exit to quit: ");
x = in.nextLine();
}
}
public static String CleanUpString(String words)
{
words = words.replace(".","");
words = words.replace("," ,"");
words = words.replace(":","");
words = words.replace("!","");
return words;
}
public static boolean checkPalindrome(String baseball)
{
String rev = "";
for(int i = 0; i<baseball.length()-1; i++)
{
rev = baseball.charAt(i) + rev;
}
if(rev.equals(baseball))
return true;
else
return false;
}
}
Here is the code I used to determine whether a string is Palindrome String or not:
private static boolean checkPalindrome(String str){
if (str == null)
return false;
int len = str.length();
for (int i=0;i<len/2 ; i++){
if (str.charAt(i) != str.charAt(len - i - 1)){
return false;
}
}
return true;
}
For reversing strings, you can simply use:
String reverse = new StringBuffer(string).reverse().toString();
Hope these can help you.
Use StringUtils for this
import org.apache.commons.lang.StringUtils;
boolean isPalindrome(String word) {
return StringUtils.reverse(word).equals(word);
}
Here is another option
public class PalindromeTester {
public static void main(String[] args) {
try {
String s = args[0];
int i = args[0].length()-1;
int i2 = args[0].length();
char [] chrs = new char[i2];
for ( int i3 = i; i3 > -1; i3-- ) {
chrs[i2-i3-1] = (s.charAt(i3) );
}
String s2 = String.valueOf(chrs);
if ( s2.equals(s) ) {
System.out.println( s + " is a palindrome!");
} else {
System.out.println( s + " is not a palindrome");
}
} catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("Please enter at least one letter or digit!");
}
}
}
Here's how I did it:
public class palindromeTWO
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int right = 0;
int left = 1;
System.out.println("Please enter a word: ");
String word = scan.next();
int word_length = word.length();
while(word.charAt(right) == word.charAt(word_length - left) && left < (word_length / 2))
{
left++;
right++;
}
if(word.charAt(right) == word.charAt(word_length - left))
{
System.out.println("'" + word + "'" + " is a palindrome!");
}
else
{
System.out.println("'" + word + "'" + " is NOT a palindrome.");
}
}
}
1st implementation using recursion -
import java.util.ArrayList;
import java.util.stream.Collectors;
public class PalindromeManager {
private static String str = "ehcache";
private static ArrayList<String> list = new ArrayList<>();
public static void main(String[] args) {
test(str);
String output = list.stream().collect(Collectors.joining());
System.out.println(output);
if (output.equals(str)) {
System.out.println("it was palindrome");
} else {
System.out.println("Nope! it wasn't");
}
}
private static void test(String str) {
if (str.length() <= 0) {
return;
}
String lastChar = "" + str.charAt(str.length() - 1);
list.add(lastChar);
test(str.substring(0, str.length() - 1));
}
}
2nd implementation using iteration -
public class PalindromeManager2 {
private static String str = "ehcache";
public static void main(String[] args) {
int startIndex = 0;
int lastIndex = str.length() - 1;
boolean result = true;
while (true) {
if (startIndex >= lastIndex) {
break;
}
char first = str.charAt(startIndex);
char last = str.charAt(lastIndex);
/*if (first == ' ') {
startIndex++;
continue;
}
if (last == ' ') {
lastIndex--;
continue;
}*/
if (first != last) {
result = false;
break;
}
startIndex++;
lastIndex--;
}
if (result) {
System.out.println("Yes! It was");
} else {
System.out.println("Nope! it wasn't");
}
}
}
In checkPalindrome method change the condition of for loop from i<baseball.length()-1 to i<baseball.length().

Java skipping a number in the sequence

This is very interesting, i notice. Before i can explain further its best i show the code and you will understand what i mean.
This is the code:
public class Qn3 {
static BigDecimal[] accbal = new BigDecimal[19];
private static Integer[] accnums = new Integer[19];
public static void main(String[] args) {
addaccount();
}
public static void addAccount() {
int i = 0, accno, input, j, check;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(System.in);
accnums[1] = new Integer(1);
while (accnums.length >= count(accnums)) {
System.out.print("Enter the account number: ");
while (sc.hasNext("[0-9]{7}")) {
accno = sc.nextInt();
System.out.print("Enter account balance: ");
accbala = in.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null)
break;
else if (accnums[j].equals(accno)) {
break;
}
}
if (j == accnums.length) {
System.out.print("No more than 20 accounts can be added.");
} else if (accnums[j] != null) {
if ((accnums[j].equals(accno)))
System.out.println("Account already exists");
break;
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
check = j;
System.out.println("Current number of accounts in the system: "
+ (check + 1)
+ "\nNumber of accounts still can be added: "
+ (20 - (check + 1)));
}
}
while (!sc.hasNext("[0-9]{7}")) {
System.out.println("Wrong NRIC");
break;
}
while (accnums.length <= count(accnums)) {
System.out.println("20 accounts have already been created");
break;
}
break;
}
}
private static int count(Integer[] array) {
int count = 0;
// accnums = new Integer[] {1,2};
for (int index = 0; index < array.length; index++) {
if (array[index] != null) {
count++;
}
}
// System.out.println("You have used " + count + " slots");
return count;
}
}
So now that you have seen the code the problem that is hard to notice is this, take note of the line in the addaccount() method where
System.out.println("Current number of accounts in the system: "+(check+1)+"\nNumber of accounts still can be added: "+(20 - (check+1)));
this line the first check+1 will give me 1 then the next one gives me 3! and then the next time i run the method it gives me 4 and then again 5 and so on so forth, what is happening to 2?
You have that println in an else block, and when j == 1 you're hitting the else if case. Try removing this line
accnums[1] = new Integer (1);

Categories