String index out of range: 0 - java

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 " ".

Related

Is there a reason why I cannot return inside of a While loop?

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;

Variable not being recognized in method

I am relatively new to Java, and I am writing a simple program to play rock, paper, scissors. This is the code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static String comChoice() {
Random rand = new Random();
int num = rand.nextInt(299) + 1;
if (num >= 1 && num <= 99) {
String pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
String pick = "ROCK";
} else if (num >= 200 && num <= 299) {
String pick = "PAPER";
}
return pick;
}
public static void main(String args[]) {
int wins = 0;
int losses = 0;
int ties = 0;
while (1 == 1) {
Scanner s = new Scanner(System.in);
System.out.println("Would you like to play Rock Paper Scissors? Y/N");
String n = s.next();
if (n.equalsIgnoreCase("Y")) {
Scanner t = new Scanner(System.in);
System.out.println("Enter your pick: rock, paper, or scissors");
String userChoice = t.next();
String pick = comChoice();
if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("TIE");
ties++;
} else if (userChoice.equalsIgnoreCase("ROCK") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("WIN");
wins++;
} else if (userChoice.equalsIgnoreCase("PAPER") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("LOSE");
losses++;
} else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("ROCK")) {
System.out.println("LOSE");
losses++;
} else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("PAPER")) {
System.out.println("WIN");
wins++;
} else {
System.out.println("Enter a valid choice");
}
} else {
System.out.println("You won " + wins + " matches");
System.out.println("You tied " + ties + " matches");
System.out.println("You lost " + losses + " matches");
break;
}
}
}
}
I'm getting an error in my method which says this:
Main.java:23: error: cannot find symbol
return pick;
^
symbol: variable pick
location: class Main
1 error
exit status 1
I can't figure out how to fix this error. I would appreciate your input as well as any other general advice
Thanks
Your variable is only visible in the if statement. Read about scopes.
Change to:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static String comChoice() {
Random rand = new Random();
int num = rand.nextInt(299) + 1;
String pick = null;
if (num >= 1 && num <= 99) {
pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
pick = "ROCK";
} else if (num >= 200 && num <= 299) {
pick = "PAPER";
}
return pick;
}
....
}
pick is out of scope. Try declaring at the start of the comChoice method.
Hence :
public static String comChoice() {
String pick=null;
Random rand = new Random();
int num = rand.nextInt(299) + 1;
if (num >= 1 && num <= 99) {
pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
pick = "ROCK";
} else if (num >= 200 && num <= 299) {
pick = "PAPER";
}
return pick;
}
variable pick is out of scope. You have to declare it outside the all if else statements. if all if else condition fail then comChoice method will not be able to find variable pick (as it is declared inside the if else block only)which it has to return.
corrected code
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static String comChoice()
{
Random rand = new Random();
int num = rand.nextInt(299) + 1;
String pick = "";
if(num >= 1 && num <= 99)
{
pick = "SCISSORS";
}
else if (num >= 100 && num <= 199)
{
pick = "ROCK";
}
else if (num >= 200 && num <= 299)
{
pick = "PAPER";
}
return pick;
}
public static void main (String args[])
{
int wins = 0;
int losses = 0;
int ties = 0;
while (1 == 1)
{
Scanner s = new Scanner (System.in);
System.out.println("Would you like to play Rock Paper Scissors? Y/N");
String n = s.next();
if (n.equalsIgnoreCase("Y"))
{
Scanner t = new Scanner (System.in);
System.out.println("Enter your pick: rock, paper, or scissors");
String userChoice = t.next();
String pick = comChoice();
if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("TIE");
ties++;
}
else if (userChoice.equalsIgnoreCase("ROCK") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("WIN");
wins++;
}
else if (userChoice.equalsIgnoreCase("PAPER") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("LOSE");
losses++;
}
else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("ROCK"))
{
System.out.println("LOSE");
losses++;
}
else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("PAPER"))
{
System.out.println("WIN");
wins++;
}
else
{
System.out.println("Enter a valid choice");
}
}
else
{
System.out.println("You won " + wins + " matches");
System.out.println("You tied " + ties + " matches");
System.out.println("You lost " + losses + " matches");
break;
}
}
}
}
You declared your variable pick in the if else structure. Doing this causes the problem that your variable cannot be accessed from outside that if else structure. In simple words, the variable pick's scope is limited to your if else structure. You have to declare your variable (and initialize it as well, otherwise you'll get an error in your case) outside of the if else structure. Like this:
String pick = null;
if(num >= 1 && num <= 99) {
...
...
...// All your if's and else's
}
return pick;
Hope this helps!

Encountering Error with Pig Code

