I don't know why the loop doesn't stop! Java - java

This is my first doubt here, i'm really noob on this and my english isn't the best, so first of all sorry if there's a dummie mistake.
The thing is that I want to do a for loop to save every user input from console and add it to a list named "Order". This action have to be done if the user type correctly the order and it have to be checked to know if that exists on the menu. If it doesn't we have to let the user know the situation and ask him/her if he/she wants something we have on the menu. Also after every input saved on the listed we want to ask the user if he/she wants to order something more, so if is YES the loop have to be initialized and if is NO we have to get out the loop.
The problem with my code is that no matter what I type in the console, the loop is done from start to finish every cicle.
Where is the error?
Thanks!!!
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Fase2_final {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] menu = { "chicken", "steak", "hamburger", "spaghettis", "pizza" };
int[] price = { 10, 15, 20, 5, 12 };
boolean order = true;
for (int i = 0; i < menu.length; i++) {
System.out.println("We have " + menu[i] + " for " + price[i] + "€");
}
int yes = 1;
int no = 0;
Scanner yesOrNo = new Scanner(System.in);
System.out.println("What do you want to eat?");
List<String> Order = new ArrayList<String>();
do {
Scanner inputOrder = new Scanner(System.in);
String userOrder = inputOrder.next().toLowerCase();
for (int j = 0; j < menu.length; j++) {
if (userOrder.equals(menu[j])) {
Order.add(userOrder);
System.out.println("You ordered" + Order + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
} else if (userOrder.equals(menu[j]) == false) {
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
} else if (yesOrNo.nextInt() == no) {
System.out.println("Order finished!");
}
}
} while (yesOrNo.nextInt() == yes);
}
}```

There is no need to re-declare the Scanner object every iteration, or to have more than one Scanner object that will read from the same source. Also, there is no need to print out "I didn't find it!" over every comparison.
Consider the following block of code:
.
.
.
// there is no need to re-declare the Scanner object every iteration, or two scanners
Scanner keyboard = new Scanner(System.in);
do {
String userOrder = keyboard.next().toLowerCase();
// we haven't found the item
boolean found = false;
// integer option (yes or no)
int option;
// do the search
for (int j = 0; j < menu.length; j++) {
// do this if found
if (userOrder.equals(menu[j])) {
// set flag to indicate we found the item
found = true;
// add the order
Order.add(userOrder);
// print out, then read the user's option
System.out.println("You ordered" + userOrder + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
option = keyboard.nextInt();
// consume the NL leftover from the nextInt() call
keyboard.nextLine();
// break out of the for loop since you already found what you're looking for
break;
}
}
// check if you didn't find the item
if (!found) {
// print out
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
// read if user wants to continue
option = keyboard.nextInt();
// consume the NL leftover from the nextInt() call
keyboard.nextLine();
}
} while (option == yes);
System.out.println("Order finished!");
.
.
.
// close the scanner when you're done
keyboard.close();
.
.
.

I have refactored your code . try to see in comparing tool .
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Fase2_final {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] menu = { "chicken", "steak", "hamburger", "spaghettis", "pizza" };
int[] price = { 10, 15, 20, 5, 12 };
boolean order = true;
for (int i = 0; i < menu.length; i++) {
System.out.println("We have " + menu[i] + " for " + price[i] + "€");
}
int decision = 0;
int yes = 1;
int no = 0;
Scanner yesOrNo = new Scanner(System.in);
System.out.println("What do you want to eat?");
List<String> Order = new ArrayList<String>();
do {
Scanner inputOrder = new Scanner(System.in);
String userOrder = inputOrder.next().toLowerCase();
for (int j = 0; j < menu.length; j++) {
if (userOrder.equals(menu[j])) {
Order.add(userOrder);
System.out.println("You ordered" + Order + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
} else if (userOrder.equals(menu[j]) == false) {
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
}
}
decision = yesOrNo.nextInt();
if (decision == no) {
System.out.println("Order finished!");
}
} while (decision == yes);
}
}
Always close the scanner when you are done .

the nextInt() method returns the current input one time, if you call it twice it needs a second input. It could should look like this:
do {
Scanner inputOrder = new Scanner(System.in);
String userOrder = inputOrder.next().toLowerCase();
int answer = 0;
for (int j = 0; j < menu.length; j++) {
if (userOrder.equals(menu[j])) {
Order.add(userOrder);
System.out.println("You ordered" + Order + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
} else if (userOrder.equals(menu[j]) == false) {
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
} else if ((answer = yesOrNo.nextInt()) == no) {
System.out.println("Order finished!");
}
}
} while (yesOrNo.nextInt() == answer);
I hope I answered your question.

Related

how to extract answers from for loop

I can't figure out how to correctly write my for loop statement that will give me the correct score. I bolded the code that is what I can't figure out how to write correctly. Anytime I run my program I end up with the first result of (rslt < 3) no matter what numbers I enter.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String options[] = {
"mild or spicy",
"tea or coffee",
"breakfast or " +
"brunch",
"summer or winter",
"paper or plastic"
};
int answers[] = new int[options.length];
String result[] = new String[answers.length];
boolean bool = true;
while (true) {
for (int i = 0; i < options.length; i++) {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 1] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 2] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 3] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 4] + "?");
answers[i] = scanner.nextInt();
break;
}
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
int rslt = getScore(result);
if (rslt < 3)
System.out.println("You prefer life to be calm and organized");
else if (rslt > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
int out = scanner.nextInt();
if (out == 0)
bool = false;
if (!bool)
System.exit(0);
}
}
static int getScore(String[] result) {
int score = 0;
for (int i = 0; i < result.length; i++) {
switch (result[i]) {
case "spicy":
score++;
break;
case "coffee":
score++;
break;
case "breakfast":
score++;
break;
case "winter":
score++;
break;
case "paper":
score++;
break;
}
}
return score;
}
}
I have modified your code according to my understanding of the code.
It works just exactly like you may have wanted.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[][] options = {
{"mild", "spicy"},
{"tea", "coffee"},
{"brunch", "breakfast"},
{"summer", "winter"},
{"plastic", "paper"}
};
int[] answers = new int[options.length];
do {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i][0] +
" or " + options[i][1] + "?");
answers[i] = scanner.nextInt();
}
int result = getScore(answers);
if (result < 3)
System.out.println("You prefer life to be calm and organized");
else if (result > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
} while (scanner.nextInt() != 0);
}
static int getScore(int[] answers) {
int score = 0;
for (int answer : answers) if (answer == 1) score++;
return score;
}
}
To Fix Your Code
In the first for-loop, you are supposed to loop through the options array. But somehow you unfold the loop within the loop body. To prevent the whole thing loop again, you break the loop immediately. To fix the first loop, write it like this instead. Properly loop through each element, no need to unfold it, no need to break it.
System.out.println("Enter 0 for the preference on the left\n" + "Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
}
In the second loop, you are supposed to retrieve the selected string from answers and write the string to results. Without modifying your data structure, this can be achieved by using split(" or ") on the option, which gives you an array of string which you can use the answer as index to access. Note that this does not prevent array index out of bound exception if user enter anything other than 0 or 1, which you should totally do, but is out of scope of this question.
for (int i = 0; i < answers.length; i++) {
result[i] = options[i].split(" or ")[answers[i]] ;
}
And there you go.
To Solve Your Task
Alternatively, redesigning the data structure and logic to get rid of the unnecessary string manipulation and comparison is more ideal. You don't even need the result and answers array, simply add up the user input will do (if the user follows your instruction)
int rslt = 0;
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
rslt += scanner.nextInt();
}
Inside the loop, you continue assigning the result to the same index in the answers list, rather than assigning the result to another index for each input. Because you are not iterating anything, you don't even need the loop. Replace the entire while loop with the code below. Please upvote and accept answer if it solves/helps you with your problem.
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[0] + "?");
answers[0] = scanner.nextInt();
System.out.println("Do you prefer " + options[1] + "?");
answers[1] = scanner.nextInt();
System.out.println("Do you prefer " + options[2] + "?");
answers[2] = scanner.nextInt();
System.out.println("Do you prefer " + options[3] + "?");
answers[3] = scanner.nextInt();
System.out.println("Do you prefer " + options[4] + "?");
answers[4] = scanner.nextInt();
Also, please note this:
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
won't work. Instead of result[i] = [answers[i]];, do result[i] = Integer.parseInt(answers.get(i)).
This is part causing the unexpected behaviour: result[i] = [answers[i]];
From what I understood, you want to implement this:
For each option, store the user choice like 0 or 1, 0 for left, 1 for right
For each user choice, store the string value of the choice, i.e., for the 1st question if the user inputs 0, mild should be captured
Calculate scores by comparing string value of user input against a branching construct, switch case here
The problem is in step 2, the current code result[i] = [answers[i]]; does not express this operation properly.
answers[i] stores the user choice 0 or 1, step 1 operation. So to convert it to the corresponding choice in string step 2 operation, something like this should be done
(options[i].split(" or "))[answers[i]]
Explanation:
Pick up the complete string for each answer
Divide the string into two parts(array with 2 indexes 0 and 1), left and right, using a delimiter, " or " in this case
pick up the left or right based on the value stored in answers[i](the user input)
This should let the code behave as expected :)
There are other aspects that can be improved in the code though, as others have already suggested.

My program is breaking out of the first for loop after one iteration

Here is my code. It asks user for terms and definitions, then quizzes the user. (It tells the user the term, and the user types in the answer.) The program uses arrays to store the terms and definitions. If the user doesn't get the definition correct, the program asks the user whether they want to study it again. If so, they will type in yes, and the program will store it on a separate array. After the program quizzes the users on all the terms and definitions, round 2 starts, where the program will quiz the user only on the starred definition. The problem is, the code is only running the for loop (that quizzes the user on round 1) once, and then skips onto round 2. Why is that so? I already tried looking at other people's questions and answers, but I can't seem to find the problem in my code.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i <= number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}
}
for (int i = 0; i <= number_terms; i++)
You have number_terms + 1 iterations. Replace with
for (int i = 0; i < number_terms; i++)
The bug is that the for-loop that you have tagged with the comment "the for loop that isn't working" is not looping through all the definitions. This for-loop after handling the first definition it moves on to handling round 2 instead of continuing the loop to the 2nd definition and so on. The fix requires that you place the closing bracket of this for-loop before the print statement "Now, time for testing definitions you starred!" as shown below. I have added the comment "end for-loop to ensure looping of all definitions" at the for-loop closing bracket that I have moved up in the code below. In addition this for loop's iteration condition should be 'i < number_terms' as the previous posters have indicated.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such " +
"that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i < number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
} // end for-loop to ensure looping of all definitions
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}

A "Stick Game" program in Java not working correctly?

I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();

Array is only printing the last stored value and array element removal only replaces element

Does anyone know why is that when I print the last message ("report header..etc etc") the count on the list updates, but I'm only printing the last person's input values?
Also, how can I make so that only if the person has 30 or more credits or less than 90 will their name and credits be stored in the array, otherwise do nothing with the inputs?
Lastly, in the 'admin review' prompt portion, if I type in a name that matches an input, it should remove that name, but in my current code it only replaces the name with what I entered..
final int MAX_ON_LIST = 50;
String[] stuName = new String[1];
int[] numCredits = new int[1];
int currentSize = 0;
String question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
while (question.equalsIgnoreCase("n")) {
for (int i = 0; i < stuName.length; i++) {
do {
try {
stuName[i] = JOptionPane.showInputDialog("Enter student name:");
currentSize++;
}
catch (NumberFormatException e) {
stuName[i] = "";
}
if (stuName[i].equals("")) {
JOptionPane.showMessageDialog(null, "Name cannot be blank");
}
} while (stuName[i].equals(""));
}
for (int i = 0; i < numCredits.length; i++) {
do {
try {
numCredits[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter # of completed credits:"));
}
catch (NumberFormatException e) {
numCredits[i] = -1;
}
if (numCredits[i] < 0) {
JOptionPane.showMessageDialog(null, "# of credits can't be less than 0");
}
} while (numCredits[i] < 0);
}
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
}
String nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
while (nxtQuestion.equalsIgnoreCase("n")) {
String searchValue = JOptionPane.showInputDialog("Enter a name:");;
int position = 0;
boolean found = false;
while (position < stuName.length && !found) {
if (stuName[position].equalsIgnoreCase(searchValue)) {
found = true;
}
else {
++position;
}
}
if (found) {
stuName[1] = stuName[currentSize - 1];
--currentSize;
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
else {
JOptionPane.showMessageDialog(null, "Name not on list");
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
}
if (nxtQuestion.equalsIgnoreCase("y"));
{
JOptionPane.showMessageDialog(null,
"Report Header\n\n" + "# of student's on list: " + currentSize + "\nNames: " + Arrays.toString(stuName) +
"\nCredits: " + Arrays.toString(numCredits));
}
I'm not sure why you go through all the pain of using arrays here while List (ArrayList or LinkedList) would suit your needs much better. I'm assuming this is some sort of a task where you must use arrays. Otherwise the whole code should be rewritten.
As correctly mentioned above, arrays don't change size - both of your arrays always have size of 1 all the time. This also results in index out of bounds exception if you enter more than one student and then in admin you enter the name of last student.
The name of last student is the only name saved, that's why it's the only name printed.
In order to only store person with credit >=30 and <=90 you can use a simple if.
Also note the code in the final part of your program:
if (nxtQuestion.equalsIgnoreCase("y"));
{
// Do something
}
Due to semicolon right after if the if is doing nothing.
The part in curly braces (where I've put "Do something" comment) will always get executed, it's separate from the if. (Java allows you to put blocks of code in curly braces in order to limit scope of local variables).
P.S. Here's a slightly better version (at least it works):
public static void main(String[] args) {
final int MAX_ON_LIST = 50;
final int bottomCreditsLimit = 30;
final int topCreditsLimit = 90;
String[] stuName = new String[0];
int[] numCredits = new int[0];
String question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
while (question.equalsIgnoreCase("n") && stuName.length < MAX_ON_LIST) {
String stuNameInput = "";
do {
stuNameInput = JOptionPane.showInputDialog("Enter student name:").trim();
if (stuNameInput.equals("")) {
JOptionPane.showMessageDialog(null, "Name cannot be blank");
}
} while (stuNameInput.equals(""));
int numCreditsInput = -1;
do {
try {
numCreditsInput = Integer.parseInt(JOptionPane.showInputDialog("Enter # of completed credits:").trim());
if (numCreditsInput < 0) {
JOptionPane.showMessageDialog(null, "# of credits can't be less than 0");
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please input integer value");
}
} while (numCreditsInput < 0);
if (numCreditsInput >= bottomCreditsLimit && numCreditsInput <= topCreditsLimit) {
stuName = Arrays.copyOf(stuName, stuName.length + 1);
stuName[stuName.length - 1] = stuNameInput;
numCredits = Arrays.copyOf(numCredits, numCredits.length + 1);
numCredits[numCredits.length - 1] = numCreditsInput;
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
}
String nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
while (nxtQuestion.equalsIgnoreCase("n")) {
String searchValue = JOptionPane.showInputDialog("Enter a name:").trim();
int position = -1;
for (int i = 0; i < stuName.length; i++) {
if (stuName[i].equalsIgnoreCase(searchValue)) {
position = i;
break;
}
}
if (position >= 0) {
stuName[position] = stuName[stuName.length - 1];
stuName = Arrays.copyOf(stuName, stuName.length - 1);
numCredits[position] = numCredits[numCredits.length - 1];
numCredits = Arrays.copyOf(numCredits, numCredits.length - 1);
} else {
JOptionPane.showMessageDialog(null, "Name not on list");
}
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
}
JOptionPane.showMessageDialog(null, "Report Header\n\n" + "# of student's on list: " + stuName.length + "\nNames: " + Arrays.toString(stuName)
+ "\nCredits: " + Arrays.toString(numCredits));
}
Each of your arrays has a single element. Every time you add a name, you're putting it into the same position in the array.
String[] stuName = new String[1];
int[] numCredits = new int[1];
This loop always has exactly one pass, with i = 0.
for (int i = 0; i < stuName.length; i++) {
Alternatives include:
Create a java.util.List of students, which grows as needed with each call to List.add().
Create a java.util.Map of students from name to value.
The for loop pre-compiles so you need to set stuName to something before engaging the loop.

Storing user input to an array java

I know this question have been asked a lot of times, but I still could not solve the problem. The problem is that I have to store an user input and print out a value.
For example, there are 4 people, person1, person2, person3 and person4. If I vote for person1, the vote number of person1 becomes 1 and the others remain 0. Then if I vote for person2, the vote number of person2 becomes 1 and person1 is also 1.
I can compile the code. But then if I vote for person1, the output becomes 4. and if I then vote for person2, the output of person2 becomes 4 and vote for person1 went back to 0. I am a complete beginner in programming and got stuck at this program for 4 whole days so any help is greatly appreciated. Thank you very much in advance.
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
When you do this:
for (i=0; i<votescount.length; i++){...
} // end for loop
The loop happens 4 times. This means that this bit is happening 4 times:
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
which means the vote count goes up by 4!
get rid of your for loop:
for (i=0; i<votescount.length; i++)
and make persons and votescount global and static.
This is the updated code:
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
static String[] person = new String[4];//these have been made global and static
static int[] votescount = new int[4];
public static void main (String[] args)
{
// Initialize String Arrays
person[0] = "person1";//these have been moved so that it is only called once
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
System.out.println(answer);
int i;
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
First you do,
int[] votescount = new int[4];
then, you do
for (i=0; i<votescount.length; i++)
{
}
So, that loop iterates 4 times.
and inside the loop, you do,
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
and that's why, your count is up by 4!

Categories