Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to build a quiz for a user that has to have 5 multiple choice questions and 5 true/false questions. I must do this using loops (while loops). I've come to the point where I set up a separate method asking the user the questions and error checking for the true/false or multiple choice questions. I now have to somehow give the user a point if they answer each question correctly. Then in the end, I must give the user the the total amount of points they won. Then I have to ask if they want to play again in the end, if they say yes I have to go back to the first question and restart the game and if they say no the program has to close. Here is where I got to on my main method. I started putting a while loop for the first answer (correct answer being 3) and making a point variable but I'm not sure where to go from there and how to connect everything. I hope what I did so far is correct. Thanks!
UserInteraction input = new UserInteraction();
Questions ask = new Questions();
int answer1 = 0, answer2 = 0, answer3 = 0, answer4 = 0, answer5 = 0;
int a1 = ask.Question1(answer1);
int point;
while (a1==3)
{point = 1;
}
int a2 = ask.Question2(answer2);
int a3 = ask.Question3(answer3);
int a4 = ask.Question4(answer4);
int a5 = ask.Question5(answer5);
boolean answer6=false, answer7=false, answer8=false, answer9=false, answer10=false;
String a6 = ask.Question6(answer6);
String a7 = ask.Question7(answer7);
String a8 = ask.Question8(answer8);
String a9 = ask.Question9(answer9);
String a10 = ask.Question10(answer10);
For the Questions methods, I'll put two blank examples on here.
{public int Question1 (int answer1)
{String message = "";
int smallestValue = 1;
int largestValue = 4;
System.out.println("Q1) What is...?");
System.out.println("1: ....");
System.out.println("2: ......");
System.out.println("3: ......");
System.out.println("4: ......");
System.out.print("Enter the number");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer1 = input2.getIntValueFromUserBetween(message, smallestValue, largestValue);
return answer1;
}
public String Question6(boolean answer10)
{String message = "";
System.out.println("(Q10) ....(true/false)");
System.out.print("Enter your answer here: ");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer10 = input2.confirm(message);
return "" + answer10;
}
}
Sorry if I misunderstand your question, but I don't understand why you're using a loop here.
while (a1==3)
Your program is either going to get stuck here or never use it. What I mean is that if the user answers the question correctly (i.e 3), they will be stuck in the while loop until you set a1 != 3.
What I think is a better solution is using selection. For example:
if (a1 == 3) {
point += 1; // point = point + 1
// Or whatever functionality you need here
}
Edit: If you really must use a loop, then having a Boolean flag would be the way to go. For example:
Boolean flag = false;
if (a1 == 3) {
flag = true;
while (flag) {
point += 1; //point = point + 1
// Make sure that you set flag equals to false at the end of the loop though, otherwise it will infinitely loop
// Include any other functionality needed
flag = false;
}
}
Is this similar to what your looking for?
int correct;
public void quiz() { // this is so you can restart quiz easily
String[] answers = String[5];
//add answers to array, set them to variables/constant first then index
String[] questions = String[5];
// add questions to array
for(int i = 0; i <= questions.length; i++) { // stops after all questions have been asked, make sure its "<="
System.out.println(questions[i]); // prints question 1 first loop then 2 and so on
// read input from user
if(input == answers[i]) { // you may have to convert input to correct type
correct += 1;
}
}
}
System.out.println("You got " + correct + " correct answers");
System.out.println("Would you like to play again?");
if(input == yes) {
quiz(); //starts quiz again // starts quiz method again
P.S. sorry if I've misunderstood the question
To ask different questions you can just change the String variables then call quiz() to ask those questions. nice and simple :)
Related
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 2 years ago.
Improve this question
Here's my code:
import java.util.Arrays;
import java.util.Scanner;
public class User
{
private static int [] users;
public User(){
users = new int[10];
Scanner input = new Scanner(System.in);
int InputNumber = input.nextInt();
int length = String.valueOf(InputNumber).length();
I have an method that calls this one, but I believe it's that everytime I do it, it creates an array, or that's what I think it does.
Down here is just a bunch of code to make verifications and add the number to the array.
if(length != 8 || InputNumber < 0){
System.out.println("That number isn't valid, try again, the number must have 8 digits");
User menu = new User();
return;
}else{
int i = -1;
do{
i++;
continue;
}while((users[i] != 0 && users[i] == InputNumber) );
if(i == users.length){
System.out.println("There's enough space, delete users");
}else if(users[i] != 0 && users[i] == InputNumber){
System.out.println("That user already exists");
}else{
System.out.println("The user " + InputNumber + " as been added!");
users[i] = InputNumber;
}
//show a menu
}
}
There aren't any errors and I can create a user but the thing is, every time I try to create another one it looks like it creates another array, I think. What I want to know is what can I change to make this work.
Since the array field is static and your initializing the array in the constructor everytime your creating a new User object your reinitializing the array and losing all the information that was there.
If you really need to have that field static simply initiate in the same line like this:
private static int [] users = new int[10];
Other thing you could do if you really want to initialize the field in the constructor is to check if the array is null or not:
if(users == null) {
users = new int[10];
}
With your example all you need is to initialize array once is to actually initialize it only once:
private static final int[] users = new int[10];
You can do 2 things:
replace this code for your static line
private static int [] users = new int[10];
and delete initialization in constructor
or you can check for null reference in constructor
if(users == null) users = new int[10];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Okay so I am only part of the way through my array inventory program, but my while loop that is supposed to prompt a user to re-enter a number when they have entered an invalid one will not execute. When an invalid number is entered the program just ends...I have tried a couple methods and neither are working. this is where i am at now, any ideas??
thanks much!
public class InventorySystem {
public static void main(String[] args) {
String[] newItemInfo = new String[1000];
String[] itemDescription = new String[1000];
int[] itemPrice = new int[1000];
int choice;
boolean isValid;
int itemChoice;
Scanner inputDevice = new Scanner(System.in);
System.out.println("*****Raider Inventory System*****");
System.out.println("1. Enter a new item");
System.out.println("2. View Item Information");
System.out.println("3. View a list of all items");
System.out.println("9. End Program\n");
System.out.println("Please enter your selection: ");
choice = inputDevice.nextInt();
if (choice == 1 || choice == 2 || choice == 3 || choice == 9) {
isValid = true;
} else {
isValid = false;
}
** while (isValid = false) {
System.out.println("Invalid entry, please enter either 1, 2, 3, or 9 for menu options.");
** }
for (int x = 0; x < 1000; ++x) {
if (choice == 1) {
System.out.println("Please enter the name if the item: ");
newItemInfo[x] = inputDevice.nextLine();
System.out.println("Please enter the item description: ");
itemDescription[x] = inputDevice.nextLine();
System.out.println("Please enter item price: ");
itemPrice[x] = inputDevice.nextInt();
}
}
if (choice == 2) {
System.out.println("***Show item Description***");
System.out.println("0. ");
System.out.println("please enter the item number ot view details: ");
itemChoice = inputDevice.nextInt();
}
if (choice == 3) {
System.out.println("****Item List Report****");
}
if (choice == 9) {
System.exit(0);
}
}
}
In your line
while(isValid = false)
the = doesn’t do what you think it does. In Java, a single = means assign the expression on the right side to the variable on the left side. It does not mean to compare the two sides.
So you should rather write this:
while (isValid == false)
Note the double ==. This code works, but you can write it even more beautifully:
while (!isValid)
The ! means not.
Don't do while (isValid = false). You're setting it to false!
Instead do
while (!isValid) {
}
Also, don't do while (isValid == false) -- that's ugly code.
Next, change isValid inside the loop.
while (!isValid) {
// get input from user in here
// test input and check if is valid. If so, set isValid = true;
// something must set isValid to true in here, else it will
// loop forever
}
Otherwise you'll be stuck in an infinite loop. The lesson to be learned here is to mentally walk through your code as if you were running it in your brain. This way you catch logic errors like what you've got.
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 8 years ago.
Improve this question
I'm trying to get this beginning part of my program to work the way I want it to before I move on and it's driving me crazy. In an attempt to receive 5 inputs for book title, author, page count, I'm receiving 6 for book title, 5 for author, and 5 for pg count. My end result is to just have each array with 5 inputs for each stored so I can organize them based on what the user requests. Do you see what I'm doing wrong? Thanks.
String[] titleChoice = new String[5];
String title = "", titleString = "";
String[] authorChoice = new String[5];
String author = "", authorString = "";
String[] pageChoice = new String[5];
String page = "", pageString = "";
String currentTitle;
String formatEntry;
int x = 0;
int numEntered;
int highestTitle = titleChoice.length - 1;
int highestAuthor = authorChoice.length - 1;
int highestPage = pageChoice.length - 1;
final int MAX_ARRAY_SIZE = 5;
boolean notQuit = false;
Arrays.fill(titleChoice, "zzzzzzzzzzz");
Arrays.fill(authorChoice, "zzzzzzzzzzz");
Arrays.fill(pageChoice, "zzzzzzzzzzz");
do
{
currentTitle = JOptionPane.showInputDialog(null, "Enter the title of a book, or zzz to
quit:");
if(!currentTitle.equals("zzz"))
{
titleChoice[x] = currentTitle;
authorChoice[x] = JOptionPane.showInputDialog(null, "Please enter "
+ titleChoice[x] + "'s author's last name: ");
pageChoice[x] = JOptionPane.showInputDialog(null, "Please enter "
+ titleChoice[x] + "'s page count: ");
x = x + 1;
}
else
JOptionPane.showMessageDialog(null, "You have elected to quit the program.
Goodbye.);
}
while(!currentTitle.equals("zzz"));
Receiving an ArrayIndexOutOfBoundsException for titleChoice[x] = currentTitle; as well. Not really sure how to remedy this.
The string in the else statement isn't closed, but besides that unless the user enters "zzz" on the 5th input the loop increments x and tries again with a nonexistent index. As suggested above while(!currentTitle.equals("zzz") && x < 5) should work because is limits the index to a number within the Array bounds (0 - 4).
If you want the program to stop asking for more than 5 titles add a further condition to the while:
while(!currentTitle.equals("zzz") && x < 5);
otherwise it will keep asking until you enter zzz.
I'm guessing your 6th book title is "zzz". They are entering a 6th title to quit but then you aren't running the section of code that generates an author and page so those both still have 5 entries.
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 9 years ago.
Improve this question
I'm making a thingy that takes 3 inputs like "1500, 1 and 1" or "1500, January and 1" and returns "January 1st, 1500" or "1/1/1500", i had some problems on the day part but someone already told me how to fix it, and now I'm having problems with the month part, i made this kinda fast and i haven't figured out why it isn't working, it SHOULD see if the input is a valid month, if it is then it outputs the month(this part is just for testing), and if it isn't then it should say "please use a valid month or a number between 1 and 12", but when i write anything that isn't a month it just stops, and doesn't output anything, even if i put a month after it just doesn't do anything, i tried to see if there was any errors but i didn't found any, this is the code that i used:
Scanner scan = new Scanner(System.in);
String mx;
System.out.println("Insert Month");
String[] mm = {"january","february","march","april","may","june","july","august","september","october","november","december"};
int mz = 0;
while (0 < 1){
mx = scan.nextLine();
mx = mx.toLowerCase();
for(int i = 0; i < 11; i++){
if (mx.equals(mm[i])){
mz = i + 1;
break;
}
else {
if(i == 11){
System.out.println("please use a valid month or a number between 1 and 12");
}
else{
}
}
}
//}
if(mz > 0){
break;
}
else {}
}
System.out.println(mx);
The reason your program just "stops" is that you only print the statement "please enter a valid month..." if i == 11 and you have your for loop break if i >= 11. Thus, this condition will never be met. The while loop keeps running, even though this statement isnt printed. You could have entered a non-month string on the first try, and then a month string on the second and your while loop would have been broken.
Here is how I have improved your code to work for taking in the month. Pay attention to subtle changes of highlighted. These are important for writing better, more readable code:
Scanner scan = new Scanner(System.in);
//initialize to empty string
String mx = "";
System.out.println("Insert Month");
//use good naming conventions for easier code readability
String[] validMonths = {"january","february","march","april","may","june","july","august","september","october","november","december"};
//using a boolean to break makes much more sense than the way you have written it with an infinite loop and a manual break statement
boolean noMonth = true;
while (noMonth){
mx = scan.nextLine();
for(int i = 0; i < 12; i++){
//rather than convert to lowercase, use this handy String method
//also compares for valid number entries
if (mx.equalsIgnoreCase(validMonths[i]) || mx.equals(Integer.toString(i+1))){
noMonth = false;
break;
}
}
if(noMonth){
System.out.println("please use a valid month or a number between 1 and 12");
}
}
System.out.println(mx);
Create a new while loop to take in the day and a new one to take in the year after these, checking for valid input. Also, every if does not require an else in Java.
You're not using meaningful variable names, making your code a little bit hard to read and maintain. So, I had to create you the following code from scratch:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String month = getMonthName(getInt("Enter Month: ", keyboard) - 1);
int day = getInt("Enter Day: ", keyboard);
int year = getInt("Enter Year: ", keyboard);
System.out.printf("%s %d, %d\n", month, day, year);
}
public static String getMonthName(final int monthNo)
{
String[] months = {"january","february","march","april","may","june","july","august","september","october","november","december"};
return months[monthNo];
}
public static int getInt(final String msg, Scanner keyboard)
{
System.out.print(msg);
return keyboard.nextInt();
}
The code above does NOT perform and input validation, as you may have noticed already. If you want to validate month input for example, your if condition may look something like this:
if (month < 0 || month < 12)
{
System.out.println("Invalid month number entered");
System.exit(0);
}
I'm having a little trouble grasping the difference between ! || and && when they are tested in a while condition. In the example below I want the program to ask a question "do you see a four on the screen?" then if the person answers no the program continues and keeps asking. If the user enters the answer "yes" the program exits but mine does not.
In my while loop condition am I telling the while loop to continue only if both i is less than 5 and the answer to the question is not yes? How is the correct way of thinking about ! || and && when used inside the context of a while loop?
import acm.program.*;
public class WhileConditionTestProgram extends ConsoleProgram{
public void run(){
String question = ("do you see a four on the screen? ");
int i = 1;
while(i <= 20 && !(question.equals("yes"))){
String question = readLine("do you see a 4 on the screen?: ");
i++;
}
}
}
Apart from the obvious issue of variable re-declaration, you should also consider using a do-while loop, since you are reading the user input at least once.
So, you can better change your loop to:
int i = 0;
String answer = "";
do {
answer = readLine("do you see a 4 on the screen?: ");
i++;
} while (i <= 20 && !answer.equalsIgnoreCase("yes"));
Note: I have used equalsIgnoreCase just for safer side, since you are reading input from user. You never know what combination of letters it passes.
In your while condition you are testing answer not question try that:
while(i <= 20 && !(answer.equals("yes"))){
answer = readLine("do you see a 4 on the screen?: ");
i++;
}
The problem with this code:
String question = ("do you see a four on the screen? ");
int i = 1;
while(i <= 20 && !(question.equals("yes"))){
String question = readLine("do you see a 4 on the screen?: ");
i++;
}
Is that you're redefining the question variable inside the while function. As an example, this will print "1", and not "2":
String question = "1";
int i = 1;
while (i <= 20) {
String question = "2";
i++;
}
System.out.println("Question is: " + question); // This will print "1"!
When you say String question = "2" you are declaring a brand new variable called question and setting it to "2". When you get to the end of the while loop, that variable goes out of scope and the program throws its data away. The original question is untouched. Here is a corrected version of that code snippet:
String question = ("do you see a four on the screen?");
int i = 1;
while(i <= 20 && !(question.equals("yes"))){
question = readLine("do you see a 4 on the screen?: ");
i++;
}
These operators work in a while loop the same way as they work everywhere else.
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions.
Try this:
String answer = "";
int i = 1;
while(i <= 20 && !(answer.equalsIgnoreCase("yes"))){
answer = readLine("do you see a 4 on the screen?: ");
i++;
}