I made a Java program that did some basic math for kids in primary. I wanted to make it a little more advanced, and remember the questions they got wrong, and then optionally present these questions again at the end and allow them to attempt them once more.
But the code for it got really complicated really quick. I thought I finished it, but it's having difficulty compiling (read: won't) and I'm at the point where I need some help. I'd greatly appreciate it.
import java.util.Scanner;
import java.util.Random;
public class ArithmeticTester0 {
public static void main(String[] arg) {
int level = 0;
String type = "";
String name = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Hi! I am your friendly Math Tutor.");
System.out.print("What is your name? ");
name = keyboard.nextLine();
System.out.print("Would you like to be tested on addition, subtraction or both? ");
type = keyboard.nextLine();
// Check if the type inputted is anything other than addition, subtraction or both
if (!type.equalsIgnoreCase("addition") && !type.equalsIgnoreCase("subtraction") && !type.equalsIgnoreCase("both") && !type.equalsIgnoreCase("add") && !type.equalsIgnoreCase("subtraction")) {
while (!type.equalsIgnoreCase("addition") && !type.equalsIgnoreCase("subtraction") && !type.equalsIgnoreCase("both") && !type.equalsIgnoreCase("add") && !type.equalsIgnoreCase("subtraction")) {
System.out.print("You must answer addition, subtraction or both. How about we try again? ");
type = keyboard.nextLine();
}
}
System.out.print("What level would you like to choose? " +
" Enter 1, 2 or 3: ");
level = keyboard.nextInt();
// Check if the level entered is not 1, 2 or 3
if (level > 3 || level < 1) {
while (level > 3 || level < 1) {
System.out.println("The number must be either 1, 2 or" +
" 3. Let's try again shall we?");
System.out.print("What level would you like to choose? ");
level = keyboard.nextInt();
}
}
System.out.println("\nOK " + name +
", here are 10 exercises for you at level " + level + ".");
System.out.println("Good luck!\n");
int a = 0, b = 0, c = 0;
int preva = 0, prevb = 0; //previous a and b value
int correct = 0;
if (type.equalsIgnoreCase("addition") || type.equalsIgnoreCase("add")) {
add(level, preva, prevb, a, b, c, type);
}
else if (type.equalsIgnoreCase("subtraction") || type.equalsIgnoreCase("subtract")) {
subtract(level, preva, prevb, a, b, c, type);
}
else {
both(level, preva, prevb, a, b, c, type);
}
}
/* The method below prints out a statement depending
on how well the child did */
public static void add(int level, int preva, int prevb, int a, int b, int c, String type) {
Random random = new Random();
Scanner keyboard = new Scanner(System.in);
List<Integer> wrongList = Arrays.asList(array);
int correct = 0;
int wrong = 0;
// Generate 10 questions
for (int i = 1; i <= 10; i++) {
/* Generate numbers depending on the difficulty.
The while loop ensures that the next question isn't the same
as the previous question that was just asked. */
if (level == 1) {
while (preva == a && prevb == b) {
a = random.nextInt(10);
b = random.nextInt(11-a);
}
}
else if (level == 2) {
while (preva == a && prevb == b) {
a = random.nextInt(10);
b = random.nextInt(10);
}
}
else if (level == 3) {
while (preva == a && prevb == b) {
a = random.nextInt(50);
b = random.nextInt(50);
}
}
preva = a;
prevb = b;
System.out.print(a + " + " + b + " = ");
c = keyboard.nextInt();
// Check if the user was correct
if (a + b == c) {
System.out.println("You are right!");
correct++;
}
if (a - b != c) {
wrongList.add(a);
wrongList.add(b);
wrong++;
}
}
// Conclusion
System.out.println("\nYou got " + correct + " right out of 10.");
if (wrong > 0) {
int[] wrongAnswers = wrongList.toArray(new int[wrongList.size()]);
System.out.print("You got " + wrong + " wrong, would you like to retry those questions?");
String response = keyboard.nextLine();
if (response.equalsIgnoreCase("Yes") || response.equalsIgnoreCase("Okay") || response.equalsIgnoreCase("OK") || response.equalsIgnoreCase("Sure") || response.equalsIgnoreCase("Yeah") || response.equalsIgnoreCase("Yea")) {
retry(wrongAnswers, type, wrongIndexArray);
}
else if (response.equalsIgnoreCase("No") || response.equalsIgnoreCase("Nope") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("No thanks") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("Do not want")) {
System.out.println("OK! That's fine.");
}
else {
while (response.equalsIgnoreCase("Yes") || response.equalsIgnoreCase("Okay") || response.equalsIgnoreCase("OK") || response.equalsIgnoreCase("Sure") || response.equalsIgnoreCase("Yeah") || response.equalsIgnoreCase("Yea") || response.equalsIgnoreCase("No") || response.equalsIgnoreCase("Nope") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("No thanks") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("Do not want")) {
System.out.println("Please put in an answer that is along the lines of \"yes\" or \"no\".");
response = keyboard.nextLine();
}
}
}
conclusion(correct, level);
System.out.println("See ya!");
}
public static void subtract(int level, int preva, int prevb, int a, int b, int c, String type) {
Random random = new Random();
Scanner keyboard = new Scanner(System.in);
List<Integer> wrongList = Arrays.asList(array);
// Generate 10 questions
int correct = 0;
int wrong = 0;
for (int i = 1; i <= 10; i++) {
/* Generate numbers depending on the difficulty.
The while loop ensures that the next question isn't the same
as the previous question that was just asked. */
if (level == 1) {
while (preva == a && prevb == b) {
a = random.nextInt(10);
b = random.nextInt(11-a);
while (b > a) {
a = random.nextInt(10);
b = random.nextInt(11-a);
}
}
}
else if (level == 2) {
while (preva == a && prevb == b) {
a = random.nextInt(10);
b = random.nextInt(10);
while (b > a) {
a = random.nextInt(10);
b = random.nextInt(11-a);
}
}
}
else if (level == 3) {
while (preva == a && prevb == b) {
a = random.nextInt(50);
b = random.nextInt(50);
}
}
preva = a;
prevb = b;
System.out.print(a + " - " + b + " = ");
c = keyboard.nextInt();
// Check if the user was correct
if (a - b == c) {
System.out.println("You are right!");
correct++;
}
if (a - b != c) {
wrongList.add(a);
wrongList.add(b);
wrong++;
}
}
// Conclusion
System.out.println("\nYou got " + correct + " right out of 10.");
if (wrong > 0) {
int[] wrongAnswers = wrongList.toArray(new int[wrongList.size()]);
System.out.print("You got " + wrong + " wrong, would you like to retry those questions?");
String response = keyboard.nextLine();
if (response.equalsIgnoreCase("Yes") || response.equalsIgnoreCase("Okay") || response.equalsIgnoreCase("OK") || response.equalsIgnoreCase("Sure") || response.equalsIgnoreCase("Yeah") || response.equalsIgnoreCase("Yea")) {
retry(wrongAnswers, type);
}
else if (response.equalsIgnoreCase("No") || response.equalsIgnoreCase("Nope") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("No thanks") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("Do not want")) {
System.out.println("OK! That's fine.");
}
else {
while (response.equalsIgnoreCase("Yes") || response.equalsIgnoreCase("Okay") || response.equalsIgnoreCase("OK") || response.equalsIgnoreCase("Sure") || response.equalsIgnoreCase("Yeah") || response.equalsIgnoreCase("Yea") || response.equalsIgnoreCase("No") || response.equalsIgnoreCase("Nope") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("No thanks") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("Do not want")) {
System.out.println("Please put in an answer that is along the lines of \"yes\" or \"no\".");
response = keyboard.nextLine();
}
}
}
conclusion(correct, level);
System.out.println("See ya!");
}
public static void both(int level, int preva, int prevb, int a, int b, int c, String type) {
Random random = new Random();
Scanner keyboard = new Scanner(System.in);
// Generate 10 questions
int correct = 0;
List<Integer> wrongIndexes = Arrays.asList(array);
for (int i = 1; i <= 5; i++) {
/* Generate numbers depending on the difficulty.
The while loop ensures that the next question isn't the same
as the previous question that was just asked. */
if (level == 1) {
while (preva == a && prevb == b) {
a = random.nextInt(10);
b = random.nextInt(11-a);
}
}
else if (level == 2) {
while (preva == a && prevb == b) {
a = random.nextInt(10);
b = random.nextInt(10);
}
}
else if (level == 3) {
while (preva == a && prevb == b) {
a = random.nextInt(50);
b = random.nextInt(50);
}
}
preva = a;
prevb = b;
System.out.print(a + " + " + b + " = ");
c = keyboard.nextInt();
// Check if the user was correct
if (a + b == c) {
System.out.println("You are right!");
correct++;
}
else {
System.out.println("Oops! You made a mistake. " + a + " + " + b + " = " + (a+b));
wrongIndexes += i;
}
}
for (int i = 6; i <= 10; i++) {
/* Generate numbers depending on the difficulty.
The while loop ensures that the next question isn't the same
as the previous question that was just asked. */
if (level == 1) {
while (preva == a && prevb == b) {
a = random.nextInt(10);
b = random.nextInt(11-a);
while (b > a) {
a = random.nextInt(10);
b = random.nextInt(11-a);
}
}
}
else if (level == 2) {
while (preva == a && prevb == b) {
a = random.nextInt(10);
b = random.nextInt(10);
while (b > a) {
a = random.nextInt(10);
b = random.nextInt(11-a);
}
}
}
else if (level == 3) {
while (preva == a && prevb == b) {
a = random.nextInt(50);
b = random.nextInt(50);
}
}
preva = a;
prevb = b;
System.out.print(a + " - " + b + " = ");
c = keyboard.nextInt();
// Check if the user was correct
if (a - b == c) {
System.out.println("You are right!");
correct++;
}
else {
System.out.println("Oops! You made a mistake. " + a + " - " + b + " = " + (a-b));
wrongIndexes += i;
}
}
int[] wrongIndexArray = wrongIndexes.toArray(new int[wrongIndexes.size()]);
// Conclusion
System.out.println("\nYou got " + correct + " right out of 10.");
if (wrong > 0) {
int[] wrongAnswers = wrongList.toArray(new int[wrongList.size()]);
System.out.print("You got " + wrong + " wrong, would you like to retry those questions?");
String response = keyboard.nextLine();
if (response.equalsIgnoreCase("Yes") || response.equalsIgnoreCase("Okay") || response.equalsIgnoreCase("OK") || response.equalsIgnoreCase("Sure") || response.equalsIgnoreCase("Yeah") || response.equalsIgnoreCase("Yea")) {
retry(wrongAnswers, type, wrongIndexArray);
}
else if (response.equalsIgnoreCase("No") || response.equalsIgnoreCase("Nope") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("No thanks") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("Do not want")) {
System.out.println("OK! That's fine.");
}
else {
while (response.equalsIgnoreCase("Yes") || response.equalsIgnoreCase("Okay") || response.equalsIgnoreCase("OK") || response.equalsIgnoreCase("Sure") || response.equalsIgnoreCase("Yeah") || response.equalsIgnoreCase("Yea") || response.equalsIgnoreCase("No") || response.equalsIgnoreCase("Nope") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("No thanks") || response.equalsIgnoreCase("Nah") || response.equalsIgnoreCase("Do not want")) {
System.out.println("Please put in an answer that is along the lines of \"yes\" or \"no\".");
response = keyboard.nextLine();
}
}
}
conclusion(correct, level);
System.out.println("See ya!");
}
public static void retry(int[] wrongAnswers, String type, int[] wrongIndexArray) {
int c = 0;
if (type.equalsIgnoreCase("addition") || type.equalsIgnoreCase("add")) {
for (int i = 0; i < wrongAnswers.length; i+=2) {
System.out.print(wrongAnswers[i] + " + " + wrongAnswers[i+1] + " = ");
c = keyboard.nextInt();
if (wrongAnswers[i] + wrongAnswers[i+1] == c) {
System.out.println("You are right!");
}
else {
System.out.println("Oops! You made a mistake. " + wrongIndex[i] + " + " + wrongIndex[i+1] + " = " + (wrongIndex[i]+wrongIndex[i+1]));
}
}
}
else if (type.equalsIgnoreCase("subtraction") || type.equalsIgnoreCase("subtract")) {
for (int i = 0; i < wrongAnswers.length; i+=2) {
System.out.print(wrongAnswers[i] + " - " + wrongAnswers[i+1] + " = ");
c = keyboard.nextInt();
if (wrongAnswers[i] - wrongAnswers[i+1] == c) {
System.out.println("You are right!");
}
else {
System.out.println("Oops! You made a mistake. " + a + " - " + b + " = " + (a-b));
}
}
}
else {
for (int i = 0; i < wrongAnswers.length; i+=2) {
for (int i = 0; i < wrongIndexArray.length; i++) {
if (wrongIndexArray[i] < 6) {
System.out.print(wrongAnswers[i] + " + " + wrongAnswers[i+1] + " = ");
c = keyboard.nextInt();
if (wrongAnswers[i] + wrongAnswers[i+1] == c) {
System.out.println("You are right!");
}
else {
System.out.println("Oops! You made a mistake. " + wrongIndex[i] + " + " + wrongIndex[i+1] + " = " + (wrongIndex[i]+wrongIndex[i+1]));
}
}
else if (wrongIndexArray[i] > 5) {
System.out.print(wrongAnswers[i] + " - " + wrongAnswers[i+1] + " = ");
c = keyboard.nextInt();
if (wrongAnswers[i] - wrongAnswers[i+1] == c) {
System.out.println("You are right!");
}
else {
System.out.println("Oops! You made a mistake. " + wrongIndex[i] + " + " + wrongIndex[i+1] + " = " + (wrongIndex[i]+wrongIndex[i+1]));
}
}
}
}
}
}
public static void conclusion(int x, int lev) {
if (x >= 9) {
if (lev == 3) {
if (x == 9)
System.out.println("Please try the same difficulty again" +
", you almost scored 10 out of 10!");
else
System.out.println("You have mastered addition at this level" +
"! The system is not of any further use.");
}
else {
System.out.println("Please select a higher difficulty next time!");
}
}
else if (x >= 6) {
System.out.println("Please try the test again.");
}
else {
System.out.println("Please ask your teacher for extra lessons.");
}
}
}
The errors are:
You forgot to import java.util.List. Just go ahead and import java.util.*. You know you want to.
You didn't declare wrongIndexArray, array, wrong, wrongList, keyboard, a, or b anywhere. I may have missed a few.
In this line:
int[] wrongAnswers = wrongList.toArray(new int[wrongList.size()]);
wrongList is an List<Integer> so I think that you can't cast it to an int[]. You have to use Integer[].
Possibly others, but...
...based on the errors you have, are you using an IDE such as NetBeans? Using an IDE will go far in letting you identify the reasons for the errors you're getting, and they often include helpful hints with each error.
Some other helpful hints:
It looks like you're storing the operands in a list when the student gets the answer wrong. Consider instead wrapping the operands and the operation into a class such as SubtractionQuestion or AdditionQuestion. It might help later on when you want to retest the student on the ones they got wrong.
Store the "yes" and "no" text answers (Yeah, Yes, Yea, Yup) in an ArrayList<String> yesAnswers, then just check if yesAnswers.contains(answer). This makes it easy to maintain the list, and you also don't need to check against yes, no, or not yes or no -- just check against yes, else no, else bad answer.
Hope that makes sense....
Related
I consistently get different output than I expected. However, the code very apparently is running correctly, providing the desired output elements, with some additional redundant elements like an appetizer and main course.
Please, see the attached code, and output when run on the Eclipse IDE.
//class FoodOrder
class Main {
// Method to display menu
static void display(String menu[]) {
for (int i = 0; i < menu.length; i++) {
System.out.println(" " + i + " - " + menu[i]);
}
System.out.print("Enter the number for your selection: ");
}
// main method
public static void main(String[] args) {
// menu lists:
String mainMenu[] = { "Nothing", "Appetizer", "Main Course", "Dessert" };
String dessertMenu[] = { "Nothing", "Baklava", "Rice Pudding", "Chocolate Cake" };
String appetizerMenu[] = { "Nothing", "Oysters", "Grilled Octopus", "Hummus" };
String mainCourseMenu[] = { "Nothing", "Steak", "Chicken", "Fish", "Vegetarian" };
String toppingsMenu[] = { "Nothing", "Olive Oil", "Paprika", "Olives" };
String list = "";
// create an instance of Scanner class
Scanner sc = new Scanner(System.in);
boolean valid;
System.out.println("Welcome to the food festival!");
String ans;
do {
System.out.print("Would you like to place an order? ");
ans = sc.next();
valid = ((ans.equals("YES")) || ans.equals("YEs") || ans.equals("Yes") || ans.equals("yES")
|| ans.equals("yeS") || ans.equals("yEs") || ans.equals("YeS") || ans.equals("yes")
|| (ans.equals("NO")) || ans.equals("No") || ans.equals("nO") || ans.equals("no"));
} while (!valid);
if ((ans.equals("NO")) || (ans.equals("No")) || (ans.equals("nO")) || (ans.equals("no"))) {
System.out.println("Thank you for stopping by, maybe next time you’ll sample our menu.");
return;
}
if (ans.equals("YES") || ans.equals("YEs") || ans.equals("Yes") || ans.equals("yES") || ans.equals("yeS")
|| ans.equals("yEs") || ans.equals("YeS") || ans.equals("yes")) {
System.out.print("What is your name for the order? ");
String name = sc.next();
System.out.println("");
int m, n, k;
while (true) {
Menu:
// proocess to select the menu items
System.out.println("Select from menu, " + name);
display(mainMenu);
n = sc.nextInt();
if (n == 0)
break;
if (n == 1) {
while (true) {
System.out.println("");
System.out.println("Appetizer Menu:");
display(appetizerMenu);
m = sc.nextInt();
list = list + "Appetizer:[" + appetizerMenu[m] + ": ";
if (m == 0) {
break;
}
while (true) {
System.out.println("");
System.out.println("Toppings Menu:");
display(toppingsMenu);
k = sc.nextInt();
if (k == 0)
break;
list = list + toppingsMenu[k] + " ";
}
list = list + "]\n";
}
}
if (n == 2) {
while (true) {
System.out.println("");
System.out.println("Main Course Menu:");
display(mainCourseMenu);
m = sc.nextInt();
list = list + "Main Course :[" + mainCourseMenu[m] + ": ";
if (m == 0) {
break;
}
while (true) {
System.out.println("");
System.out.println("Toppings Menu:");
display(toppingsMenu);
k = sc.nextInt();
if (k == 0)
break;
list = list + toppingsMenu[k] + "]\n";
}
}
}
if (n == 3) {
while (true) {
System.out.println("");
System.out.println("Dessert Menu:");
display(dessertMenu);
m = sc.nextInt();
list = list + "Main Course :[" + dessertMenu[m] + ": ";
if (m == 0) {
break;
}
while (true) {
System.out.println("");
System.out.println("Toppings Menu:");
display(toppingsMenu);
k = sc.nextInt();
if (k == 0)
break;
list = list + toppingsMenu[k] + "]\n";
}
}
}
} // end while loop
System.out.println("Here is your order " + name);
System.out.println(list);
System.out.println("Enjoy your meal!");
} // end of if
}// main method
}// end of class
This is the output I am supposed to get:
Here is your order Superman:
Appetizer: [ Hummus: Olives, Olive Oil ]
Main Course: [ Fish: Paprika ]
Dessert: [ Baklava: ]
Enjoy your meal!
Unfortunately, I am getting this output:
Here is your order Superman:
Appetizer:[Hummus: Olives Olive Oil ]
Appetizer:[Nothing: Main Course :[Fish: Paprika]
Main Course :[Nothing: Main Course :[Baklava:
Main Course :[Nothing:
Enjoy your meal!
I did some assumptions, and made the implementation.
There are some errors with your implementation:
You need to check if the list is empty or not to add ","
You are first adding the selection before checking if it was exit option
I think this could be the code that you are looking for:
public static String collectToppings(Scanner sc, String[] toppingsMenu) {
String list = "";
while (true) {
System.out.println("");
System.out.println("Toppings Menu:");
display(toppingsMenu);
int k = sc.nextInt();
if (k == 0)
break;
if (list.length() == 0) {
list = toppingsMenu[k];
} else {
list += ", " + toppingsMenu[k];
}
}
if (list.length() > 0) {
return list + " ]\r\n\r\n";
} else {
return "]\r\n\r\n";
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = "Superman";
int m, n;
String[] mainMenu = new String[] { "Exit", "Appetizer Menu", "Toppings Menu", "Main Course Menu" };
String[] appetizerMenu = new String[] {"Exit", "Hummus"};
String[] mainCourseMenu = new String[] {"Exit", "Fish"};
String[] dessertMenu = new String[] {"Exit", "Baklava"};
String list ="";
while (true) {
// proocess to select the menu items
System.out.println("Select from menu, " + name);
display(mainMenu);
n = sc.nextInt();
if (n == 0)
break;
if (n == 1) {
while (true) {
System.out.println("");
System.out.println("Appetizer Menu:");
display(appetizerMenu);
m = sc.nextInt();
if (m == 0) {
break;
}
list = list + "Appetizer: [ " + appetizerMenu[m] + ": ";
String[] toppingsMenu = new String[] {"Exit", "Olives", "Olive Oil"};
list += collectToppings(sc, toppingsMenu);
}
}
if (n == 2) {
while (true) {
display(mainCourseMenu);
m = sc.nextInt();
if (m == 0) {
break;
}
list = list + "Main Course: [ " + mainCourseMenu[m] + ": ";
String[] toppingsMenu = new String[] {"Exit", "Paprika"};
list += collectToppings(sc, toppingsMenu) ;
}
}
if (n == 3) {
while (true) {
display(dessertMenu);
m = sc.nextInt();
if (m == 0) {
break;
}
list = list + "Dessert: [ " + dessertMenu[m] + ": ";
String[] toppingsMenu = new String[] {"Exit", "...", "..."};
list += collectToppings(sc, toppingsMenu);
}
}
}
System.out.println("Here is your order " + name + ":\r\n");
System.out.println(list);
System.out.println("Enjoy your meal!");
}
private static void display(String[] menu) {
int i = 0;
for (String s : menu) {
System.out.println(i++ + ". " + s);
}
}
I am working on a method in my program which has to return the value purchaseMethod. The while loop needs to run until "Q" is input into the console. The issue I am having is that I cannot return while in a while loop. Is there any way around this? Possibly making an array or for loop? If the return statement is necessary to be outside of the while-loop, how would I keep the values to total for the purchaseAmount.
public static int getShoppingList(){
Scanner input = new Scanner(System.in);
int eight = 8;
int hat = 32;
int patch = 2;
int sword = 20;
int map = 100;
int shirt = 150;
int quanEight = 0;
int quanHat = 0;
int quanPatch = 0;
int quanSword = 0;
int quanMap = 0;
int quanShirt = 0;
int count = 0;
System.out.println("Enter Item Code, ? or Q: ");
String code = input.next();
// Convert input into character
char ch = code.charAt(0);
// Convert string into uppercase
ch = Character.toUpperCase(ch);
// Calculate total
while (count != 0){
int purchaseAmount = ( quanEight * eight) + ( quanHat * hat) + ( quanPatch * patch) + ( quanSword * sword) + ( quanShirt * shirt) + ( quanMap * map);
if (ch == '?'){
System.out.println("Valid Item codes are: 8 I H M S T.");
System.out.println("Q to quit.");
}
else if (ch == '8'){
quanEight ++;
}
else if (ch == 'I'){
quanHat++;
}
else if (ch == 'H'){
quanPatch++;
}
else if (ch == 'M'){
quanMap++;
}
else if (ch == 'S'){
quanSword++;
}
else if (ch == 'T'){
quanShirt++;
}
else if (ch == 'Q'){
count++;
System.out.println("Pirate Trading Post");
System.out.println(quanEight + " Genuine Piece Of Eight\n " + quanHat + " Pirate Hat\n " + quanPatch +
" Eye Patch\n " + quanSword + " Sword\n " + quanMap + " Treasure Map\n " + quanShirt + " T-Shirt\n ");
System.out.println("Total: " + purchaseAmount + " bits");
return purchaseAmount;
}
}
}
The problem is a compile problem with this:
int count = 0;
while (count != 0){ // count **IS** 0, does not enter
// your stuff
}
// no return
If with the return command you intend to return the purchaseAmount to the caller of getShoppingList() method, I suggest you moving the return to the end of the method and putting a break in its while instead of purchaseAmount. Like this:
while (count != 0){
// your stuff
if (...) {
// ...
} else if (ch == 'Q'){
// ...
break;
}
}
return purchaseAmount;
If there are numbers in which some are in sequence and some are random number, then how the consecutive numbers can be replaced with the range of number and random number should be as it is?
for eg: 1,2,3,4,5,6, 458,243
output: 1-6,458,243
I have just solved this problem..Its super simple just some if-else condition, however, I don't think about efficient way, so please follow the solution and try to efficient it.
public static void main(String[] args) {
int [] numberList = {1,2,3,4,5,6,458,243};
int initialSequence = -1;
int endSequence = -5;
for (int num = 0; num<numberList.length;num++) {
if(num<numberList.length-1) {
if(initialSequence == -1 && numberList[num] == numberList[num+1]-1) {
initialSequence = endSequence = numberList[num];
}else if(initialSequence == -1 && numberList[num] != numberList[num+1]-1){
System.out.print(numberList[num] + " ");
}else if(initialSequence != -1 && numberList[num] == numberList[num+1]-1) {
endSequence = numberList[num];
}
else {
System.out.print(initialSequence + "-" + (endSequence+1) + " ");
initialSequence = -1;
endSequence = -5;
}
}else {
if(initialSequence == -1) System.out.print(numberList[num] + " ");
else {
System.out.print(initialSequence + "-" + (endSequence+1) + " ");
}
}
}
}
While looking for a solution to this I found a suggestion to use sc.next() instead of sc.nextLine() but I can't use that so I require additional assistance.
I Am developing an online multiplayer text game and need to filter player name but I keep getting the error "String index out of range: 0" I have tried for hours to fix this and have not been able to find a solution.
The Function causing the error is this:
public static Player charCreate(Player player) {
int points = 60;
int i = 0;
boolean cont = true;
int str = 0;
int dex = 0;
int end = 0;
int INT = 0;
int lck = 0;
int cha = 0;
Output.slowDiscription("You stand there and think about all"
+ " that has transpired, who are you realy?");
System.out.print("What is your Name? ");
boolean bool = false;
String temp;
String name = null; //name is forced to be declared by while loop
do {
name = sc.nextLine();
System.out.println(name);
if (Utills.profan(name) && (name != null)
&& ((!name.equals("")) || (!name.equals(" ")))) {
bool = true;
player.setName(Utills.filter(name)); //Error is here
}
else {
bool = false;
}
} while (bool == false);
player.Height = getUsrHeight();
System.out.print("Please select your stats. ");
do {
System.out.println("Points Remaining: " + points);
switch (i) {
case 0:
System.out.println();
System.out.println("Please Enter the number of points to alot to "
+ "Strength.\n Min:1 Max:18");
str = sc.nextInt();
if ((str >= 1) && (str <= 18) && (str <= points) &&
((points - str) >= 5)) {
points -= str;
i++;
}
break;
case 1:
System.out.println();
System.out.println("Please Enter the number of points to alot to "
+ "Dexterity.\n Min:1 Max:18");
dex = sc.nextInt();
if ((dex >= 1) && (dex <= 18) && (dex <= points) &&
((points - dex) >= 4)) {
points -= dex;
i++;
}
break;
case 2:
System.out.println();
System.out.println("Please Enter the number of points to alot to "
+ "Endurance.\n Min:1 Max:18");
end = sc.nextInt();
if ((end >= 1) && (end <= 18) && (end <= points) &&
((points - end) >= 3)) {
points -= end;
i++;
}
break;
case 3:
System.out.println();
System.out.println("Please Enter the number of points to alot to "
+ "Inteligence.\n Min:1 Max:18");
INT = sc.nextInt();
if ((INT >= 1) && (INT <= 18) && (INT <= points) &&
((points - INT) >= 2)) {
points -= INT;
i++;
}
break;
case 4:
System.out.println();
System.out.println("Please Enter the number of points to alot to "
+ "Luck.\n Min:1 Max:18");
lck = sc.nextInt();
if ((lck >= 1) && (lck <= 18) && (lck <= points) &&
((points - lck) >= 1)) {
points -= lck;
i++;
}
break;
case 5:
System.out.println();
System.out.println("Please Enter the number of points to alot to "
+ "Charisma.\n Min:1 Max:18");
cha = sc.nextInt();
if ((cha >= 1) && (cha <= 18) && (cha <= points)) {
points -= cha;
i++;
}
break;
case 6:
int[] stats = {str, dex, end, INT, lck, cha};
player.setStats(stats);
cont = false;
break;
}
}while (cont);
return player;
}
The Error here comes from the Utills.filter(name):
public static String filter(String name) {
//Variables
String[] Name = name.toLowerCase().split(" ");
StringBuilder sb = new StringBuilder();
StringBuilder endStr = new StringBuilder();
char temp;
int i = 0;
//Sorting
for(String w: Name) {
sb.append(w);
temp = Character.toUpperCase(sb.charAt(0)); //And Error is here
sb.setCharAt(0, temp);
if(i >= 1) {
endStr.append(" " + sb.toString());
}
else {
endStr.append(sb);
}
i++;
empty(sb);
}
return endStr.toString();
}
I would be greatfull for any help
I think your problem is this:
if (Utills.profan(name) && (name != null)
&& ((!name.equals("")) || (!name.equals(" "))))
It should probably be
if (Utills.profan(name) && (name != null)
&& !name.equals("") && !name.equals(" "))
or even
if (Utills.profan(name) && (name != null)
&& !name.trim().isEmpty())
If you still don't see what problem I mean, the check ((!name.equals("")) || (!name.equals(" "))) will always be true, because name is always either not "" or not " ".
I'm working on a program to display 7 random numbers between 1 and 42 using the Math.random method while also checking that no 2 numbers generated are the same. The way I have gotten it to work so far is by creating 7 different variables and checking each one to make sure it's not equal to the previous one which is extremely inefficient! Look below:
import javax.swing.JOptionPane;
public class LottoDrawEdited {
public static void main(String[] args) {
int no1 = 0, no2 = 0, no3 = 0, no4 = 0, no5 = 0, no6 = 0, no7 = 0;
String Numbers = "";
no1 = (int)(Math.random()*42 + 1);
Numbers += no1 + " ";
no2 = (int)(Math.random()*42 + 1);
do{
if(no2 == no1){
no2 = (int)(Math.random()*42 + 1);
}
}while(no2 == no1);
Numbers += no2 + " ";
no3 = (int)(Math.random()*42 + 1);
do{
if(no3 == no1 || no3 == no2){
no3 = (int)(Math.random()*42 + 1);
}
}while(no3 == no1 || no3 == no2);
Numbers += no3 + " ";
no4 = (int)(Math.random()*42 + 1);
do{
if(no4 == no1 || no4 == no2 || no4 == no3){
no4 = (int)(Math.random()*42 + 1);
}
}while(no4 == no1 || no4 == no2 || no4 == no3);
Numbers += no4 + " ";
no5 = (int)(Math.random()*42 + 1);
do{
if(no5 == no1 || no5 == no2 || no5 == no3 || no5 == no4){
no5 = (int)(Math.random()*42 + 1);
}
}while(no5 == no1 || no5 == no2 || no5 == no3 || no5 == no4);
Numbers += no5 + " ";
no6 = (int)(Math.random()*42 + 1);
do{
if(no6 == no1 || no6 == no2 || no6 == no3 || no6 == no4 || no6 == no5){
no6 = (int)(Math.random()*42 + 1);
}
}while(no6 == no1 || no6 == no2 || no6 == no3 || no6 == no4 || no6 == no5);
Numbers += no6 + " ";
no7 = (int)(Math.random()*42 + 1);
do{
if(no7 == no1 || no7 == no2 || no7 == no3 || no7 == no4 || no7 == no5 || no7 == no6){
no7 = (int)(Math.random()*42 + 1);
}
}while(no7 == no1 || no7 == no2 || no7 == no3 || no7 == no4 || no7 == no5 || no7 == no6);
Numbers += no7 + " ";
JOptionPane.showMessageDialog(null,"The Lotto Numbers Are:\n" + Numbers,"Lotto Draw",JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}
As you can see it looks awful. Before I started this way I was trying to figure out whether I could:
Only Have 1 Variable
Generate the first variable
Append the first variable to a JTextArea
Clear the first variable
Generate the second variable
Somehow check if that matches the 1st variable which is already appended onto the JTextArea?
That way would be much more efficient and would take significantly less code but I can't manage to work my head around it with any other more efficient solution. What would be the best way to go about doing it more efficiently and does my logic above make any sense when it comes to using JTextArea?
Thanks for your time!
You could put each value you calculate into a List or Set and check it to see if you've already used and calculate a new one if you have.
Something along the lines of...
List<Integer> values = new ArrayList<>(25);
//...
int value = -1;
do {
value = (int)(Math.random()*42 + 1);
} while (values.contains(value));
values.add(value);
textArea.append(Integer.toString(value) + "\n");
... for example...
You could wrap the generation of the numbers into a method to make it eaiser...
public int getNextNumber() {
int value = -1;
do {
value = (int)(Math.random()*42 + 1);
} while (values.contains(value));
values.add(value);
return value;
}
This would assume you've made the values List and instance field...
Take a look at Collections Trail for more details
Updated
If using a List is to complex or not allowed, you could roll your own functionality using arrays, for example...
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
new Test();
}
private int[] values = new int[6];
private int count = 0;
public Test() {
for (int index = 0; index < values.length; index++) {
System.out.println(getNextNumber());
}
}
public int getNextNumber() {
int value = -1;
if (count < values.length) {
do {
value = (int) (Math.random() * 42 + 1);
} while (contains(value));
values[count] = value;
count++;
}
return value;
}
protected boolean contains(int value) {
Arrays.sort(values);
return Arrays.binarySearch(values, value) >= 0;
}
}
This becomes a little more complex, as you need to guard against ArrayIndexOutOfBoundsExceptions
Now, if Arrays.sort and Arrays.binarySearch are to complex or not allowed, you could change it for something like...
private boolean contains(int value) {
boolean contains = false;
for (int check : values) {
if (value == check) {
break;
}
}
return contains;
}
Which will do the same job...