My variable names are pretty stupid near the bottom but that's not the point. Line 110 says that I'm making an else statement without the if and I'm nearly certain the if is there. Please help in any way you can.
Thank you
import java.util.*;
public class hw7
{
public static void main(String[] args)
{
int turnScores = 0;
int totalScores = 0;
int turnScores2 = 0;
int totalScores2 = 0;
int dice;
int dice2;
String input = "r";
char repeat;
boolean peppers;
peppers = true;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(totalScores < 20 || totalScores2 < 20)
{
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScores = 0;
System.out.print("Your lose your turn!");
System.out.println("Your Total is " + totalScores);
break;
}
else
{
turnScores += dice;
System.out.print("Your turn score is " + turnScores);
System.out.println(" and your total scores is " + totalScores);
System.out.println("If you hold, you will have " + turnScores
+ " points.");
System.out.println("Enter 'r' to roll again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h')
{
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
totalScores += turnScores;
peppers = peppers(turnScores, turnScores2);
System.out.println("Your scores is " + totalScores);
turnScores = 0;
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The computer rolled: " + dice2);
if(dice2 == 1)
{
turnScores2 = 0;
System.out.print("The computer lost its turn!");
System.out.println(" Computer total is " + totalScores2);
break;
}
else
{
turnScores2 += dice2;
if(turnScores2 >= 20 || (totalScores2 + turnScores2) >= 20 )
{
System.out.println("The computer holds");
break;
}
}
}
while(dice2 != 1 || turnScores2 < 20);
totalScores2 += turnScores2;
System.out.println("The computer's scores is " + totalScores2 + "\n");
turnScores2 = 0;
}
}
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20);
{
done = false;
System.out.println(" YOU WIN!!!");
return done;
}
else (ghost >= 20);
{
done = false;
System.out.println(" COMPUTER WINS");
return done;
}
/*else
{
return done;
}
*/
}
}
Try removing the semicolons in if(chili >= 20); and else (ghost >= 20);.
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20)
{
done = false;
System.out.println(" YOU WIN!!!");
}
else if (ghost >= 20)
{
System.out.println(" COMPUTER WINS");
}
return done;
}
replace
else (ghost >= 20);
with
else if (ghost >= 20)
and remove the semicolons after the if-statement.

Java String Calculator

