I'm making a simple multiplication game, but when the user enters a correct answer, it still runs the else statement. I know it's a simple solution but I just can't figure it out. Can someone give me a hand?
public static void partB() {
System.out.println("Exercise 1B");
int count = 0;
String active = "true";
int correct = 0;
while (active == "true") {
Random r = new Random();
int Low = 10; //inclusive
int High = 21; //not inclusive
int Result = r.nextInt(High - Low) + Low;
Random r2 = new Random();
int Result2 = r2.nextInt(High - Low) + Low;
int Total = Result * Result2;
Scanner input = new Scanner(System.in);
System.out.println(Result + "*" + Result2 + "=?");
String guess = new String(input.nextLine());
String tostrng = String.valueOf(Total);
if (guess.equals (tostrng)) {
correct += 1;
count+=1;
System.out.println("Correct answer. Score: " + correct + "(" + count + ")");
}
if (guess.equals("q")) {
System.out.println("Good Bye!");
active = "false";
//return;
}
else {
count +=1;
System.out.println("Incorrect answer. Score:" + correct + "(" + count + ")");
}
}
}
Your else with wrong if
public static void partB() {
System.out.println("Exercise 1B");
int count = 0;
String active = "true";
int correct = 0;
while (active == "true") {
Random r = new Random();
int Low = 10; //inclusive
int High = 21; //not inclusive
int Result = r.nextInt(High - Low) + Low;
Random r2 = new Random();
int Result2 = r2.nextInt(High - Low) + Low;
int Total = Result * Result2;
Scanner input = new Scanner(System.in);
System.out.println(Result + "*" + Result2 + "=?");
String guess = new String(input.nextLine());
String tostrng = String.valueOf(Total);
if (guess.equals (tostrng)) {
correct += 1;
count+=1;
System.out.println("Correct answer. Score: " + correct + "(" + count + ")");
}
else {
count +=1;
System.out.println("Incorrect answer. Score:" + correct + "(" + count + ")");
}
if (guess.equals("q")) {
System.out.println("Good Bye!");
active = "false";
//return;
}
}
}
Make type of active variable as boolean i.e. boolean active=true;
and for comparing string values always use .equals() method.
Fixed it like this!
thanks for the help though guys.
if (guess.equals("q")) {
System.out.println("Good Bye!");
return;
}
if (guess.equals(tostrng)) {
correct += 1;
count += 1;
System.out.println("Correct answer. Score: " + correct + "(" + count + ")");
} else {
count += 1;
System.out.println("Incorrect answer. Score:" + correct + "(" + count + ")");
}
Related
I'm currently working on an offline Jackpot system for fun, and i got stuck with the ticket problem.
Basically I want it to be (which seems to me like the best way to do it) so for every 10$ a user enters, you'll get 1 ticket. so let's say Jason deposits 250$, then he gets tickets 1-25, Bob deposits 100$ then he gets tickets 26-36. etc etc
then in the end it'd pick a random number and it'd pick a player that has that number in his range.
this is the current code:
public class Main {
private static int totalPlayers = 0;
private static int totalMoney = 0;
private static int playerDeposit = 0;
private static ArrayList<String> players = new ArrayList<String>();
private static ArrayList<Integer> botsMoney = new ArrayList<Integer>();
private static Timer timer;
private static Random random = new Random();
private static int playerMoney = 500;
private static String playerName;
private static double playerChance;
public static void main(String[] args) {
onUserEnter();
}
public static boolean onUserEnter(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter your name:");
playerName = scan.nextLine();
System.out.println("Money: 500$");
System.out.println("How much would you like to deposit?");
try{
playerDeposit = scan.nextInt();
}catch(NumberFormatException ex) {
System.out.println(playerDeposit + " is not a proper number!");
playerDeposit = 0;
return false;
}
if(playerDeposit <= 0) {
System.out.println("You can't deposit " + playerDeposit + "$");
return false;
}else if(playerDeposit > playerMoney){
System.out.println("You can't deposit more money than what you have!");
return false;
}
playerMoney -= playerDeposit;
System.out.println("You now have: " + playerMoney + "$");
players.add(playerName);
totalPlayers = players.size();
totalMoney += playerDeposit;
System.out.println(totalPlayers + " Players: " + players);
System.out.println("Total Pot: " + totalMoney + ", Your chances: 100%");
TimerTask tasknew = new TimerTask() {
#Override
public void run() {
}
};
timer = new Timer();
timer.schedule(tasknew, 20000);
botJoin();
return true;
}
public static boolean botJoin(){
botsMoney.add(5355);
int x = 0;
while(true){
int willBotJoin = random.nextInt(1000000000);
if(willBotJoin <= 2){
if(players.size() >= 10) {
break;
}
int moneyBotDeposits = random.nextInt(1100);
botsMoney.add(moneyBotDeposits);
double tickets = (double) moneyBotDeposits / 10;
x++;
players.add("Bob #" + x);
totalPlayers = players.size();
totalMoney += moneyBotDeposits;
System.out.println(totalPlayers + " Players: " + players);
playerChance = ((double) playerDeposit / totalMoney) * 100;
System.out.println("Total Pot: " + totalMoney + "$, Your chances: " + playerChance + "%");
}
}
botsPrecentage();
return true;
}
public static boolean botsPrecentage(){
for (int i = 1; i <= 9; i++){
double botPrecent = ((double) botsMoney.get(i) / totalMoney) * 100;
String botName = players.get(i);
System.out.println(botName + " has " + botPrecent + "%");
}
System.out.println(playerName + " has " + playerChance + "%");
return true;
}
Also I tried setting up a timer which I don't understand how, I've looked up Timer online but I just can't understand the explanations.
I try to save both user input after the iteration, but I'm not sure how to do it. I always get
java:19: error: variable x might not have been initialized
long resalt = bio(x, y);
Source code:
import java.util.Scanner;
public class Aufgabe11 {
public static void main (String [] args) {
Scanner pit = new Scanner(System.in);
System.out.println("Enter fac number");
long a = pit.nextLong();
long result = recFac(a);
System.out.println("The factorial of" + " "+ a + " " + "is"+ " " + result);
Scanner pat = new Scanner(System.in);
long[] vars = new long [2];
for(int i = 0; i < vars.length; i++){
System.out.println("Enter bio var:");
vars [i] = pat.nextLong();
}
long x,y = pat.nextLong();
long resalt = bio(x, y);
System.out.println("The bio of" + " " + x + "over" + y + "is" + " " + resalt);
}
public static long recFac (long a) {
if (a <= 1) {
return 1;
}
else {
return a * recFac (a-1);
}
}
public static long bio (long x, long y) {
if ((x == y) || (y == 0))
return 1;
else
return bio (x-1, y) + bio (x-1, y-1);
}
}
I am very new to learning Java and currently I am working on a program that lets me fight the computer based on simple stats that I have assigned us and a random number to function as a dice roll. I recognize that there may be numerous other problems with my code, but the main issue I am trying to resolve is the "Syntax error on tokens, delete these tokens" on line 84 and the "Syntax error, insert "}" to complete Statement" on line 77.
I don't see what the issue is. What am I doing wrong? Both issues are listed near the bottom of my code in comments next to their corresponding lines.
import java.util.Scanner;
import java.util.Random;
public class Fight {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name");
String you = keyboard.next();
int youWounds = 1;
int youTough = 4;
int youAttack = 1;
int youWS = 4;
int youAS = 3;
String Comp = "Bad Guy";
int compWounds = 1;
int compTough = 4;
int compAttack = 1;
int compWS = 4;
int compAS = 3;
System.out.println(you + ", do you want to FIGHT?!?!?");
System.out.println("Yes / No?");
String inputString = keyboard.next();
if (inputString.equalsIgnoreCase("Yes")) {
System.out.println("FIGHT!!!!");
while (youWounds > 0 && compWounds > 0) {
int youRan = new Random().nextInt(6)+1; // this is where you roll to hit
System.out.println(you + " rolls " + youRan +" to hit");
if (youRan >= 7-youWS) { // this is the logic for roll to hit
System.out.println(you +" hit");
int youRanTW = new Random().nextInt(6)+1; // this is where you check to see if your hit wounds
System.out.println(you + " rolls " + youRanTW +" to wound");
if (youRanTW > compTough) { // this is the logic for roll to wound
System.out.println(you+" wounds"+Comp);
compWounds = compWounds - 1; // this is where comp loses a wound
if (compWounds <= 0) { // this is the logic for wound loss
System.out.println(Comp+" dies!!!");
} else {
System.out.println("But, "+Comp+" fights on!");
}
} else {
System.out.println(you=" does not wound");
}
} else {
System.out.println(you +" misses");
}
int compRan = new Random().nextInt(6)+1;
System.out.println(Comp+" rolls " + compRan + " to hit");
if (compRan >= 7-compWS) { // this is the logic for roll to hit
System.out.println(Comp +" hit");
int compRanTW = new Random().nextInt(6)+1; // this is where you check to see if your hit wounds
System.out.println(Comp + " rolls " + compRanTW +" to wound");
if (compRanTW > youTough) { // this is the logic for roll to wound
System.out.println(Comp+" wounds"+you);
youWounds = youWounds - 1; // this is where you loses a wound
if (youWounds <= 0) { // this is the logic for wound loss
System.out.println(you+" dies!!!");
} else {
System.out.println("But, "+you+" fights on!");
}
} else {
System.out.println(Comp=" does not wound");
}
} else {
System.out.println(Comp +" misses");
}
} else { // this is wher I get "Syntax error, insert "}" to complete Statement". The "}" is underlined in red on my screen
if (youWounds <=0){
System.out.println(Comp+" WINS!!!!");
} else {
System.out.println(you+" WINS!!!!");
}
}
} else { // this is where i get "Syntax error on tokens, delete these tokens". it wants me to delete "} else".
System.out.println(you + " you are a looser!!!!!!!!");
}
keyboard.close();
}
}
There are a few issues with the flow of your program, but the current problem is that you are trying to use else on your while loop. This is not possible or necessary.
The while loop will continue until the defined condition is met. Once that happens, the while loop ends and the next line of code is executed.
So, remove the else { from the closing of the while loop. You can then just evaluate the results.
Here's the corrected code, with a couple comments to show WHERE to remove things:
import java.util.Random;
import java.util.Scanner;
public class Fight {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name");
String you = keyboard.next();
int youWounds = 1;
int youTough = 4;
int youAttack = 1;
int youWS = 4;
int youAS = 3;
String Comp = "Bad Guy";
int compWounds = 1;
int compTough = 4;
int compAttack = 1;
int compWS = 4;
int compAS = 3;
System.out.println(you + ", do you want to FIGHT?!?!?");
System.out.println("Yes / No?");
String inputString = keyboard.next();
if (inputString.equalsIgnoreCase("Yes")) {
System.out.println("FIGHT!!!!");
while (youWounds > 0 && compWounds > 0) {
int youRan = new Random().nextInt(6) + 1; // this is where you roll to hit
System.out.println(you + " rolls " + youRan + " to hit");
if (youRan >= 7 - youWS) { // this is the logic for roll to hit
System.out.println(you + " hit");
int youRanTW = new Random().nextInt(6) + 1; // this is where you check to see if your hit wounds
System.out.println(you + " rolls " + youRanTW + " to wound");
if (youRanTW > compTough) { // this is the logic for roll to wound
System.out.println(you + " wounds" + Comp);
compWounds = compWounds - 1; // this is where comp loses a wound
if (compWounds <= 0) { // this is the logic for wound loss
System.out.println(Comp + " dies!!!");
} else {
System.out.println("But, " + Comp + " fights on!");
}
} else {
System.out.println(you = " does not wound");
}
} else {
System.out.println(you + " misses");
}
int compRan = new Random().nextInt(6) + 1;
System.out.println(Comp + " rolls " + compRan + " to hit");
if (compRan >= 7 - compWS) { // this is the logic for roll to hit
System.out.println(Comp + " hit");
int compRanTW = new Random().nextInt(6) + 1; // this is where you check to see if your hit wounds
System.out.println(Comp + " rolls " + compRanTW + " to wound");
if (compRanTW > youTough) { // this is the logic for roll to wound
System.out.println(Comp + " wounds" + you);
youWounds = youWounds - 1; // this is where you loses a wound
if (youWounds <= 0) { // this is the logic for wound loss
System.out.println(you + " dies!!!");
} else {
System.out.println("But, " + you + " fights on!");
}
} else {
System.out.println(Comp = " does not wound");
}
} else {
System.out.println(Comp + " misses");
}
} // REMOVE THE ELSE AND BRACKET
if (youWounds <= 0) {
System.out.println(Comp + " WINS!!!!");
} else {
System.out.println(you + " WINS!!!!");
}
// REMOVE THIS BRACKET
} else { // this is where i get "Syntax error on tokens, delete these tokens". it wants me to delete "} else".
System.out.println(you + " you are a looser!!!!!!!!");
}
keyboard.close();
}
}
I am trying to store the data that's created in the while loop in the list variable so that I can use it later with the JOptionPane.INFORMATION_MESSAGE.
I tried using an array to store the data but it would not work.
Please let me know what I am missing.
package loops;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Statistics
{
public static void main(String[] args)
{
int observations = 1,
num = 0,
sum = 0,
max = Integer.MIN_VALUE,
min = Integer.MAX_VALUE;
double mean = 0.0;
String userEntry = "",
result,
list = " ",
seperator = "\n***********\nYou entered the following observations: ";
DecimalFormat twoDigits = new DecimalFormat ("0.00");
userEntry = JOptionPane.showInputDialog ("Enter observation # " + observations +
" (or \"end\" to quit) ");
//num = Integer.parseInt(userEntry);
String[] list2 = new String[num];
while(!userEntry.equalsIgnoreCase("end"))
{
num = Integer.parseInt(userEntry);
observations ++;
userEntry = JOptionPane.showInputDialog ("Enter observation #" + observations +
" (or \"end\" to quit) ");
//num = Integer.parseInt(userEntry);
//num = Integer.parseInt(userEntry);
//list = "\n" + num;
//list = list.toString();
sum += num;
if(num > max)
{
max = num;
}
if(num < min)
{
min = num;
}
//Integer.toString(num);
//ArrayList<String> list = new ArrayList<String>();
//list.add(num);
//list = "\n" + Integer.toString(num);
//String[] list2 = new String[num];
//for(String list1 : list2)
//{
list = "\n" + num;
//}
}
observations --;
mean = sum / (double)observations;
//twoDigits.format(mean);
if(observations == 0)
{
result = "no observations selected";
}
else
{
result = "You entered " + observations +
(observations == 1 ? " observation" : " observations");
result = result + "\nThe minimum is " + min;
result = result + "\nThe maximum is " + max;
result = result + "\nThe sum is " + sum;
result = result + "\nThe mean is " + twoDigits.format(mean);
result = result + seperator;
result = result + list;
}
JOptionPane.showMessageDialog(null, result,
"Results", JOptionPane.INFORMATION_MESSAGE);
//observations --;
System.exit(0);
}
}
Try using ArrayList instead of []. Example based on your code is shown below.
package loops;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Statistics {
public static void main(String[] args) {
// method local variables
int observations = 0;
int num = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double mean = 0.0;
String userEntry = "";
String result;
String list = " ";
String seperator = "\n***********\nYou entered the following observations: ";
DecimalFormat twoDigits = new DecimalFormat("0.00");
ArrayList<Integer> intList = new ArrayList<Integer>();
// get user entry from JOptionPane
userEntry = JOptionPane.showInputDialog("Enter observation # " + observations + " (or \"end\" to quit) ");
// iterate until user enters end
while (userEntry.equalsIgnoreCase("end") == false) {
observations++;
num = Integer.parseInt(userEntry);
userEntry = JOptionPane.showInputDialog("Enter observation #" + observations + " (or \"end\" to quit) ");
sum = sum + num;
// change number to max if > max
if (num > max) {
max = num;
}
// change number to min if < min
if (num < min) {
min = num;
}
// add the number to the string and to the list
list = list + "\n" + num;
intList.add(num);
}
echoList(intList);
mean = sum / (double) observations;
if (observations == 0) {
result = "no observations selected";
}
else {
result = "You entered " + observations + (observations == 1 ? " observation" : " observations");
result = result + "\nThe minimum is " + min;
result = result + "\nThe maximum is " + max;
result = result + "\nThe sum is " + sum;
result = result + "\nThe mean is " + twoDigits.format(mean);
result = result + seperator;
result = result + list;
}
// show results and exit
JOptionPane.showMessageDialog(null, result, "Results", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
private static void echoList(ArrayList<Integer> intList) {
System.out.println("------------------------------");
System.out.println("Got " + intList.size() + " integers.");
for(Integer i : intList) {
System.out.println("\t" + i);
}
System.out.println("------------------------------");
}
}
JOptionPane.showInputDialog() will return the string the user has entered if the user hits ok, and returns null otherwise.
Therefore, if the user hits cancel, your while condition (userEntry.equalsIgnoreCase("end") == false) will throw a NullPointerException.
Therefore, it's safer to change the while condition to (userEntry != null).
Now, if you want to store all the user entries, use a list of integers, say List<Integer> userEntries
List<Integer> userEntries = new ArrayList<>();
while (userEntry.equalsIgnoreCase("end") == false)
{
observations++;
num = Integer.parseInt(userEntry);
userEntries.add(num);
...
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is my code for a program that should count the number of each letter in an inputted string. When I run the program, it says that there is 0 of each letter, no matter what I input. Thanks for the help in advance!
import java.util.Scanner;
public class stringprogram {
public static void stringinputmethod()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
int strslength = strs.length();
int numa = 0;
int numb = 0;
int numc = 0;
int numd = 0;
int nume = 0;
int numf = 0;
int numg = 0;
int numh = 0;
int numi = 0;
int numj = 0;
int numk = 0;
int numl = 0;
int numm = 0;
int numn = 0;
int numo = 0;
int nump = 0;
int numq = 0;
int numr = 0;
int nums = 0;
int numt = 0;
int numu = 0;
int numv = 0;
int numw = 0;
int numx = 0;
int numy = 0;
int numz = 0;
for(int i = 0; i <= strslength; i++)
{
if (strs.substring(i, i) == "a")
{
numa = numa + 1;
}
if (strs.substring(i, i) == "b")
{
numb = numb + 1;
}
if (strs.substring(i, i) == "c")
{
numc = numc + 1;
}
if (strs.substring(i, i) == "d")
{
numd = numd + 1;
}
if (strs.substring(i, i) == "e")
{
nume = nume + 1;
}
if (strs.substring(i, i) == "f")
{
numf = numf + 1;
}
if (strs.substring(i, i) == "g")
{
numg = numg + 1;
}
if (strs.substring(i, i) == "h")
{
numh = numh + 1;
}
if (strs.substring(i, i) == "i")
{
numi = numi + 1;
}
if (strs.substring(i, i) == "j")
{
numj = numj + 1;
}
if (strs.substring(i, i) == "k")
{
numk = numk + 1;
}
if (strs.substring(i, i) == "l")
{
numl = numl + 1;
}
if (strs.substring(i, i) == "m")
{
numm = numm + 1;
}
if (strs.substring(i, i) == "n")
{
numn = numn + 1;
}
if (strs.substring(i, i) == "o")
{
numo = numo + 1;
}
if (strs.substring(i, i) == "p")
{
nump = nump + 1;
}
if (strs.substring(i, i) == "q")
{
numq = numq + 1;
}
if (strs.substring(i, i) == "r")
{
numr = numr + 1;
}
if (strs.substring(i, i) == "s")
{
nums = nums + 1;
}
if (strs.substring(i, i) == "t")
{
numt = numt + 1;
}
if (strs.substring(i, i) == "u")
{
numu = numu + 1;
}
if (strs.substring(i, i) == "v")
{
numv = numv + 1;
}
if (strs.substring(i, i) == "w")
{
numw = numw + 1;
}
if (strs.substring(i, i) == "x")
{
numx = numx + 1;
}
if (strs.substring(i, i) == "y")
{
numy = numy + 1;
}
if (strs.substring(i, i) == "z")
{
numz = numz + 1;
}
}
System.out.println("Number of a's: " + numa + "\n" + "Number of b's: " + numb + "\n" + "Number of c's: " + numc + "\n" + "Number of d's: " + numd + "\n" + "Number of e's: " + nume + "\n" + "Number of f's: " + numf + "\n" + "Number of g's: " + numg + "\n" + "Number of h's: " + numa + "\n" + "Number of i's: " + numi + "\n" + "Number of j's: " + numj + "\n" + "Number of k's: " + numk + "\n" + "Number of l's: " + numl + "\n" + "Number of m's: " + numm + "\n" + "Number of n's: " + numn + "\n" + "Number of o's: " + numo + "\n" + "Number of p's: " + nump + "\n" + "Number of q's: " + numq + "\n" + "Number of r's: " + numr + "\n" + "Number of s's: " + nums + "\n" + "Number of t's: " + numt + "\n" + "Number of u's: " + numu + "\n" + "Number of v's: " + numv + "\n" + "Number of w's: " + numw + "\n" + "Number of x's: " + numx + "\n" + "Number of y's: " + numy + "\n" + "Number of z's: " + numz);
}
public static void main(String[] args)
{
stringinputmethod();
}
}
Correct usage of the substring method:
strs.substring(i, i)
needs to be
strs.substring(i, i + 1)
because the char at lastIndex is not included in the output.
Correct comparison of Strings in Java
Also, as pointed out in the comments to this answer, you are comparing Strings with the == operator.
This will only works as long as both your Strings are the same object. For proper comparison you need to use strs.substring(..).equals()
Proper storing of data
Additionally, as already suggested in a comment to your question, you should start using arrays to save data like this.
Instead of
int numa = 0;
....
int numz = 0;
you should use arrays, or even better Map<Character,Integer>.
strs.substring(i, i) == "a" have two problems:
substring(i, i) creates string from i (inclusive), till i (exclusive) which means it creates empty string ""
this is not how we compare Strings. == may work sometimes if strings are pooled, but for dynamically created strings you need to use equals instead of == because Strings are objects, or even better use charAt(i) to get primitive char which you can be able to compare like strs.charAt(i) == 'a' (notice ' instead of ").
You can also use enhanced for loop on array of characters representing your string to avoid charAt. You should probably also be working on lower case characters as pointed in this comment. So your code can look more like
for (char ch : strs.toLowerCase().toCharArray()){
//do something based on value of `ch`
}
Try this:
It is a little bit shorter than your implementation (which is very good, but still a little bit verbose). Use Java 8 with this code, otherwise it won't compile.
What does it do?
If you understand that a string is nothing more but an array you can iterate over that array and see what kind of value is at the given index. The value at this index is put in a map (remember, a map is a key-value-store). So if you put the Integer 1 in the map where its key is "a", that means "a" occurs 1 time.
By reading the values at the appropriate indexii (very sophisticated plural form of index) with HashMap.get("a") and then incrementing the value by one, we have a nice little letter counter... without the need to predefine numa=0 and so forth. Give it a try and let me know if it werx.
package lettercounter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
/**
*
* #author edm
*/
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
//this map will be populated with the occurrence of the letters in the string.
HashMap<String, Integer> countenLetters = new HashMap<>();
//the next line generates a key-value-store whose key is the letter in the string
//and the value is the accumulated occurrence of said letter.
Arrays.asList(strs.split("")).stream().forEach((String letter) -> {
Integer count = 0;
try {
count = countenLetters.get(letter).intValue();
} catch (Exception e) {
//tried to access a non existing value in the map
//this happens if there is a letter which was not set in the map until now.
//i.e. the first time the letter is encountered.
//this is no error. could have done it with an if also.
}
countenLetters.put(letter, ++count);
});
//do with this stuff what you want;
countenLetters.forEach((k,v) -> {
System.out.println("Letter "+k+" occurs "+v+" times in the string.");
});
}
}