variable doesn't increase when code is executed - java

Tester is called and executed if the player inputs a certain name.
Variable testerWrong doesnt add one when testerWrong++ is executed
private void Tester(){
int testerTotal;
int testerScore;
int testerWrong;
testerTotal = 0;
testerScore = 0;
testerWrong = 0;
System.out.println("");
System.out.println("Hello tester, you're the designated tester. Would you like to take the quiz? Y/N");
Scanner yesno = new Scanner(System.in);
String YesNo = yesno.next();
if(YesNo.equals("Y") || YesNo.equals("y")){ //This type of code will appear very often
System.out.println("Okay, let's being!"); //if the user input (YesNo) is Y or y then...
}else{
if(YesNo.equals("N") || YesNo.equals("n")){
System.out.println("Okay, maybe some other time");
}else{ //else...
System.out.println("Sorry, i do not recognise what you entered. Please restart the program.");
}
}
System.out.println("");
QUIZ enter = new QUIZ();
enter.e2c();
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Question #1");
System.out.println("");
System.out.println("The answer is A");
System.out.println("");
System.out.println(" - A. ");
System.out.println(" - B. ");
System.out.println(" - C. ");
System.out.println(" - D. ");
Scanner testerQ1 = new Scanner(System.in);
String TesterQ1 = testerQ1.next();
if(TesterQ1.equals("A") || TesterQ1.equals("a")){
testerScore++;
System.out.println("Correct! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
System.out.println("");
System.out.println("Next Question.");
System.out.println("");
}else{
testerWrong++;
System.out.println("Incorrect! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
System.out.println("");
}
Is there a way to make the variable execute without having to add a system output before it?
Thanks

This is not a minimal (way too many print statements) or even complete example (the QUIZ class is not included).
Narrowing your code down to a minimum example:
import java.util.Scanner;
public class Tester {
public static void main(String args[]) {
int testerScore = 0;
int testerWrong = 0;
System.out.println("The answer is A");
Scanner scanner = new Scanner(System.in);
String answer = scanner.next();
if (answer.equals("A") || answer.equals("a")) {
testerScore++;
System.out.print("Correct!");
}
else {
testerWrong++;
System.out.println("Incorrect! ");
}
System.out.println(" You hve answered " + testerScore +
" correct and " + testerWrong + " incorrect!");
}
}
This works for me. Compare your code against this and see what you are doing differently.
If you cannot find the problem that way, run your code in a debugger. Step through the program to see what it does when.
You may also want to follow Java naming conventions (variables start with lower case letters, classes start with upper case letters but aren't all upper case), to make it easier for others to read your code.

Related

Trying to create a quiz with java, but something went wrong. What part of my program did i screw up?

So I'm starting to get the hang of java, and I'm creating a quiz as a mini project. However, when I get to the input part of my program, it breaks down. What's going on?
I also apologize for the formatting
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int score = 0;
int total = 0;
System.out.println("Are you ready for a quiz? (Y/N)");
char answer = in.findInLine(".").charAt(0);
if (answer == 'Y' || answer == 'y');
{
String a = "Barrow";
String b = "Juneau";
String c = "Anchorage";
String d = "Annapolis";
System.out.println("Alright! Lets get right to it!");
System.out.println("What is the Capital of Alaska?");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
char choice = in.findInLine(".").charAt(0);
if (choice == 'B' || choice == 'b')
{
System.out.println("Good Job! 1 point for you!");
score = score + 1;
}
else
{
System.out.println("Incorrect! the answer was actually " + b);
}
String e = "Yes";
String f = "No";
System.out.println("Alright, Next Question! Can you"
+ " store the value 'cat' in a variable of type int?");
System.out.println("A: " + e);
System.out.println("B: " + f);
char secchoice = in.findInLine(".").charAt(0);
if (secchoice == 'A' || secchoice == 'a')
{
System.out.println("Correct! Good Job!");
score = score + 1;
}
else
{
System.out.println("Incorrect");
}
System.out.println("What is the result of 2+2X3-5?");
int result = in.nextInt();
if (result == 3)
{
System.out.println("Correct! Good Job!");
}
else
{
System.out.println("Incorrect");
}
System.out.println("Your total score was " + score + "out of 3");
}
}
}
You are getting a NullPointerException on line 26 because of the way that findInLine() works. Basically, you have used up the one line of input you give it when it starts and the Scanner has advanced passed it to find the next one (which does not exist). In other words, you should use another method for Scanner or use an entirely different approach for getting input.
For example, it is preferable to use this technique
char answer = in.nextLine().charAt(0);
because nextLine() will wait until it has more input.
Of course, you will have to come up with some way to parse the input from the user to make sure that it is valid (i.e. if they can only choose between 'Y' and 'N' you handle the case where they choose neither).
That would look something like
char answer = parseInput(in.nextLine().charAt(0));
where parseInput(String s) is a method you write yourself.
As far as other approaches go, this tutorial from Oracle can help you get started.

Do/while loop not returning to the top?

recently started computer programming and I am stuck on a homework assignment. I created a loop but instead of going back to the top, it starts 1 step ahead of where I intended it to. (it's all listed in the comments I made in the coding. I have been trying to figure this out for the past 6 hours so it would greatly appreciated if someone can help me.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
DecimalFormat n = new DecimalFormat("##");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
response = scan.next();
while (response.equals("y"))
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
break;
//not returning to point A, instead it returns to point B
}
if (response.equals("n"))
{
break;
}
if (response.equals("n"))
{
break;
}
}
}
while (response.equals("n"));
System.out.println("Final Tally");
System.out.println("Polly received:\t " + n.format(totalPolly) + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + n.format(totalErnest) + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
My guess is that the string response has already been determine to be y at the end of the loop which is why it skips the first step and jumps right back into the loop assuming my answer is already y.
You will just need to strip your code of unnecessary breaks and also handle the 2 responses differently. Your loop should also continue when the response is y, not the other way round.
See edited code below:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
DecimalFormat n = new DecimalFormat("##");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
String response2 = scan.next();//create a new response variable, so the loop doesn't confuse which response to break on
//I removed the inner loop. If you really intended for this to be an inner loop then the while(response2.equals("y")){} should be around the question, not after
if (response2.equals("y"))
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
}
//removed the unnecessary checks for when response in 'n'
}
}
while (response.equals("y"));
System.out.println("Final Tally");
System.out.println("Polly received:\t " + n.format(totalPolly) + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + n.format(totalErnest) + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
if (response.equals("n"))
{
break;
}
breaks your while loop.
You might want to loop again if user's response if 'y'.
In that case, use while (response.equals("y"));
Your requirement is to break out if the user enters "n" but loop while the user input is "y", but your code says,
do{
.....
}while (response.equals("n"));
It should be,
while (response.equals("y"));
do {
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
#code
if (response.equals("n")) //<--- this 'if' block will break the loop when response equals 'n'
{
break;
}
}
}
while (response.equals("n"));// <----- this means doing loop when response equals "n"
You can see my comment on above block of code, the loop will do one more time only when response equals 'n'. But when response equals 'n', the 'if' block at above of it will break the loop and the while (response.equals("n")) will be not checked.

