I am trying to code a word game. There are questions which is shown randomly and user try to answer right.
I matched questions and answers with switch case but I can't check if it is right or not because I can't figure out how can I find words in String array. Also, there is an error in the switch-case because of the method.
import java.util.Scanner;
import java.util.Random;
public class Odev {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter the 1 for answer or 2 for requesting a letter.");
int first= input.nextInt();
String[] question = new String[9];
String [] answer=new String[9];
question=array(question);
answer=array2(answer);
Random b= new Random();
int randomNumber=b.nextInt(question.length);
if(first==1) {
System.out.println(question[randomNumber]);
System.out.println(randomNumber);
String a1=input.next();
switch (randomNumber) {
case 0: equalM(a1, answer[0]);
break;
case 1: equalM(a1, answer[1]);
break;
case 2:equalM(a1, answer[2]);
break;
case 3:equalM(a1, answer[3]);
break;
case 4:equalM(a1, answer[4]);
break;
case 5:equalM(a1, answer[5]);
break;
case 6:equalM(a1, answer[6]);
break;
case 7:equalM(a1, answer[7]);
break;
case 8:equalM(a1, answer[8]);
break;
}
}
}
public static String [] array(String [] question) {
question[0]="A beverage which is white and generally consumed in mornings";
question[1]="The natural satellite of earth";
question[2]="An adjective which describes people who have not adequate money";
question[3]="A furniture sit around for eating or studying";
question[4]="A group that consists a lot of soldier";
question[5]="A fruit which can be red, yellow and green";
question[6]="A tool for writing which consists graphite";
question[7]="A beverage which is consumed by people who need caffeine ";
question[8]="A term which is stand for the smallest group of the society ";
return question;
}
public static String [] array2(String [] answer) {
answer[0]="milk";
answer[1]="moon";
answer[2]="poor";
answer[3]="table";
answer[4]="army";
answer[5]="apple";
answer[6]="pencil";
answer[7]="coffee";
answer[8]="family";
return answer;
}
public static String[] equalM(String a1, String[] answer) {
for (int i=0; i<answer.length; i++) {
if(a1.equals(answer[i])) {
System.out.println("Correct you gained 500 points");
} else
System.out.println("Wrong.You lost 500 points");
}
return answer;
}
}
You could use a hashmap to do this easily, but if you want to stick with arrays, you could print out all the answer choices along with their index number, and then read in the number the user types in for the correct answer. You then just have to check if that number is equal to the random number used to generate the question.
Related
I'm trying to convert a text to nato alphabet but I can't figure out what is the problem. I tried to split the text into characters and then put it in arrays then in a for loop to test if the character is equal and write the correct word
Sample Text : hello
Result: hotel echo lima lima oscar
package text2nato;
import java.util.Scanner;
public class Text2nato {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the text to conver to nato :");
String text = scan.nextLine();
char[] carray = text.toCharArray();
for(int i=0;i<carray.length;i++){
if("a".equals(carray[i])){
System.out.print("alpha");
}if("b".equals(carray[i])){
System.out.print("brabo");
}if("c".equals(carray[i])){
System.out.print("charlie");
}
if("d".equals(carray[i])){
System.out.print("delta");
}if("e".equals(carray[i])){
System.out.print("echo");
} if("f".equals(carray[i])){
System.out.print("foxtrot");
}if("g".equals(carray[i])){
System.out.print("golf");
} if("h".equals(carray[i])){
System.out.print("hotel");
} if("i".equals(carray[i])){
System.out.print("india");
} if("j".equals(carray[i])){
System.out.print("juliet");
} if("k".equals(carray[i])){
System.out.print("kilo");
} if("l".equals(carray[i])){
System.out.print("lima");
} if("m".equals(carray[i])){
System.out.print("mike");
} if("n".equals(carray[i])){
System.out.print("november");
} if("o".equals(carray[i])){
System.out.print("oscar");
} if("p".equals(carray[i])){
System.out.print("papa");
} if("q".equals(carray[i])){
System.out.print("quebec");
} if("r".equals(carray[i])){
System.out.print("romeo");
} if("s".equals(carray[i])){
System.out.print("sierra");
} if("t".equals(carray[i])){
System.out.print("tango");
} if("u".equals(carray[i])){
System.out.print("uniform");
} if("v".equals(carray[i])){
System.out.print("victor");
} if("w".equals(carray[i])){
System.out.print("whiskey");
} if("x".equals(carray[i])){
System.out.print("x-ray");
} if("y".equals(carray[i])){
System.out.print("yankee");
} if("z".equals(carray[i])){
System.out.print("zulu");
}
}
}
}
Others have already pointed out in the comments that you're comparing a string to a char, which will never be equal. By way of illustration, try the following program:
public class Demo {
public static void main(String[] args) {
Boolean x = "b".equals('b');
System.out.println(x);
}
}
The result will be false. You could argue that this is a bit of a "gotcha" in Java, but that's a matter of opinion.
Also, if you have that many if statements in a row, it's a pretty good hint that something's probably gone wrong. At a minimum, a switch statement would be far easier to read:
package text2nato;
import java.util.Scanner;
public class Text2nato {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the text to convert to nato: ");
String text = scan.nextLine();
// You might want to consider converting the whole string to lowercase to make this case-insensitive
char[] carray = text.toCharArray();
for(int i=0; i < carray.length; i++){
if (i > 0)
{
// We need to prepend a space here
System.out.print(" ");
}
switch (carray[i])
{
case 'a': System.out.print("alpha"); break;
case 'b': System.out.print("bravo"); break;
// The rest of your cases go here
// Be sure to handle the case where the user enters something invalid
default: System.out.print(carray[i] + " is not a valid lowercase letter"); break;
}
}
}
}
As you can see, indenting the code properly, adding some extra whitespace, and using a switch statement makes this much easier to read.
public static void choice( String arrayString[], double arrayReal[])
{
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("1.display mark");
System.out.println("2.exit");
choice = sc.nextInt();
while (choice !=2 && choice != 1)
{
System.out.println("invalid input enter again");
choice = sc.nextInt();
}
switch (choice)
{
case 1:
output(arrayString, arrayReal);
break;
case 2:
System.out.println("exiting");
break;
default:
System.out.println("invalid choice choose between 1 and 2");
choice = sc.nextInt();
}
}
public static void output(String arrayString[], double arrayReal[])
{
String name;
Scanner sc = new Scanner(System.in);
for (int i=0;i<arrayString.length;i++)
{
System.out.println(arrayString[i]);
}
System.out.println("enter stident name");
name = sc.nextLine();
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
for (int j=0;j<arrayString.length;j++)
{
if (arrayString[j].equals(name))
{
System.out.println("mark of " + arrayString[j] + "is " + arrayReal[j]);
}
}
im trying to validate the student name and if it doesnt equal to any of the names in the array return back to the menu. it does go back to the menu but the problem is after going back to the menu even if i type the correct student name if keps going back to the menu. i thought for loops were supposed to loop set amount of times and pass to the next code?? is that right? also is my approach correct? ive tried putting if else in the last for loop but that didnt end up as i wanted it to as well. any help is appreciated thanks!
EDIT-
thanks for spotting the mistake. fixed !arrayString.equals(name) to !arrayString[k].equals(name) but still the same problem
Your problem ist here:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
You are comparing an Array String[] arrayString with a String name. They are never going to be treated as equal and therefor your choice method is allways called.
Also the whole loop is totally pointless as you never use your loop index k for anything.
You don't need a loop here at all. Instead you can simply convert the String array to a temporary list and check if it contains your input:
if(!Arrays.asList(arrayString).contains(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
Edit:
here a short main Method that can be used for testing:
public static void main(final String[] args) {
final String[] test = { "Mark", "Peter" };
final double[] test2 = { 1, 2 };
choice(test, test2);
}
Input/Output:
OUTPUT: 1.display mark
OUTPUT:2.exit
INPUT: 1
OUTPUT: Mark
OUTPUT: Peter
OUTPUT: enter stident name
INPUT: Mark
OUTPUT: mark of Markis 1.0
The logic at this part, after adding the index, is still wrong:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString[k].equals(name))
{
System.out.println("invalid name");
...
}
}
this will print "invalid name" for every name in the list that is not the given name. Example: if the first name in the array does not match, you will get a message (and choice called), no matter if the second entry matches.
One way is to search the whole array until you find the name and then act on the result:
boolean found = false;
for (int k=0;k<arrayString.length;k++)
{
if(arrayString[k].equals(name))
{
found = true;
break; // stop searching
}
}
if (!found)
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
I am writing a code for Hang Man game in Java.But I cannot write a proper code or find a way to calculate users' score and printing it at the users' end command with 0:stop.Here are the score calculation rules;
Score is computed as number of letters of the word minus number of letters currently displayed.
Here “table “ score is 5-4=1 as when the user make a guess there are 4 letters already displayed.
If the user guess is not correct score is 0
If the man’s figure is completed before a guess, the score is 0
Each play of the game bu the same user is a session, the same word cannot be held by computer.
If “table” is held as a “things” it can bot be held by computer again n the same session.
When the user press 0 in the main mene, the session ends.
Toptal number of plays, how many times correctly guessed , and total score of the user is displaid to the screen.
Also,i have a problem to prevent duplicate in random selected words array
import java.util.Random;
import java.util.Scanner;
public class CEVIK_CAGATAY{
public static char[] star;
public static void main (String args[])
{
char game[];
int category;
int correct=0;
Scanner input = new Scanner(System.in);
Random r = new Random();
int totalplay=0;
int totalscore=0;
String man[] = new String[7];
man[2] = " --\n o |\n/ |\n |\n_____\n";
man[3] = " --\n o |\n/| |\n |\n_____\n";
man[4] = " --\n o |\n/|\\|\n |\n_____\n";
man[5] = " --\n o |\n/|\\|\n/ |\n_____\n";
man[6] = " --\n o |\n/|\\|\n/ \\|\n_____\n";
String arr[]={"serhat","cagatay","begum","emre","berk","ali","veli","istanbul",
"ankara","mersin","izmir","antalya","new york","samsun","kedi","kopek",
"kus","ayi","bocek","karinca","manda","masa","pencil","bag","clock","televison","book","glass"};
int arr1 []={6,7 };
System.out.println("0 To Stop,1 to Continue");
category=input.nextInt();
while(category!=0){
System.out.println("0 To STop,1 to Continue");
String word = arr[r.nextInt(arr.length)];
for(int i=0; i<arr.length;i++) {
if(arr[i]==word){
int letterlength=arr1[i];
}
//letterlength-existedlength=guessremain;
}
int count = word.length();
char[] CharArr=word.toCharArray();
char[] star = word.toCharArray();
for(int i=0;i<star.length;i++)
{
star[i] = '*';
System.out.print(star[i]);
}
for (int i=1; i<=5; i++)
{
System.out.printf ("\nGuess a Letter:");
char letter= input.next().charAt(0);
for (int j=0;j<CharArr.length; j++)
{
if(letter == star[j])
{
System.out.println("this word already exist");
}
else
{
if(letter==CharArr[j])
{
star[j]=letter;
i--;
System.out.printf("CORRECT GUESS!\n");
correct++;
}
}
}
System.out.print(star);
switch(i+0)
{
case 1: System.err.printf("Strike 1\n");
System.out.println(man[2]);
break;
case 2: System.err.printf("Strike 2\n");
System.out.println(man[3]);
break;
case 3: System.err.printf("Strike 3\n");
System.out.println(man[4]);
break;
case 4: System.err.printf("Strike 4\n");
System.out.println(man[5]);
break;
case 5: System.err.printf("Strike5\n");
System.err.printf("You're out!!! The word is Not_Matched\n");
System.out.println(man[6]);
break;
}
System.out.printf("\n");
if((new String(word)).equals(new String(star)))
{
System.err.printf("Winner Winner\n");
break;
}
}
totalplay++;
totalscore+=correct;
System.out.println("CONTINUE 1,STOP 0");
category=input.nextInt();
if(category==0) {
System.out.println(totalplay);
System.out.println(totalscore);
}
}
}
}
Get rid of the following for loop. It serves no purpose except to throw an Array Index Out of Bounds error. Your program runs without it. Be sure to practice best practices for language as well (such as camelCase for naming variables). It makes your code easier for humans to understand.
for(int i=0; i<arr.length;i++) {
if(arr[i]==word){
int letterlength=arr1[i];
}
//letterlength-existedlength=guessremain;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am writing a program where i have to use methods to count my string, .upper and lower using a switch statement. My code is not showing any errors can someone help.
import java.util.*;
public class Strings
{
public static void main(String[] args)
{
String selection;
Scanner keyboard = new Scanner(System.in);
System.out.println("*********** EXAM 3 ENTER A STRING *************");
System.out.println("Enter 1 to display the number of words in the string");
System.out.println("Enter 2 to display the string in all capital letters");
System.out.println("Enter 3 to display the string in all lower case letters");
System.out.println("Enter 4 to display the string in reverse order");
System.out.println("Enter -1 to exit");
selection = keyboard.nextLine();
switch(selection.charAt(0))
{
case 1:
numberOfWords(selection);
break;
case 2:
allCapitals(selection);
break;
case 3:
allLowers(selection);
break;
case 4:
reverseOrder(selection);
break;
}//ends switch
}
/*public static void menuMethod(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("*********** EXAM 3 ENTER A STRING *************");
System.out.println("Enter 1 to display the number of words in the string");
System.out.println("Enter 2 to display the string in all capital letters");
System.out.println("Enter 3 to display the string in all lower case letters");
System.out.println("Enter 4 to display the string in reverse order");
System.out.println("Enter -1 to exit");
}
*/
public static void numberOfWords(String selection)
{
String input; // To hold input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
input = keyboard.nextLine();
// Display the number of words.
System.out.println("That string has " + wordCount(input) + " words in it.");
}
public static int wordCount(String str)
{
StringTokenizer strTok = new StringTokenizer(str);
return strTok.countTokens();
}
public static void allCapitals (String str)
{
String input;
String capInput;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a string. ");
input = keyboard.nextLine();//You must use nextLine here next will not work.
capInput = input.toUpperCase();
System.out.println("Your capital case string = \n" + capInput);
}
public static void allLowers (String str)
{
String input;
String lowerInput;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a string. ");
input = keyboard.nextLine();//You must use nextLine here next will not work.
lowerInput = input.toUpperCase();
System.out.println("Your lower case string = \n" + lowerInput);
}
public static void reverseOrder (String str)
{
String input; // To hold input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter something: ");
input = keyboard.nextLine();
// Display it backwards.
backward(input);
}
public static void backward(String str)
{
for (int i = str.length() - 1; i >= 0; i--)
System.out.print(str.charAt(i));
System.out.println();
}
}
Please use this code for switch
switch(selection.charAt(0))
{
case '1':
numberOfWords(selection);
break;
case '2':
allCapitals(selection);
break;
case '3':
allLowers(selection);
break;
case '4':
reverseOrder(selection);
break;
}//ends switch
replace your switch condition to
switch(Integer.parseInt(selection))
{
//your code
}
instead of
switch(selection.charAt(0))
{
//your code
}
if you use charAt(0) your checking condition must be like that because that method returns a char value
case '1':
numberOfWords(selection);
break;
case '2':
allCapitals(selection);
break;
case '3':
allLowers(selection);
break;
case '4':
reverseOrder(selection);
break;
You haven't said what is wrong with the program output. Explaining your problem as thoroughly as possible will help you get a good answer quickly.
As for possible problems:
Your allLowers() method is using toUpperCase(). As a good design practice, try to copy paste code as little as possible, since copy/pasting code implies that there could be a function that does the same thing.
You are never actually checking for an input of -1. All you would do in your current method (if you were to check for the exit condition) is check for the - sign as that is the first character, rather that the entire -1 string, which could easily lead to bugs if you expand the program.
This question already has answers here:
Simple Java calculator
(10 answers)
Closed 8 years ago.
Trying to make a simple calculator in Java but I keep getting errors when I try to compile it. Not sure if it's the coding or something I am doing when I compile it. Any help would be appreciated!
import java.util.Scanner;
class simple calculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double fnum,snum,ans;
System.out.print("Enter the first and second " +
"number : ");
a=bucky.nextFloat(); //assign the numbers
b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
Two compilation errors:
Your class name has whitespace in it: class simple calculator isn't valid, because "calculator" isn't a recognized token. Try: class SimpleCalculator. Also make it public and change the name of the file to match. (SimpleCalculator.java).
You declare variables a and b but don't give them types. Use float a = ... and double b = .... That one is a float and the other is a double is strange, but pressing on...
Other new-to-java issues to note:
You never close bucky, the scanner. This is a resource leak, and in a bigger application could be a major bug. Add bucky.close() after you read the last line from it, which is after operation = bucky.next()
the name bucky tells me absolutely nothing about what it is or what its use is. Try to use descriptive variable names. (The only main exception being single letter names for loop indices, etc).
fnum and snum are local variables that you declare but never use. Perhaps get rid of them?
Here's your code with edits made:
import java.util.Scanner;
public class SimpleCalculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double ans;
System.out.print("Enter the first and second " +
"number : ");
float a=bucky.nextFloat(); //assign the numbers
double b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
bucky.close();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
I was able to compile it in the terminal with no trouble.