I am working on the tortoise and hare game, and everything works except I want to print out "OUCH" when the hare and the tortoise are in the same position. My race track is a character array so I can only put 'O', and whenever I try to print it as a string "OUCH" it prints it as a separate new line. Is there a way to print "OUCH" without breaking up the flow of the game, and outputting it on a different line to everything else?
public static int turtlePosition = 0; // Turtle location
public static int harePosition = 0; // Hare location
public static char[] track = new char [70]; // Array for Track
public static void main(String[] args) {
System.out.println("AND THEY ARE OFF!!");
while (!gameOver()){
for (int i = 0; i < track.length; i++){
track[i] = '-';
}
Random random = new Random();
int r = random.nextInt(10) + 1;
turtleMove(r);
hareMove(r);
if (gameOver()){
break;
}
track[turtlePosition] = 'T';
track[harePosition] = 'H';
if (turtlePosition == harePosition){
String str = String.valueOf(track[turtlePosition]);
str = "OUCH";
System.out.println(str);
}
for (int i = 0; i < track.length; i++)
{
System.out.print(track[i]);
}
System.out.println();
}
if (turtlePosition >= 70 && harePosition >= 70){
System.out.println("IT'S A TIE!!");
}
else if (turtlePosition >= 70){
System.out.println ("TORTOISE WINS!!");
}
else {
System.out.println ("HARE WINS!!");
}
i don't believe so but you could put a text area to the side.
like this:
Code changes:
if (turtlePosition>=6 || harePosition>=6){
turtlePosition = 7;
harePosition = 7;
}
track[turtlePosition] = 'T';
track[harePosition] = 'H';
if (turtlePosition == harePosition){
insertintotrack("OUCH |");
}else {
insertintotrack(" |");
}
New Function:
public static void insertintotrack(String in)
{
char[] info = in.toCharArray();
for (int i = 0; i < info.length; i++) {
track[i] = info[i];
}
}
Related
I was getting this error while running the following code. I couldn't find out what was wrong with the code.
As far as I can see, there's some issue with my second character array. But couldn't find out what was wrong. First tried running the last loop before temp_count. Then also tried temp_count±1. Yet, I failed. I have also tried taking different array size. still no luck
import java.util.Scanner;
public class oop2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str=sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[temp_count];
//Converting uppercase to lower case for convenience
for(int i=0; i<str.length(); i++)
{
if (Character.isUpperCase(c[i]))
{
c[i]=(char) (c[i]+32);
}
}
//verifying whether the alphabet exists
for(char x = 'a'; x<='z'; x++)
{
int count=0;
for(int i=0; c[i]!='\0'; i++)
{
if (c[i]==x)
{
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count==0)
{
temp[temp_count]=x;
temp_count++;
}
}
//Verifying whether it's a pangram or not
if (temp_count==0)
{
System.out.println("Pangram");
}
else
{
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for(int i=0; i<temp_count-1; i++)
{
System.out.print(temp[i]+", ");
}
}
sc.close();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str = sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[0];
//Converting uppercase to lower case for convenience
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(c[i])) {
c[i] = (char)(c[i] + 32);
}
}
//verifying whether the alphabet exists
for (char x = 'a'; x <= 'z'; x++) {
int count = 0;
for (int i = 0; c[i] != '\0'; i++) {
if (c[i] == x) {
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count == 0) {
char [] copy = new char[temp.length+1];
for (int i = 0; i < temp.length; i++) {
copy[i]=temp[i];
}
copy[copy.length-1] = x;
temp=copy;
}
}
//Verifying whether it's a pangram or not
if (temp_count == 0) {
System.out.println("Pangram");
} else {
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for (int i = 0; i < temp_count - 1; i++) {
System.out.print(temp[i] + ", ");
}
}
sc.close();
}
}
Blockquote
I can't find a way to be to able to put the encryptedChar to a char Array so that I can out put the message on one line. If anyone could give me a simple solution to the problem or help me in any way that would be great!
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// can get the index without key. DONE
// encrypt message. finish equation.
int encryptKey, encryptedIndex;
int plainLetterIndex = 0;
int loadingBar = 3;
char encryptedChar;
char[] alphaArray = {'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'};
String redo, message;
System.out.println("Welcome to the encrypter and decrypter program. The program will take the message");
System.out.println("and either encrypt it or decrypt it. Depending on what you choose to do.");
System.out.println("");
do {
System.out.println("Please enter your message!");
message = sc.nextLine();
message = message.toUpperCase();
System.out.print("Would you like to re-enter your message? (Y/N)");
redo = sc.nextLine();
} while (redo.equals("Y") || redo.equals("y"));
// declaring arrays
char[] messageArray = message.toCharArray();
char[] encryptedMessageArray = new char[messageArray.length];
// asking for key
System.out.println("Please input the 'key' you would like to use to encrypt your message.");
while(true){
try{
encryptKey = Integer.parseInt(sc.nextLine());
break;
} catch (NumberFormatException ignore){
System.out.println("You have entered an incorrect number, please try again!");
}
}
System.out.println(" ");
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
//encryptedMessageArray = encryptedChar;
System.out.print(encryptedChar);
}
}
}
sc.close();
}
}
Use an index variable for encryptedMessageArray, increase it everytime you put a character into encryptedMessageArray
int index = 0;
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[index] = encryptedChar;
index++;
}
}
}
System.out.println();
System.out.println(encryptedMessageArray);
Add either the encrypted char or the original char to your encryptedMessageArray so you can decrypt the array end get the original message
for (int i = 0; i < messageArray.length; i++) {
boolean isCharEncrypted = false;
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[i] = encryptedChar;
isCharEncrypted = true;
}
}
if (!isCharEncrypted) {
encryptedMessageArray[i] = messageArray[i];
}
}
Here is an alternative solution to avoid the inner for-loop
for (int i = 0; i < messageArray.length; i++) {
char c = messageArray[i];
if (c >= 'A' && c <= 'Z') {
plainLetterIndex = c - 65; //A is ASCII 65
encryptedIndex = (char) (plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[i] = encryptedChar;
} else {
encryptedMessageArray[i] = messageArray[i];
}
}
Hello I can't make this work, I am given a main word followed by another sub words if the word is contained in the main word the part should be deleted.
//Example
//fmrog (in.nextLine)(main word)
//4 (in.nextInt)(the amount of sub words)
//roc(in.nextLine)(not contained)
//gor(in.nextLine)(not contained)
//rog(in.nextLine)(contained)
//ogr(in.nextLine)(not contained)
//result:fm
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder mainWord = new StringBuilder(in.nextLine);
int n = in.nextInt();
StringBuilder MainWord2 = new StringBuilder(mainWord);
in.nextLine();
for (int i = 0; i < n; i++) {
String subWord = in.nextLine();
int chars = subWord.length();
if (chars> mainWord.length()){
continue;
}
for (int j = 0; j < subWord.length(); j++) {
int r = 0;
for (int k = 0; k < mainWord.length(); k++) {
r++;
if (k > MainWord2.length() - 1) {
break;
}
if (MainWord2.charAt(k) == subWord.charAt(j)) {
break;
}
}
if (r <= MainWord2.length() && MainWord2.charAt(r-1) == subWord.charAt(j)) {
MainWord2.deleteCharAt(r - 1);
if (j >= subWord.length() -1 ) {
mainWord = MainWord2;
break;
}
}
if (r > MainWord2.length()) {
MainWord2 = mainWord;
break;
}
}
}
System.out.println(mainWord);
}
}
Honestly I am stucked maybe there is an easier way to solve this. The main thing is that when I write a case like : "super 2 pe surr" At the end at "surr" the two StringBuilders start to act as one when I delete chatAt at one of them the other one changes also
No need to make it so complex.
String input = // complete user input
String[] words = String.split(input);
String mainWord = words[0];
int numWords = Integer.parseInt(words[1]); // this variable isn't needed
for(int i = 2; i < words.length; i++) {
if (mainWord contains words[i]) {
mainWord = mainWord.replace(words[i], ""); // remove subword from mainword
}
}
At the end, mainWord will be the original mainWord without any subwords that were entered later.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
String[] words = new String[n];
for (int i = 0; i <n ; i++) {
words[i] = in.nextLine();
}
String mainWord = words[0];
for (int i = 1; i <words.length ; i++) {
if (mainWord.contains(words[i])){
mainWord = mainWord.replace(words[i], "");
}
}
System.out.println(mainWord);
}
}
Here but the thing is if the letters are not one next to another it doesnt remove the subword.
I am using a StringBuilder and appending it with * for each letter of the word to be guessed. Then when the user guesses a letter/char correct the StringBuilder should be changing the char at a certain index from * to the guessed letter/char. Then print the new StringBuilder to show the correct letter like this (ho * s *). If the guess is wrong then just print the StringBuilder and say wrong guess.
I am trying to figure out why this is not working properly. I am getting output like: (minus the / it wouldn't post just the *)
HANGMAN
Try and guess the word, you have 9 attempts:
/***************
Guess a letter: g
/*************************
Guess a letter: p
p****p****p****p****p****
Guess a letter
It is also printing the word more than once and I am not sure why.
import java.util.Random;
import java.util.Scanner;
public class Hangman {
static String[] words = {"house", "show", "garage", "computer", "programming", "porch", "dog"};
static char[] correct = new char[26];
static char[] wrong = new char[26];
static char guess;
static Random generator = new Random();
static Scanner input = new Scanner(System.in);
static String word;
static int attempts = 0;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args){
word = words[generator.nextInt(words.length)];
System.out.print("HANGMAN\nTry and guess the word, you have 9 attempts: \n");
printAstrick();
while(attempts <= 9){
System.out.print("\nGuess a letter: ");
guess = input.next().charAt(0);
findMatch(guess);
}
if(attempts == 9){
System.out.println("Your attempts are up");
}
}
public static void findMatch(char c){
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == c){
correct[i] = c;
sb.setCharAt(i, c);
System.out.print(sb.toString());
}
else if(word.charAt(i) != c){
wrong[i] = c;
sb.setCharAt(i, '*');
System.out.print(sb.toString());
}
}
attempts++;
}
public static void printAstrick(){
for(int i = 0; i < word.length(); i++){
sb.append("*");
System.out.print(sb.toString());
}
}
You are overwriting any correct guesses with this line:
sb.setCharAt(i, '*');
in your findMatch method so you should remove it.
Also, your print statements are in for loops so each word is printed out n times. Fix this by moving your calls to System.out.print(sb.toString()) outside of the for loops.
This leaves you with:
public static void findMatch(char c) {
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == c) {
correct[i] = c;
sb.setCharAt(i, c);
} else if (word.charAt(i) != c) {
wrong[i] = c;
}
}
System.out.print(sb.toString());
attempts++;
}
public static void printAstrick() {
for (int i = 0; i < word.length(); i++) {
sb.append("*");
}
System.out.print(sb.toString());
}
I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.