Let users input create object

I'm writing this program where the user takes a math test. The problem Im now facing and have been trying to fix is how to display the final score at the end of the test.
I have a counter and the score increments for every correct answer, but how do I (at the end) display the final/total score? Any help is appreciated.
This is one of three classes btw.
import java.util.Scanner;
public class Questions {
Scanner scan = new Scanner(System.in);
int answer = 0;
int point = 0;
String correct = "Correct";
public void pointers(){
point++;
System.out.println(point + " point added to total score");
}
public void totalPoints(){
pointers();
}
public void showQuestions(){
System.out.println("\n--------------\nQuestion #1: 1+1 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println(correct);
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #2: 340-23 = ? ");
answer = scan.nextInt();
if(answer == 317){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #3: 900/3 = ? ");
answer = scan.nextInt();
if(answer == 300){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #4: 23*2 = ? ");
answer = scan.nextInt();
if(answer == 46){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #5: -4+6 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
}
}
The problem is that you're trying to get the input first and then you're asking for the age. When you type keyboard.nextInt() it is expecting an input immediately. So the problem is here:
*int age = keyboard.nextInt();
* System.out.println("Age: " + age);
*age = keyboard.nextInt();
My suggestion is to just remove the first keyboard.nextInt():
Example:
System.out.println("\nName: " + name);
name = keyboard.nextLine();
System.out.println("Age: " + age);
final int age = keyboard.nextInt();
and that's about it. Just be careful where you place your method calls, e.g. they should be after your println()'s.
No idea what you try to achieve, but
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
System.out.println("Hello, it is time to take a math test.\nFirst we need you to enter some information about yourself.");
System.out.print("\nEnter name: ");
final String name = keyboard.nextLine();
System.out.print("Enter Age: ");
final int age = keyboard.nextInt();
keyboard.close();
System.out.println("Your personal information: " + name + " of " + age + " years old.");
}
}
output:
C:\Temp\123431>java -classpath .;Main.class Main
Hello, it is time to take a math test.
First we need you to enter some information about yourself.
Enter name: ttt
Enter Age: 321
Your personal information: ttt of 321 years old.
C:\Temp\123431>java -classpath .;Main.class Main

Why isn't my code randomly generating more than once?

Sorry for probably a noobish question but I can't figure out what's wrong with this code. I've looked everywhere but I couldn't find any answer.
The problem is that it will only randomly generate num and num2 once when I need it randomly genereated 5 times. Any help is greatly appreciated.
import java.util.Scanner;
import java.util.Random;
public class Choice5
{
public static void main(String [] args)
{
Random r = new Random();
Scanner k = new Scanner(System.in);
String name;
int num= 1 + r.nextInt(10);
int num2=1 + r.nextInt(10);
int answer = num*num2;
int attempt;
int countcorrect = 0;
int countincorrect =0;
System.out.println("Hi, what's your name?");
name =k.next();
for(int x=1; x<=5; x++)
{
System.out.println("Test " +x+ " of 5");
System.out.println("Ok " +name+ " What is " +num+ " x " +num2+ " ?");
attempt = k.nextInt();
if(attempt == answer)
{
System.out.println("Good Job " +name+ " the answer was indeed " +answer);
countcorrect++;
}
if(attempt != answer)
{
System.out.println("Incorrect " +name+ " the answer was actually " +answer);
countincorrect++;
}
}
System.out.println("You got " +countcorrect+ " right");
System.out.println("You got " +countincorrect+ " wrong");
if (countcorrect < 3)
{
System.out.println("You should try the test again");
}
else
{
System.out.println("Good job " +name+ " ,you passed the test!");
}
}
}
You are choosing random numbers for num and num2 exactly once, toward the top of main, and more importantly, before the for loop. These numbers aren't assigned again, so they remain the same during all loop iterations.
To have them change for each loop iteration, declare the variables for the numbers and the answer, and assign new values inside the for loop, instead of before it.
for(int x=1; x<=5; x++)
{
int num= 1 + r.nextInt(10);
int num2=1 + r.nextInt(10);
int answer = num*num2;
// rest of code is the same
You generate a random number when, in this case, you call nextNum() As you can see you only call this once for num and num2 since it is out of the loop.
Simple answer, put those calls within your loop to create more than one random number.

Why isn't my program able to read the text file after the encountering the first error message?

import java.util.*; // needed for scanner
import java.io.*; // needed to read text file
public class MainC
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); // scanner is established
System.out.println("Welcome to the Tourist Site Simulator. In this program, we will allow you to simulate a European experience by traveling to a country in Europe"
+ "and staying there for a set number of days. "); // general explanation
int count = 0, time = 10; // for possible repetition of instructions
try {
BufferedReader file = new BufferedReader(new FileReader("Countries.txt"));
while(count == 0){
System.out.println("First of all, which of the fifty sovereign states of Europe would you like to visit?");
String country = scan.next();
while (file.ready()){
String countryF = file.readLine();
String cityF1 = file.readLine();
String cityF2 = file.readLine();
String cityF3 = file.readLine();
String squiq = file.readLine();
if(countryF.equalsIgnoreCase(country)){
count++;
int count2 = 0;
while(count2 == 0){
country = country.substring(0,1).toUpperCase() + country.substring(1);
System.out.println("Country: " + country);
System.out.println("");
System.out.println("The largest cities at this nation are " + cityF1 + ", " + cityF2 + ", " +cityF3 + ". Which one would you like to visit?");
String city = scan.next();
if(cityF1.equalsIgnoreCase(city)||cityF2.equalsIgnoreCase(city)||cityF3.equalsIgnoreCase(city)){
count2++;
city = city.substring(0,1).toUpperCase() + city.substring(1);
System.out.println("");
System.out.println("Country: " + country);
System.out.println("City: " + city);
System.out.println("");
System.out.println("How many days will you be staying?");
int days = scan.nextInt();
System.out.println("");
System.out.println("Country: " + country + " Number of Days Left: " + days);
System.out.println("City: " + city);
System.out.println("");
System.out.println("What is the your rate of currency exchange to one Euro?");
double rate = scan.nextDouble();
}else{
System.out.println("I must regretfully inform you that this city is not in our listed database. Please try again.");
System.out.println("");
}
}//while count == 2
}//while file.ready()
}//while count == 0
if(count == 0)
{
System.out.println("I must regretfully inform you that this country in not in our listed database. Please try again.");
System.out.println("");
}
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
Hi there. I was having problems with this code. What it should be doing is that if the user enters an incorrect country, a loop will be initiated and the user will be asked for the country again. My problem is that after this error message comes up and the user is asked for the country again, it repeatedly asks the question regardless of whether the input is correct or not. Thank you.
I think it may be because you have your
if(countryF.equalsIgnoreCase(country))
and then from what I can see is the if statement after that is this
if(count == 0)
So your count never gets to increment if it is the wrong country.
try this instead
if(countryF.equalsIgnoreCase(country){
}else(instead of if count == 0){
"print wrong country try again"
}
You don't really need this either
while(count ==0)
try putting a second scan catcher in the else statement.
if(countryF.equalsIgnoreCase(country){
}else(instead of if count == 0){
"print wrong country try again"
country = scan.next();
}

Categories