i have a problem writing guess the word game java code .
i'll show you my current code and till you the problem .
import java.util.Scanner;
class Q
{
public static void main(String argss[])
{
String strs[] = { "kareem", "java", "izz", "tamtam", "anas" };
Scanner input = new Scanner(System.in);
int index = ((int) (Math.random() * 5));
int points = 50;
String c;
boolean result = false;
boolean finalResult = false;
boolean tempResult = false;
String word = strs[index];
System.out.println(
"\t *** Enter a character and guess the world*** \n\t ***You will loose if your points become 0 *** \n ");
System.out.println(stars(word));
System.out.println("Your points: " + points);
System.out.print("Enter and guess a character! ");
String temp = stars(word);
String oldTemp = temp;
c = input.next();
while (points > 0)
{
for (int i = 0; i < word.length(); i++)
{
result = (word.charAt(i) + "").equals(c);
if (result == true)
{
temp = toChar(i, temp, c);
}
}
finalResult = temp.equals(word);
tempResult = temp.equals(oldTemp);
System.out.println(temp);
if (finalResult == true)
{
System.out.println("\n \n YOU HAVE GUESSED THE WORLD,YOU WON ! ");
break;
}
if (tempResult == true)
{
points = points - 5;
System.out.println("False and now your points are " + points);
}
else if (tempResult == false)
{
System.out.println("True and now your points are " + points);
}
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
System.out.print("Guess another time,enter a character: ");
c = input.next();
}
}
public static String stars(String word)
{
String temp = "";
for (int i = 0; i < word.length(); i++)
temp = temp + "*";
return temp;
}
public static String toChar(int index, String temp, String c)
{
char[] tempChar = temp.toCharArray();
char s = c.charAt(0);
tempChar[index] = s;
temp = String.valueOf(tempChar);
return temp;
}
}
now as you can see in line number 39 , i have a little problem here because when its false it'll be no longer right .
do you know another way to compare if the entry is right or not ?
Doesn't look like you are changing oldTemp inside the while loop. Try setting it to equal to temp after all of the if statements.
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
oldTemp = temp; // add this here
System.out.print("Guess another time,enter a character: ");
c = input.next();
Related
I am trying to compare two different strings, one character at a time. I need to return the correct number of digits until they do not equal each other anymore. However, I can't include the character of '.' in the return statement. How would I go about doing this?
import java.util.Scanner;
import java.math.BigDecimal;
public class PiEstimate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a;
String b;
char y;
char c;
char d;
String userInput;
do {
System.out.print("Enter a number of randomly generated points:");
userInput = in.nextLine();
if (!isValid(userInput)) {
System.out.print("\n" + "You entered an invalid integer. Please enter a valid integer greater than 0: ");
userInput = in.nextLine();
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
} else {
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
}
System.out.println("\n" + "Would you like to play again? Enter 'Y' for yes or 'N' for no: ");
String optionToPlay = in.nextLine();
c = optionToPlay.charAt(0);
d = Character.toUpperCase(c);
if (d == 'n' || d == 'N') {
BigDecimal estimate2= new BigDecimal( (Math.PI / 4) * 4);
System.out.println("\n" + "The best estimate is: " + estimate2);
}
} while (d == 'Y');
} // end psvm
public static boolean isValid(String a) {
boolean isFlag = true;
char holder;
for (int i = 0; i < a.length(); i++) {
holder = a.charAt(i);
if (!Character.isDigit(a.charAt(i))) {
return false;
} if (i == 0 && holder == '-') {
return false;
}
} // end for
return isFlag;
} // end isValid
public static double calculation(String a) { // String a means 'looking for a string
double calc = Double.parseDouble(a);
int i;
double x;
double y;
double c = 0;
double runningCounter = 0;
double totalCounter;
for (i = 0; i < calc; i++) {
x = Math.random();
y = Math.random();
c = Math.sqrt((x * x) + (y * y));
if (c <= 1) {
runningCounter++;
}
} // end for
totalCounter = ((runningCounter / calc) * 4);
calc = totalCounter;
return calc;
}
public static int comparison (String bear, String userInput) {
int i = 0;
String s = calculation(userInput) + "";
int b;
int counter2 = 0;
for (i=0; i < s.length(); i++) {
if (s.charAt(i) != bear.charAt(i)) {
return i;
}
}
return i;
} // end comparison
} // end class
Code from IDE
So I have been given a project in where I must validate ISBN-10 and ISBN-13 numbers. My issue is that I want to use an ArrayList based on what the user inputs(the user adds as many numbers as they want to the ArrayList). Here is my code (without an ArrayList). How can I modify this so that the user can put as many ISBN number as they want?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
//Get the ISBN
System.out.print("Enter an ISBN number ");
isbn = input.nextLine();
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
}else{
isValid = false;
}
//Print check Status
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{
System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
//
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
}
public static List<String> scanNumberToListUntilAppears(String end) {
if(end == null || end.isEmpty())
end = "end";
List<String> numbers = new ArrayList<>();
String message = "Enter an ISBN number: ";
try (Scanner input = new Scanner(System.in)) {
System.out.print(message);
while(input.hasNext()) {
String isbn = input.nextLine();
if(isbn.equalsIgnoreCase(end)) {
if(!numbers.isEmpty())
break;
} else {
numbers.add(isbn);
if(numbers.size() == 1)
message = "Enter the next ISBN number or '" + end + "': ";
}
System.out.print(message);
}
}
return numbers;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
String ans;
ArrayList<String> isbns = new ArrayList<String>();
// user will enter at least 1 ISBN
do{
//Get the ISBN
System.out.println("Enter an ISBN number ");
isbns.add(input.nextLine());
//loops till answer is yes or no
while(true){
System.out.println("Would you like to add another ISBN?");
ans = input.nextLine();
if(ans.equalsIgnoreCase("no"))
break;
else if (!(ans.equalsIgnoreCase("yes"))
System.out.println("Please say Yes or No");
}
}while(!(ans.equalsIgnoreCase("yes"));
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
for(int i = 0; i<isbns.size(); i++)
isbns.set(i, isbns.get(i).replaceAll("( |-)", ""));
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
for(String isbn : isbns){
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
print(isbn, isValid);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
print(isbn, isValid);
}else{
isValid = false;
print(isbn, isValid);
}
}
public static void print(String isbn, boolean isValid){
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{ System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
I have this bit of code that is meant to alphabetize three words. I'm trying to remove the method at the bottom, and simply add it to the code above. However, I can't figure out a working way to do so. Any guidance or help would be appreciated, thank you!
System.out.print("Please enter three words: ");
final String words = keyboard.nextLine();
final String[] parts = words.split(" ");
if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) {
System.out.println("All three of those words are the same!");
} else {
System.out.print("In alphabetical order those are: ");
alphabetizing (parts);
final int three = 3;
for (int limit = 0; limit < three; limit++) {
System.out.print(parts[limit] + " ");
}
}
}
public static void alphabetizing (final String[] parts) {
int word;
boolean check = true;
String temp;
for (word = 0; word < parts.length - 1; word++) {
if (parts[ word ].compareToIgnoreCase(parts[word + 1]) > 0) {
temp = parts[word];
parts[word] = parts[word + 1];
parts[word + 1] = temp;
check = true;
}
}
}
}
Since you want to do it anyway. I don't see any problem why it will not work. Just add it into the else statement where you are calling the method and it should work.
System.out.print("Please enter three words: ");
Scanner keyboard = new Scanner(System.in);
final String words = keyboard.nextLine();
final String[] parts = words.split(" ");
if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) {
System.out.println("All three of those words are the same!");
} else {
System.out.print("In alphabetical order those are: ");
//boolean check = true; you don't neeed this.
String temp = "";
for (int word = 0; word < parts.length - 1; word++) {
if (parts[word].compareToIgnoreCase(parts[word + 1]) > 0) {
temp = parts[word];
parts[word] = parts[word + 1];
parts[word + 1] = temp;
}
}
final int three = 3;
for (int limit = 0; limit < three; limit++) {
System.out.print(parts[limit] + " ");
}
}
Output :
Please enter three words: a b c
In alphabetical order those are: a b c
Please enter three words: a a a
All three of those words are the same!
Just started a computer science degree and have been tasked with making a Hangman game, it seems to work find other than it doesn't print "You won" and I cannot see/figure out why it doesn't. Any help from you guys would be great.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
char[] alpha = new char[26];
Arrays.fill(alpha, ' ');
String a1 = "intro to programming";
String a2 = "computer";
String a3 = "mouse and keyboard";
String a4 = "skyrim";
String a5 = "hello world";
int selector = rand.nextInt(5) + 1;
char[] words = null;
char[] show = null;
if (selector == 1) {
words = a1.toCharArray();
show = a1.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 2) {
words = a2.toCharArray();
show = a2.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 3) {
words = a3.toCharArray();
show = a3.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 4) {
words = a4.toCharArray();
show = a4.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 5) {
words = a5.toCharArray();
show = a5.toCharArray();
Arrays.fill(show, '-');
}
int length = words.length;
System.out.println("Please enter the amount of tries you would like:");
int amount = scan.nextInt();
String guessed;
char guessedchar;
for (int i = 0; i < length; i++) {
if (words[i] == ' ') {
show[i] = ' ';
}
}
int x = 0;
while (amount >= 0) {
System.out.print("String to guess: ");
for (char n : show) {
System.out.print(n);
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Number of tries left: " + amount);
System.out.print("Number of times you have tried: ");
for (char a : alpha) {
System.out.print(a);
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Enter a guess");
guessed = scan.next();
guessedchar = guessed.charAt(0);
alpha[x] = guessedchar;
for (int i = 0; i < length; i++) {
if (guessedchar == words[i]) {
show[i] = guessedchar;
}
}
x = x + 1;
amount = amount - 1;
if (amount == 0) {
System.out.println("You lose");
return;
} else if (show == words) {
System.out.println("You won");
}
}
}
Convert the words and show arrays to Strings and check if they are equal with .equals(), this should then display the correct message
I am creating a program which acts as a translator for given words. I have created a text file with the data I am using, reading that into a 2D array (English in column 0, translation in column 1, 16 rows in total). I prompt the user to enter a string and pass that string, the 2D, and a blank String to hold the translation to my translation method (named: turnKlingon). I am using the String tokenizer to pick out specific words. My problem is that I cannot figure out how to search my 2D array in column 0 for the English and only print the column 1 translated word.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
System.out.println("Klingon Translator");
System.out.println();
System.out.println();
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
String Klingon = " ";
turnKlingon(Klingon, userString, translate);
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated to Klingon: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String Klingon, String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println("Number of Tokens: "+ numberOfWords);
int counter = 1;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
System.out.print(s2 + "_"); //string tokenizer
for(int r = 0; r < translate.length; r++)
{
for(int c = 0; c < translate[r].length; c++)
{
if (translate[r][c].compareTo(s2) == 0)
{
translate[0] = translate[1];
}
}
System.out.println(translate[0] + "," + translate[1]);
counter++; //string tokenizer
}//end while
}
}
}
After messing around with this code for a few hours I finally managed to solve my own problem. I also added a while true loop in the main method to allow the user to translating multiple times as well as an option to translate to another language (German) though I have omitted that method from this reply.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
Scanner input = new Scanner(System.in);
System.out.println("English to Klingon/German Translator");
System.out.println();
System.out.println();
while (true)
{
int again = 999;
int language = 999;
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
System.out.println("Would you like to translate to Klingon or German? \n Press 1 for Klingon: \n Press 2 for German: ");
language = input.nextInt();
if (language == 1)
{
turnKlingon(userString, translate);
}
else if (language == 2)
{
turnGerman(userString, translate);
}
else
{
System.out.println("Invalid input");
}
System.out.println();
System.out.println();
System.out.println("Would you like to translate another sentence? \n Press 1 for yes or 0 for no: ");
again = input.nextInt();
if (again == 0)
{
System.out.println("Goodbye!");
break;
}
else if (again == 1)
{
continue;
}
}
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println();
System.out.println("Any words that cannot be directly \n translated will remain in English");
System.out.println("____________________________________");
System.out.println();
System.out.print("Translation: ");
int counter = 1;
boolean found = false;
int translateCounter = 0;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
//string tokenizer
for(int r = 0; r < 16; r++)
{
for(int c = 0; c < 18; c++)
{
found = false;
if (translateCounter == 16)
{
System.out.print(s2+ " ");
translateCounter = 0;
break;
}
else if (translate[r][0].compareTo(s2) == 0)
{
found = true;
}
else if (translate[r][0].compareTo(s2) != 0)
{
found = false;
r++;
c = -1;;
translateCounter++;
continue;
}
if (found == true)
{
System.out.print(translate[r][1]+ " ");
translateCounter = 0;
c = -1;
r = -1;
break;
}
}
counter++;//string tokenizer
break;
}//end while
}
}