I am coding a quiz game in Java and I can't figure out how to find the average number of guesses a user makes. Here is the game in simple code:
import java.util.Scanner;
import java.io.File;
public class JavaQuiz
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
File file = new File("questions.txt");
Scanner scan = new Scanner(file);
String line;
double lineNum = 0;
int skip = 0;
int correct = 0;
double guesses = 0;
while(scan.hasNextLine()){
// Counting of the line number
lineNum = lineNum + 1;
// Scanning the next line
line = scan.nextLine();
// Declaring the delimeter.
String delimiter = "\\|";
// Splitting the line
String[] temp = line.split(delimiter);
// Print out the questions
System.out.println(temp[0]);
// Wait for the user to input
String keyboard = input.next();
// Take the space off the answer
String two = temp[1].replaceAll("\\s","");
if(keyboard.equals("q")){
skip = skip + 1;
}
else{
while(!(keyboard.equals(two)) && !(keyboard.equals("q"))){
keyboard = input.nextLine();
if(keyboard.equals("q")){
skip = skip + 1;
} else {
System.out.println("Incorrect. Please Try Again");
}
}
if(keyboard.equals(two)){
correct = correct + 1;
}
}
}
System.out.println("You got " + correct + " Questions Correct.");
System.out.println("You skipped " + skip + " questions.");
System.out.println("And for the questions you completed, you averaged " + avg + " guesses.");
}
}
Should I do something like this?
double avg = guesses / lineNum;
I am getting an answer of 0 no matter what though.
After this Line :String keyboard = input.next();
You should do something like this:
if(!(keyboard==null))
guesses++;
then you are right when: avg=guesses/lineNum;
*Tip guesses & lineNum should be int where guesses represents the number of times he answered and lineNum represents the number of lines.There is no need to double here
int takes less space than double on Ram
Related
I'm just starting Java and this is a coin flip program that I've written recently. So it's supposed to produce sequences of coin flips that meet the requirements that the user sets, however when it gets to the end it should ask if the user wants to go again. I'm having an issue where it will print the question twice when it gets down to end. I really need to figuer this out so any suggestions/clarifications for my code would be greatly appreciated.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
outer: while (true) {
System.out.print("Ready to run a coin flip simulation. Enter the number of sequences: ");
int sequences = scan.nextInt();
System.out.print("How many heads should each sequence have? ");
int heads = scan.nextInt();
System.out.print("How many tails should each sequence have? ");
int tails = scan.nextInt();
System.out.println("Simulating Sequences");
int tFlips = 0;
int mFlips = 0;
for (int i = 1; i <= sequences; i++) {
int h = 0;
int t = 0;
String s = "";
while (t < tails || h < heads) {
if (Math.random() < 0.5) {
h++;
s += "H";
} else {
t++;
s += "T";
}
tFlips++;
}
if (t + h > mFlips) {
mFlips = t + h;
}
System.out.println(i + " - " + s);
h = 0;
t = 0;
s = "";
}
System.out.printf("The average number of flips was " + ((float) tFlips / sequences) + " and maximum was %d", mFlips);
System.out.println("\r\n");
boolean go = true;
while (go) {
System.out.print("Would you like to run another simulation? (y/n): ");
String c = scan.nextLine();
if (c.equalsIgnoreCase("y")) {
break;
} else if (c.equalsIgnoreCase("n")) {
break outer;
} else {
continue;
}
}
System.out.print("\r\n");
}
}
Your String c = scan.nextLine(); reads a new line from your scan.nextInt() calls. You can read more here Scanner is skipping nextLine() after using next() or nextFoo()?
It is good practice to call .nextLine() after every call to .nextInt() to always consume the newline character.
Change the String c = scan.nextLine(); to String c = scan.next();. And you don't really need the while(go) loop, it's more simple if you're doing this:
System.out.print("Would you like to run another simulation? (y/n): ");
String c = scan.next();
if (!c.equalsIgnoreCase("y"))
break;
P.S.: here is a good answer why the nextLine() isn't working correctly. (by #Rohit Jain)
Hi I'm a novice coder and I've been up all night trying to figure this out.
I'm working on a hangman game where the user has to input the letter they want to guess with and the number of spaces they want to check. The word is of course hidden by dashes. When the user gets a letter correct in the right space i'm suppose to print out the hidden word with the letters and spaces guessed correctly. for example
Word: loops
Hidden: -----
What letter would you like to guess:
o
Which spaces would you like to check:
1 2
Hidden: -oo--
I know that Strings are immutable so I have to create a new string and concatinate it with the substring and the letter that user inputed but the position changes so I have to re order how I concatinate it every time correct?
And I'm not allowed to use arrays, StringBuilder, or StringBuffer
I hope I explained this clear enough
here is what I've done so far
Scanner keyboard = new Scanner(System.in);
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
diff = diff.substring(0, 1);
String guess = "";
String newGuess = "";
String newWord = "loops";//RandomWord.newWord();
int y = 0;
int count = 0;
for (int i = 0; i < newWord.length(); i++) {
newWord.charAt(i);
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
System.out.println("The secret word is:" + " " + newWord);
System.out.println("The word is:" + " " + guess);
System.out.println("Please enter the letter you want to guess");
String letterInput = keyboard.next();
System.out.println("Please enter the spaces you want to check (seperated by spaces)");
String spaces = keyboard.nextLine();
spaces = keyboard.nextLine();
System.out.println(Character.getNumericValue(spaces.trim().charAt(count)));
for (int i = 0; i < spaces.trim().length(); i++) {
int x = Character.getNumericValue(spaces.trim().charAt(i));
if (x == 0) {
y = x - 1;
y = 0;
if ((letterInput.equalsIgnoreCase(newWord.substring(x, x + 1)))) {
newGuess = guess.substring(0, y) + guess.substring(y, x) + letterInput + guess.substring(x + 1);
System.out.println(newGuess);
}
}
else if ((letterInput.equalsIgnoreCase(newWord.substring(x, x + 1)))) {
newGuess = guess.substring(0, x) + guess.substring(x, x + 1) + letterInput + guess.substring(x + 1);
System.out.println(newGuess);
}
}
}
}
The only problem here is Scanner is playing with you:
Default delimiter for scanner is white-space character hence when you enter for options including space scanner reads only first character.
There were couple of problems with your Substring method also, I have tweaked your code a bit:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n"); \\---------- this is what tells scanner to use new line char as delimiter
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
String guess = "";
String newGuess = "";
String newWord = "loops";//RandomWord.newWord();
int y = 0;
int count = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
System.out.println("The secret word is:" + " " + newWord);
System.out.println("The word is:" + " " + guess);
System.out.println("Please enter the letter you want to guess");
String letterInput = keyboard.next();
System.out.println("Please enter the spaces you want to check (seperated by spaces)");
String spaces = keyboard.next();
for (String s : spaces.split("\\s")) {
int x = Integer.valueOf(s);
if (newWord.charAt(x) == letterInput.charAt(0)) {
System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
System.out.println(guess);
}
}
}
}
}
Hope this helps! You almost got there
Good luck!
I have to write a program that asks the user to enter an integer value. After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even.
I have done this so far with a do-while loop, but I am confused on how to get the averages of the values the user enters. How would you get the average for all the numbers entered?
Here is my code so far:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
From the Question looks like following things need to handled,
haven't add mechanism for addition into single variable.
put all variable to out from do...while loop body...
created additional variable according to requirement.
see all this things covered by me with following code snippet.
do something likewise,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
In order to calculate Average, you need 2 things: Sum of all numbers and Count of all numbers involved in the Average calculation.
Your sum and count which involved in the Average calculation needs to be out of the do..while scope in order for them to be known at the calculation stage.
I also took the liberty of fixing your code a little bit
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int count = 0;
int sum = 0;
String answer = "";
do {
System.out.print("Enter any number : ");
int num = scan.nextInt();
boolean isEven = (num % 2 == 0);
System.out.println(num + " is an " + (isEven ? "even" : "odd") + " number.");
sum += num;
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.toLowerCase().equals("y"));
System.out.println("Average: " + (sum/count));
}
}
Change your code like this:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr is average. that means when you input an integer. we add num and avr . and when finish looping. we divideto count. like this:
1-5-9-11
avr = 1+5+9+11;
count = 4;
avr = avr/4;
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I have following class
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = sc.nextInt();
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
I can't type song name nr 1 because it Always shows first two together.
Like this if I type 3:
How many songs do your CD contain?
3
Please enter song nr 1:
Please enter song nr 2:
Change
int songs = sc.nextInt();
to:
int songs = Integer.parseInt(sc.nextLine().trim());
and it will work fine.
You should not mix usages of nextInt with nextLine.
add sc.nextLine(); after int songs = sc.nextInt();
Once you enter a number and read it using a scanner ( as a number) using sc.nextInt();, the newline character will be present in the input stream which will be read when you do sc.nextLine(). So,to skip(over) it, you need call sc.nextLine() after sc.nextInt();
Add a sc.nextLine() after sc.nextInt() and your code works fine.
The reason is the end of line after you type the nomber of songs.
Either use nextInt or nextLine, I would opt for nextLine:
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = Integer.parseInt(sc.nextLine()); // instead of nextInt()
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
put a sc.nextLine(); after int songs = sc.nextInt();
I have this basic program that works pretty well when entering single digit numbers. But when calculating an expression with multiple digits, like 1337 - 456 + 32, the program doesn't move on...it acts likes I did nothing.
It doesn't freeze or output an error message, it just stops.
here's the code:
import java.io.*;
import java.util.*;
public class Tester {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter number: ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*");
int sum = 0;
int temp = 0;
int intbefore = 0;
if (sc.hasNext("\\-")) {
sc.next();
if (sc.hasNextInt()) {
intbefore = sc.nextInt();
int temper = intbefore * 2;
intbefore = intbefore - temper;
}
}
if (sc.hasNextInt()) {
intbefore = sc.nextInt(); //now its at the sign (intbefore = 5)
}
sum = intbefore;
while (sc.hasNext()) {
if(sc.hasNext("\\+")) { //does it have a plus sign?
sc.next(); //if yes, move on (now at the number)
System.out.println("got to the next();");
if(sc.hasNextInt()) { //if there's a number
temp = sc.nextInt();
sum = sum + temp; //add it by the sum (0) and the sum of (5) and (4)
System.out.println("added " + sum);
}
}
if(sc.hasNext("\\-")) {
sc.next();
System.out.println("got to the next();");
if (sc.hasNextInt()) {
temp = sc.nextInt();
sum = sum - temp; //intbefore - temp == 11
System.out.println("intbefore: " + intbefore + " temp: " + temp);
System.out.println("subtracted " + sum); // subtracted by 11
}
}
}
System.out.println("Sum is: " + sum);
}
}
Help with why this happens and what to do to fix it?
(I'm using netbeans if that helps)
Also, I'm assuming that the input has a space between each number Ex: 123 + -23 - 5
I tried to execute your code and this is what i found.
Suppose your input was 12+1.
Not sc.hasNextInt() will give you 1 which you are assigning to intbefore.
Next the while loop in your code is going to infinite loop cos sc.hasNext() will always be true (and returning 2 in this case ) and it doesn't match the two if conditions inside the while loop thus making your code run in infinite loop. Now go ahead and work on that. All the best.
Try to change the dilimeter as "\\s+" in the first place or just use the default one