I have created that Java programme but it have repetition problem, I want that if one question has done either right or wrong it must not be ask again.
It should ask 10 question only. I have tried alot to change but every time I am getting error.
I have created that Java programme but it have repetition problem, I want that if one question has done either right or wrong it must not be ask again.
It should ask 10 question only. I have tried alot to change but every time I am getting error.
package examapp;
import java.util.Random;
import javax.swing.JOptionPane;
public class Examapp {
static int nQuestions = 0; static int nCorrect = 0;
public static void main(String[] args) {
int prevNum=0;
int sum=0;
do{
Random rand = new Random();
int randomNum = rand.nextInt((11 - 1) + 1) + 1;
if(randomNum==prevNum){
prevNum=randomNum;
}
else if(randomNum==1){
String question1;
question1 = "What was the name of Google in late 90s?\n";
question1+="A. Googol\n";
question1+="B. Gigablast\n";
question1+="C. Backrub\n";
question1+="D. Google\n";
question1+="Marks=9";
check(question1,"C");
sum=sum+1;
}
else if(randomNum==2){
String question2;
question2 = "\"Do no evil\" is a tagline of?\n";
question2+="A. Yahoo\n";
question2+="B. Google\n";
question2+="C. Bing\n";
question2+="D. Duck Duck Go\n";
question2+="Marks=9";
check(question2,"B");
sum=sum+1;
}
else if(randomNum==3){
String question3;
question3 = "Which of the following is fully Object Oriented Programming Language?\n";
question3+="A. SmallTalk\n";
question3+="B. Kotlin\n";
question3+="C. Java\n";
question3+="D. F#\n";
question3+="Marks=9";
check(question3,"A");
sum=sum+1;
}
else if(randomNum==4){
String question4;
question4 = "Which among the following is not a mobile Operating System?\n";
question4+="A. Bada\n";
question4+="B. Safari\n";
question4+="C. WebOS\n";
question4+="D. MeeGo\n";
question4+="Marks=9";
check(question4,"B");
sum=sum+1;
}
else if(randomNum==5){
String question5;
question5 = "Which of the following is a correct format of Email address?\n";
question5+="A. info.website.com\n";
question5+="B. info#website.com\n";
question5+="C. info#website#com\n";
question5+="D. info.website#com\n";
question5+="Marks=9";
check(question5,"B");
sum=sum+1;
}
else if(randomNum==6){
String question6;
question6 = "What is the shortcut key of printing a document for computer having windows?\n";
question6+="A. Ctrl + Shift + P\n";
question6+="B. Alt + P\n";
question6+="C. Ctrl + Alt + P\n";
question6+="D. Ctrl + P\n";
question6+="Marks=9";
check(question6,"D");
sum=sum+1;
}
else if(randomNum==7){
String question7;
question7 = "Computer software includes\n";
question7+="A. Packaged programs\n";
question7+="B. Operating system programs\n";
question7+="C. Applications programs\n";
question7+="D. All of these\n";
question7+="Marks=9";
check(question7,"D");
}
else if(randomNum==8){
String question8;
question8 = "A function inside another function is called a _______ function\n";
question8+="A. Nested\n";
question8+="B. Round\n";
question8+="C. Sum\n";
question8+="D. Grouped\n";
question8+="Marks=9";
check(question8,"A");
sum=sum+1;
}
else if(randomNum==9){
String question9;
question9 = "What does HTTP stands for?\n";
question9+="A. Hypertext Transfer Plotter\n";
question9+="B. Hypertext Transfer Plot\n";
question9+="C. Hypertext Transfer Protocol\n";
question9+="D. Head Tail Transfer Protocol\n";
question9+="Marks=9";
check(question9,"C");
sum=sum+1;
}
else if(randomNum==10){
String question10;
question10 = "The term 'Pentium' is realted to\n";
question10+="A. DVD\n";
question10+="B. Hard Disk\n";
question10+="C. Microprocessor\n";
question10+="D. Mouse\n";
question10+="Marks=9";
check(question10,"C");
sum=sum+1;
}
else{
prevNum=randomNum;
}
}while(sum<=9);
JOptionPane.showMessageDialog(null,nCorrect + " correct out of 10" + " questions");
JOptionPane.showMessageDialog(null,"Total Obtained Marks="+(nCorrect*9));
}
public static String ask(String question) {
while(true) {
String answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
if(!(answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("D"))){
JOptionPane.showMessageDialog(null,"Invalid Answer");
continue;
}
return answer;
}
}
static void check(String question, String correctAnswer) {
nQuestions++;
String answer = ask(question);
if(answer.equals(correctAnswer)) {
nCorrect++;
}
else {
}
}
}
Thank you!
Your main is quite cluttered. By the time you get to the bottom, you have already forgotten what was on top, such as that it is a very large do-while block. If I were you, I would put the questions and answers in an array, list or even better in your own question object. Then you could use array shuffle to put them in different order for each run and omit all the if-else blocks. It is best to also pull your initialization from random out of the loop so that you don't create a new object with every iteration.
In order to answer your question, so that you do not use an already generated random number again, you must somehow remember the already generated ones. For example, use a list.
public static void main(String[] args) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int count = 0;
int randomNum;
do{
randomNum = rand.nextInt(10)+1;
while(list.contains(randomNum)){
randomNum = rand.nextInt(10)+1;
}
list.add(randomNum);
count++;
// rest of your code goes here
}while( count < 10);
System.out.println(list);
}
Related
Hi i'm trying to write a programme similar to a BMI calculator tutorial i followed and completed successfully last fortnight.
However I'm now trying to do a health programme that compares a users temperature/blood pressure and heart beat, and if any are below or above certain values to warn the user via console message.
for example
if
temperature <35 or >39 display a warning message or
heart rate <60 or >150 display a warning message or
blood pressure <100 or >150 display a warning message.
hI am unsure how to convert and compare the value as it says "Operator '<' cannot be applied to 'java.lang.String', 'int'". I have the user input the value in a text field and understand that it is cannot compare text fields, so i tried to convert it to a float using Float.parseFloat(temperatureStr); but that didn't seem to work. Is there something that can change String temperatureStr = temperature.getText().toString(); into an interger so I am able to compare it to a number and then display a warning message?
I am not sure but if i understand you correctly you try to implement something like this:
class UserClassName {
int bodyTemp;
int bloodPressure;
int heartSkip;
public void getUsersValues() {
Scanner body, temp, blood;
body = new Scanner(System.in);
temp = new Scanner(System.in);
blood = new Scanner(System.in);
System.out.println("Your temp ..");
String intputTempAsString = body.nextLine();
try {
bodyTemp = Interger.parseInt(inputTempAsString);
catch {
throw new Exception("Your warning her");
}
// Do this for ever Number or Value you wanna have and it should work
}
// Methods to compare the input
public boolean checkHeartSkiptsFrequncy() {
return heartSkip > 60 && heartskip < 150;
}
public boolean checkBodyTemp() {
return heartSkip > 35 && heartskip < 39;
}
public boolean checkBlood() {
return heartSkip > 100 && heartskip < 150;
}
public boolean checkHealth() {
if(!chechHeartSkipFrequncy) {
System.out.println("The Frequceny of you Heartbeat ....");
else if(!checkBodyTemp) {
System.out.println("Your body Temp is bad...");
else if(!checkBlood) {
System.out.println("Your blood ....");
else {
System.out.println("Everything is fine")
}
I think this is what you are looking for. I know that is not 100% perfect but i hope this it will help you to solve your problem.
This code is also no complete solution for your problem but i tried to cover all important aspekts.
If you have any questions or improvment for me than reply to this post.
Have a nice Day and good luck man.
I'm relevantly new to Java and just started my first semi serious assignment. I'm confident most of my code is working, the only problem is because I've been using classes I can't seem to call a method which uses an array into my main class. Every other method I want to call seems to work. I wonder if anyone has any explanation or easy solution to this?
Thanks in advance for taking time looking into, really appreciate it!
import java.util.Scanner;
public class GeographyQuizMain
{
public static void main(String[] args)
{
takeQuiz();
}
public static void takeQuiz(Question[][] questions)
{
int score = 0;
RandomNumber randomQuestion = new RandomNumber();
//user chooses catergory
int cat = pickCatergory();
//ask 10 questions
for(int i = 0; i < 10;)
{
Scanner answerChoice = new Scanner(System.in);
randomQuestion.dice();
int q = (randomQuestion.dice() - 1);
//checks to see if question as been asked before
if (!questions[cat][q].beenAsked)
{
questions[cat][q].beenAsked = true; //changes question status to beenAsked
System.out.println(questions[cat][q].promt);
String answer = answerChoice.nextLine();
System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");
if(answer.equals(questions[cat][q].answer))
{
score++;
}
i++;
}
}
System.out.println("That is the end of the quiz!\n"
+ "You got " + score + "/10");
}
Your problem is with the call itself,
This line public static void takeQuiz(Question[][] questions) states that the method will accept a two dimensional array ([][]) of an object named Question.
On the other hand, your call - takeQuiz(); passes no array of such.
You should initialise an array of such to make this compile and pass it to the function. i.e.
Question[][] questionArray = GenerateQuestionArray(); //you should write this method
takeQuiz(questionArray);
Like you stated, it's clearly you're new to Java and I strongly suggest you to read the instructions and the information provided to you in class about that. I bet the details of Object initialisation, methods and arrays are covered there.
It seems that problem with your method call, in your method takeQuiz(); is taking 2 dimensional array for questions but at the calling time you are not providing that parameter so, compiler not able to found the method.
That's the problem.
try to use like this, this is simple an example for you. replace this with your actual values.
String[][] questions= new String[3][3];
takeQuiz(questions);
this will work.
You have called your method takeQuiz() without actually supplying its arguments Question[][] questions
so I am trying to design a GUI with the program BlueJ, that sends data from a jtextfield box into a variable (already done), and using that variable to be able to update another variable, but for java to "stop running" until a specific variable is updated. So something along the lines of...
string bacon = "";
int agility = 1;
int dexterity = 2;
int strength = 3;
int intelligence = 4;
int charisma = 5;
//my variables.
if (bacon = "agility")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
agility= agility+bacon
}
else if (bacon = "dexterity")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
dexterity = dexterity+bacon
}
else if (bacon = "strength")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
strength = strength+bacon
}
else if (bacon = "intelligence")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
intelligence = intelligence+bacon
}
else if (bacon = "charisma")
{
//what I am doing goes below where words are being used instead
Stop java progression until bacon is updated with an integer.
charisma = charisma+bacon
}
Thank you very much to anybody who can help me figure this out. I would also like it to have something so that if bacon is stated as a non-integer (32.7 or "hello"), it would simply ask you to input a proper integer.
Not quite sure what you are asking in the first part of the question, but for the second part to it check if it is a non integer you can do something like this....
boolean isValidInput = true;
for(int i=0;i<bacon.length();i++) {
char charAt = bacon.charAt(i);
if(!Character.isDigit(charAt)) {
isValidInput = false;
break;
}
}
if(!isValidInput)
System.out.println("Invalid Input!");
Also, = is used for assignment in java, ex a = 3;, however if you are trying to check if something is equal to something else, you should use the == operator. ex. if(x==2)
But in your case, since you are comparing Strings, you should use if(x.equals("hello"))
Another tip, instead of saying charisma = charisma + bacon; you can just say charisma += bacon; as a shorthand ;)
Hope this helps,
Saashin
QUESTION:
How can I read the string "d6+2-d4" so that each d# will randomly generate a number within the parameter of the dice roll?
CLARIFIER:
I want to read a string and have it so when a d# appears, it will randomly generate a number such as to simulate a dice roll. Then, add up all the rolls and numbers to get a total. Much like how Roll20 does with their /roll command for an example. If !clarifying {lstThen.add("look at the Roll20 and play with the /roll command to understand it")} else if !understandStill {lstThen.add("I do not know what to say, someone else could try explaining it better...")}
Info:
I was making a Java program for Dungeons and Dragons, only to find that I have come across a problem in figuring out how to calculate the user input: I do not know how to evaluate a string such as this.
I theorize that I may need Java's eval at the end. I do know what I want to happen/have a theory on how to execute (this is more so PseudoCode than Java):
Random rand = new Random();
int i = 0;
String toEval;
String char;
String roll = txtField.getText();
while (i<roll.length) {
check if character at i position is a d, then highlight the numbers
after d until it comes to a special character/!aNumber
// so if d was found before 100, it will then highlight 100 and stop
// if the character is a symbol or the end of the string
if d appears {
char = rand.nextInt(#);
i + #'s of places;
// so when i++ occurs, it will move past whatever d# was in case
// d# was something like d100, d12, or d5291
} else {
char = roll.length[i];
}
toEval = toEval + char;
i++;
}
perform evaluation method on toEval to get a resulting number
list.add(roll + " = " + evaluated toEval);
EDIT:
With weston's help, I have honed in on what is likely needed, using a splitter with an array, it can detect certain symbols and add it into a list. However, it is my fault for not clarifying on what else was needed. The pseudocode above doesn't helpfully so this is what else I need to figure out.
roll.split("(+-/*^)");
As this part is what is also tripping me up. Should I make splits where there are numbers too? So an equation like:
String[] numbers = roll.split("(+-/*^)");
String[] symbols = roll.split("1234567890d")
// Rough idea for long way
loop statement {
loop to check for parentheses {
set operation to be done first
}
if symbol {
loop for symbol check {
perform operations
}}} // ending this since it looks like a bad way to do it...
// Better idea, originally thought up today (5/11/15)
int val[];
int re = 1;
loop {
if (list[i].containsIgnoreCase(d)) {
val[]=list[i].splitIgnoreCase("d");
list[i] = 0;
while (re <= val[0]) {
list[i] = list[i] + (rand.nextInt(val[1]) + 1);
re++;
}
}
}
// then create a string out of list[]/numbers[] and put together with
// symbols[] and use Java's evaluator for the String
wenton had it, it just seemed like it wasn't doing it for me (until I realised I wasn't specific on what I wanted) so basically to update, the string I want evaluated is (I know it's a little unorthodox, but it's to make a point; I also hope this clarifies even further of what is needed to make it work):
(3d12^d2-2)+d4(2*d4/d2)
From reading this, you may see the spots that I do not know how to perform very well... But that is why I am asking all you lovely, smart programmers out there! I hope I asked this clearly enough and thank you for your time :3
The trick with any programming problem is to break it up and write a method for each part, so below I have a method for rolling one dice, which is called by the one for rolling many.
private Random rand = new Random();
/**
* #param roll can be a multipart roll which is run and added up. e.g. d6+2-d4
*/
public int multiPartRoll(String roll) {
String[] parts = roll.split("(?=[+-])"); //split by +-, keeping them
int total = 0;
for (String partOfRoll : parts) { //roll each dice specified
total += singleRoll(partOfRoll);
}
return total;
}
/**
* #param roll can be fixed value, examples -1, +2, 15 or a dice to roll
* d6, +d20 -d100
*/
public int singleRoll(String roll) {
int di = roll.indexOf('d');
if (di == -1) //case where has no 'd'
return Integer.parseInt(roll);
int diceSize = Integer.parseInt(roll.substring(di + 1)); //value of string after 'd'
int result = rand.nextInt(diceSize) + 1; //roll the dice
if (roll.startsWith("-")) //negate if nessasary
result = -result;
return result;
}
I'm trying some Java recently and look for some review of my style. If You like to look at this exercise placed in the image, and tell me if my style is good enought? Or maybe it is not good enought, so You can tell me on what aspect I should work more, so You can help me to improve it?
exercise for my question
/*
* File: MathQuiz.java
*
* This program produces Math Quiz.
*/
import acm.program.*;
import acm.util.*;
public class MathQuiz extends ConsoleProgram {
/* Class constants for Quiz settings. */
private static final int CHANCES = 3;
private static final int QUESTIONS = 5;
private static final int MIN = 0;
private static final int MAX = 20;
/* Start program. Number of questions to ask is assigned here. */
public void run() {
println("Welcome to Math Quiz");
while(answered != QUESTIONS) {
produceNumbers();
askForAnswer();
}
println("End of program.");
}
/* Ask for answer, and check them. Number of chances includes
* first one, where user is asked for reply. */
private void askForAnswer() {
int answer = -1;
if(type)
answer = readInt("What is " + x + "+" + y + "?");
else
answer = readInt("What is " + x + "-" + y + "?");
for(int i = 1; i < CHANCES+1; i++) {
if(answer != solution) {
if(i == CHANCES) {
println("No. The answer is " + solution + ".");
break;
}
answer = readInt("That's incorrect - try a different answer: ");
} else {
println("That's the answer!");
break;
}
}
answered++;
}
/* Produces type and two numbers until they qualify. */
private void produceNumbers() {
produceType();
produceFirst();
produceSecond();
if(type)
while(x+y >= MAX) {
produceFirst();
produceSecond();
}
else
while(x-y <= MIN) {
produceFirst();
produceSecond();
}
calculateSolution();
}
/* Calculates equation solution. */
private void calculateSolution() {
if(type) solution = x + y;
else solution = x - y;
}
/* Type of the equation. True is from plus, false is for minus. */
private void produceType() {
type = rgen.nextBoolean();
}
/* Produces first number. */
private void produceFirst() {
x = rgen.nextInt(0, 20);
}
/* Produces second number. */
private void produceSecond() {
y = rgen.nextInt(0, 20);
}
/* Class variables for numbers and type of the equation. */
private static boolean type;
private static int x;
private static int y;
/* Class variables for equation solution. */
private static int solution;
/* Class variable counting number of answered equations,
* so if it reaches number of provided questions, it ends */
private static int answered = 0;
/* Random generator constructor. */
RandomGenerator rgen = new RandomGenerator();
}
One thing I noticed was that all of your methods take no parameters and return void.
I think it would be clearer if you use method parameters and return values to show the flow of data through your program instead of using the object's state to store everything.
There are a few things you should do differently, and a couple you could do differently.
The things you should do differently:
Keep all fields together.
static fields should always be in THIS_FORM
you've used the static modifier for what clearly look like instance fields. (type,x,y,solution, answered). This means you can only ever run one MathsQuiz at a time per JVM. Not a big deal in this case, but will cause problems for more complex programs.
produceFirst and produceSecond use hardcoded parameters to nextInt rather than using MAX and MIN as provided by the class
There is no apparent need for answered to be a field. It could easily be a local variable in run.
Things you should do differently:
There is a small possibility (however tiny), that produceNumbers might not end. Instead of producing two random numbers and hoping they work. Produce one random number and then constrain the second so that a solution will always be formed. eg. say we are doing and addition and x is 6 and max is 20. We know that y cannot be larger than 14. So instead of trying nextInt(0,20), you could do nextInt(0,14) and be assured that you would get a feasible question.
For loop isn't really the right construct for askForAnswer as the desired behaviour is to ask for an answer CHANCES number of times or until a correct answer is received, whichever comes first. A for loop is usually used when you wish to do something a set number of times. Indeed the while loop in run is a good candidate for a for loop. A sample while loop might look like:
int i = 1;
boolean correct = (solution == readInt("What is " + x + "+" + y + "?"));
while (i < CHANCES && !correct) {
correct = (solution == readInt("Wrong, try again."));
i++;
}
if (correct) {
println("Well done!");
} else {
println("Nope, the answer is: "+solution);
}
Looks like a very clean program style. I would move all variables to the top instead of having some at the bottom, but other than that it is very readable.
Here is something I'd improve: the boolean type that is used to indicate whether we have an addition or subtraction:
private void produceType() {
type = rgen.nextBoolean();
}
produceType tells, that something is generated and I'd expect something to be returned. And I'd define enums to represent the type of the quiz. Here's my suggestion:
private QuizType produceType() {
boolean type = rgen.nextBoolean();
if (type == true)
return QuizType.PLUS;
else
return QuizType.MINUS;
}
The enum is defined like this:
public enum QuizType { PLUS, MINUS }
Almost good I have only a few improvements:
variables moves to the top
Inside produceNumbers and your while you have small repeat. I recommend refactor this
Small advice: Code should be like books - easy readable - in your run() method firstly you call produceNumber and then askForAnswer. So it will be better if in your code you will have the same order in definitions, so implementation askForAnswer before produceNumber. But it isn't necessary
Pay attention to have small methods. A method shouldn't have much to do - I think that askForAnswer you could split to two methods