I'm trying to make a simple calculator in Java which takes input in the form of a string and does a simple '+' and '-' operation.
Single digit inputs work but my problem is when i try to implement this for double digit
input string is: 5+20+5+11
list 1 = [5, 20, 2, 0, 5, 11, 1]
list 2 = [+, +, +]
Answer:27
I need to find a way where after storing [5] in list1 how i can add [5,20] instead of [5,20,2,0] which the current code is doing.
public int calC(String input) {
int len = input.length();
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
for (int i = 0; i < len; i++) {
if ((input.charAt(i) != '+') && (input.charAt(i) != '-')) {
// check if the number is double-digit
if ((i + 1 <= len - 1)) {
if ((input.charAt(i + 1) != '+')&& (input.charAt(i + 1) != '-')) {
String temp = "";
temp = temp + input.charAt(i) + input.charAt(i + 1);
int tempToInt = Integer.parseInt(temp);
// adding the double digit number
list1.add(tempToInt);
}
// add single digit number
list1.add(input.charAt(i) - '0');
}
} else {
// adding the symbols
list2.add(input.charAt(i));
}
}
int result = 0;
result = result + (int) list1.get(0);
for (int t = 0; t < list2.size(); t++) {
char oper = (char) list2.get(t);
if (oper == '+') {
result = result + (int) list1.get(t + 1);
} else if (oper == '-') {
result = result - (int) list1.get(t + 1);
}
}
return result;
}
Edit: working version
#Ker p pag thanks for the updated methods
input string is: 5+20+5+11
[5, 20, 5, 11]
[+, +, +]
Answer:41
I'll need to try to implement this with stack as suggested but the current version works
static boolean isDigit(char check) {
if (Character.isDigit(check)) {
return true;
}
return false;
}
public static int calC(String input) {
int len = input.length();
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
for (int i = 0; i < len; i++) {
if ((i + 1 <= len - 1)) {
if (isDigit(input.charAt(i)) && isDigit(input.charAt(i + 1))) {
String temp = input.charAt(i) + "" + input.charAt(i + 1);
int toInt = Integer.parseInt(temp);
list1.add(toInt);
i = i+1;
} else if (isDigit(input.charAt(i))) {
list1.add(input.charAt(i)- '0');
} else {
list2.add(input.charAt(i));
}
}
}
int result = 0;
result = result + (int) list1.get(0);
for (int t = 0; t < list2.size(); t++) {
char oper = (char) list2.get(t);
if (oper == '+') {
result = result + (int) list1.get(t + 1);
} else if (oper == '-') {
result = result - (int) list1.get(t + 1);
}
}
return result;
}
Here is the code:
String a = "5+20-15+8";
System.out.println(a);
String operators[]=a.split("[0-9]+");
String operands[]=a.split("[+-]");
int agregate = Integer.parseInt(operands[0]);
for(int i=1;i<operands.length;i++){
if(operators[i].equals("+"))
agregate += Integer.parseInt(operands[i]);
else
agregate -= Integer.parseInt(operands[i]);
}
System.out.println(agregate);
If you want the result 41 for input string "5+20+5+11",
why not use ScriptEngineManager with JavaScript engine,
public double calC(String input) {
int result = 0;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
return (Double)engine.eval(input);
}
But note that the return type is double here.
If you want only int as return type in this case, try with this
return new BigDecimal(engine.eval(input).toString()).intValue();
Another way to think about this:
public class InlineParsing {
public static void main(String []args){
String input = "5-2+20+5+11-10";
input = input.replace(" ","");
String parsedInteger = "";
String operator = "";
int aggregate = 0;
for (int i = 0; i < input.length(); i++){
char c = input.charAt(i);
if (Character.isDigit(c)) {
parsedInteger += c;
}
if (!Character.isDigit(c) || i == input.length()-1){
int parsed = Integer.parseInt(parsedInteger);
if (operator == "") {
aggregate = parsed;
}
else {
if (operator.equals("+")) {
aggregate += parsed;
}else if (operator.equals("-")){
aggregate -= parsed;
}
}
parsedInteger ="";
operator = ""+c;
}
}
System.out.println("Sum of " + input+":\r\n" + aggregate);
}
}
It's basically a state machine that traverses over each char.
Iterate over each char:
if current char is a digit, add to current number buffer
if current char is not a digit or we're parsing the last digit
if an operator has been parsed use that to add the newly parsed number to the sum
if no operator has been parsed, set sum to current parsed number
clear current number buffer
store current char as operator
I agree that stack is the best solution,but still giving an alternative way
of doing this.
String input = "5+20+11+1";
StringBuilder sb = new StringBuilder();
List<Integer> list1 = new ArrayList<Integer>();
List<Character> list2 = new ArrayList<Character>();
char[] ch = input.toCharArray();
for(int i=0;i<ch.length;i++)
{
if(ch[i]!='+')
{
sb.append(ch[i]);
}else
{
list2.add(ch[i]);
list1.add(Integer.valueOf(sb.toString()));
sb.setLength(0);
}
}
if(sb.length()!=0)
list1.add(Integer.valueOf(sb.toString()));
System.out.println(list1.size());
for(Integer i:list1)
{
System.out.println("values"+i);
}
for storing the input to the list you could try this snippet
for (int i = 0; i < input.length() - 1; i++) {
// make a method
// check if current character is number || check if current
// character is number and the next character
if (isDigit(input.charAt(i)) && isDigit(input.charAt(i + 1))) {
list.add(input.charAt(i) +""+ input.charAt(i + 1));
} else if (isDigit(input.charAt(i))) {
list.add(input.charAt(i));
}else{
operator.add(input.charAt(i));
}
}
//check if it is a number
public boolean isDigit(char input){
if(input == '1' ||
input == '2' ||
input == '3' ||
input == '4' ||
input == '5' ||
input == '6' ||
input == '7' ||
input == '8' ||
input == '9' ||
input == '0')
return true;
return false;
}
I could advise you to use Exp4j. It is easy to understand as you can see from the following example code:
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
Especially for the case of using more complex expression this could be a better choice.
private static int myCal() {
String[] digits = {
"1",
"2",
"3",
"4",
"5"
};
String[] ops = {
"+",
"+",
"+",
"-"
};
int temp = 0;
int res = 0;
int count = ops.length;
for (int i = 0; i < digits.length; i++) {
res = Integer.parseInt(digits[i]);
if (i != 0 && count != 0) {
count--;
switch (ops[i - 1]) {
case "+":
temp = Math.addExact(temp, res);
break;
case "-":
temp = Math.subtractExact(temp, res);
break;
case "*":
temp = Math.multiplyExact(temp, res);
break;
case "/":
temp = Math.floorDiv(temp, res);
break;
}
}
}
return temp;
}
You can check this code that I created using array only. I also tried several arithmetic problems also your given problem.
Please see also the comments within the method.
public static String Calculator(String str) {
// will get all numbers and store it to `numberStr`
String numberStr[] = str.replaceAll("[+*/()-]+"," ").split(" ");
// will get all operators and store it to `operatorStr`
String operatorStr[] = str.replaceAll("[0-9()]+","").split("");
int total = Integer.parseInt(numberStr[0]);
for (int i=0; i<operatorStr.length; i++) {
switch (operatorStr[i]) {
case "+" :
total += Integer.parseInt(numberStr[i+1]);
break;
case "-" :
total -= Integer.parseInt(numberStr[i+1]);
break;
case "*" :
total *= Integer.parseInt(numberStr[i+1]);
break;
case "/" :
total /= Integer.parseInt(numberStr[i+1]);
break;
}
if(i+2 >= operatorStr.length) continue; // if meets the last operands already
numberStr[i+1] = String.valueOf(total);
}
return String.valueOf(total);
}
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Character> listOfOpertionsCharFORM = new ArrayList<>();
ArrayList<Character> listOfNumbersCharFORM = new ArrayList<>();
ArrayList<Integer> listOfNumbersINTEGERFORM = new ArrayList<>();
int Total = 0;
Scanner sc = new Scanner(System.in);
String input;
System.out.print("Please enter your math equation :");
input = sc.nextLine();
System.out.println("string is : " + input);
separator();
char[] convertAllToChar = input.toCharArray();
for (char inputToChar : convertAllToChar) {
System.out.println("convertAllToChar " + inputToChar);
}
for (int i = 0; i < input.length(); i++) {
if (convertAllToChar[i] == '+') {
listOfOpertionsCharFORM.add(convertAllToChar[i]);
}
if (convertAllToChar[i] == '-') {
listOfOpertionsCharFORM.add(convertAllToChar[i]);
}
if (convertAllToChar[i] == '*') {
listOfOpertionsCharFORM.add(convertAllToChar[i]);
}
if (convertAllToChar[i] == '/') {
listOfOpertionsCharFORM.add(convertAllToChar[i]);
}
if (Character.isDigit(convertAllToChar[i])) {
listOfNumbersCharFORM.add(convertAllToChar[i]);
}
}
separator();
for (Character aa : listOfOpertionsCharFORM) {
System.out.println("list Of Operations Char FORM " + aa);
}
separator();
for (Character aa : listOfNumbersCharFORM) {
System.out.println("list Of Numbers Char FORM " + aa);
}
separator();
for (Character aa : listOfNumbersCharFORM) {
if (aa == '0') listOfNumbersINTEGERFORM.add(0);
if (aa == '1') listOfNumbersINTEGERFORM.add(1);
if (aa == '2') listOfNumbersINTEGERFORM.add(2);
if (aa == '3') listOfNumbersINTEGERFORM.add(3);
if (aa == '4') listOfNumbersINTEGERFORM.add(4);
if (aa == '5') listOfNumbersINTEGERFORM.add(5);
if (aa == '6') listOfNumbersINTEGERFORM.add(6);
if (aa == '7') listOfNumbersINTEGERFORM.add(7);
if (aa == '8') listOfNumbersINTEGERFORM.add(8);
if (aa == '9') listOfNumbersINTEGERFORM.add(9);
}
for (Integer aaa : listOfNumbersINTEGERFORM) {
System.out.println("list Of Numbers INTEGER FORM " + aaa);
}
separator();
separator();
separator();
System.out.print(listOfNumbersINTEGERFORM);
System.out.print(listOfOpertionsCharFORM);
System.out.println();
System.out.println();
if (listOfNumbersINTEGERFORM.size() == (listOfOpertionsCharFORM.size() + 1)) {
for (int i = 0; i < listOfOpertionsCharFORM.size(); i++) {
System.out.println("i :" + i);
if (listOfOpertionsCharFORM.get(i) == '+') if (i == 0) {
Total = Total + listOfNumbersINTEGERFORM.get(i) + listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
} else {
Total = Total + listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
}
if (listOfOpertionsCharFORM.get(i) == '-') if (i == 0) {
Total = Total + listOfNumbersINTEGERFORM.get(i) - listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
} else {
Total = Total - listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
}
if (listOfOpertionsCharFORM.get(i) == '*') if (i == 0) {
Total = Total + listOfNumbersINTEGERFORM.get(i) * listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
} else {
Total = Total * listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
}
if (listOfOpertionsCharFORM.get(i) == '/') if (i == 0) {
Total = Total + listOfNumbersINTEGERFORM.get(i) / listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
} else {
Total = Total / listOfNumbersINTEGERFORM.get(i + 1);
System.out.println("total : " + Total);
separatorShort();
}
}
} else {
System.out.println("*********###############**********");
System.out.println("** your input not correct input **");
System.out.println("*********###############**********");
}
System.out.println("*** Final Answer *** : " + Total);
}
public static void separator() {
System.out.println("___________________________________");
}
public static void separatorShort() {
System.out.println("_____________");
}

Having trouble with this Java program that does some math

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....

Categories