This is on day four of advent of code part two...
I tried out the sample input they gave and it was correct and I used the input I have and comes out wrong every time
What I see 1
What I see 2
There is more below but its what happens after you solve the first part
Advent of code day 4
Puzzle input
The input differs by user but the code should be the same no matter the input
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:
If cm, the number must be at least 150 and at most 193.
If in, the number must be at least 59 and at most 76.
hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
pid (Passport ID) - a nine-digit number, including leading zeroes.
cid (Country ID) - ignored, missing or not.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File inputText = new File("src/input.txt");
Scanner sc = new Scanner(inputText);
ArrayList<ArrayList> ids = new ArrayList<>();
ArrayList<ArrayList> attributes = new ArrayList<>();
while (sc.hasNextLine()) {
String builtString = "";
String input = "1";
while(input.length() != 0 && sc.hasNextLine()) {
input = sc.nextLine();
builtString += input + " ";
}
String[] temp = builtString.split(" ");
ArrayList<String> tempIds = new ArrayList<>();
ArrayList<String> tempAttributes = new ArrayList<>();
for (String i : temp) {
tempIds.add(i.split(":")[0]);
tempAttributes.add(i.split(":")[1]);
}
ids.add(tempIds);
attributes.add(tempAttributes);
}
System.out.println(ids);
System.out.println(attributes);
int valid = 0;
for (int a = 0; a < ids.size(); a++) {
int has = 0;
for (int j = 0; j < ids.get(a).size(); j++) {
String id = ids.get(a).get(j).toString();
String attribute = attributes.get(a).get(j).toString();
if (id.contains("ecl")) {
if (attribute.contains("blu") || attribute.contains("brn") || attribute.contains("gry") || attribute.contains("grn") || attribute.contains("hzl") || attribute.contains("oth")) {
System.out.println(attribute + " is an eye color");
has++;
} else {
System.out.println(attribute + " is not an eye color");
}
has++;
}
if (id.contains("pid")) {
if (attribute.length() == 9) {
try {
Integer.parseInt(attribute);
System.out.println(attribute + " of pid attribute is valid ");
has++;
} catch (Exception e) {
System.out.println(attribute + " of pid attribute is not valid");
}
}
has++;
}
if (id.contains("eyr")) {
int at = Integer.parseInt(attribute);
if (at >= 2020 && at <= 2030) {
System.out.println(attribute + " attribute of eyr is valid");
has++;
} else {
System.out.println(attribute + " attribute of eyr is not valid");
}
has++;
}
if (id.contains("hcl")) {
boolean isValid = false;
if (attribute.contains("#")) {
for (char c : attribute.toCharArray()) {
if (attribute.length() == 7) {
if ((c >= 'a' && c <= 'f') || c == '#') {
isValid = true;
} else if (Character.isDigit(c)) {
isValid = true;
} else {
isValid = false;
break;
}
}
}
}
if (isValid) {
has++;
}
System.out.println(attribute + " hcl is " + isValid);
has++;
}
if (id.contains("byr")) {
int date = Integer.parseInt(attribute);
if (date >= 1920 && date <= 2002) {
System.out.println(attribute + " byr attribute is valid");
has++;
} else {
System.out.println(attribute + " byr attribute is not valid");
}
has++;
}
if (id.contains("iyr")) {
int date = Integer.parseInt(attribute);
if (date >= 2010 && date <= 2020) {
has++;
} else {
System.out.println(attribute + " iyr is false");
}
has++;
}
if (id.contains("hgt")) {
boolean isValid = false;
String type = attribute.replaceAll("[^A-Za-z]", "");
int amount = Integer.parseInt(attribute.replaceAll("[^0-9]", ""));
if (type.equals("in")) {
if (amount >= 59 && amount <= 76) {
isValid = true;
has++;
}
} else if (type.equals("cm")) {
if (amount >= 150 && amount <= 193) {
isValid = true;
has++;
}
}
System.out.println(attribute + " hgt is " + isValid);
has++;
}
}
System.out.println();
if (has >= 14) {
valid++;
}
}
System.out.println(valid);
System.out.println("End");
}
}
you forgot the 'amb' eye colour. If you add this to the if statement on line 41 it should work
if (attribute.contains("amb") || attribute.contains("blu") || attribute.contains("brn") || attribute.contains("gry") || attribute.contains("grn") || attribute.contains("hzl") || attribute.contains("oth")) {
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);
}
}
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) + " ");
}
}
}
}
Doing my AP Computer Science homework right now but I am stuck with run-time errors. Does anyone know what is wrong with my code?
The program was working fine on Dr.Java but it shows run-time error on my website tester in edhesive...
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String tweet = scan.nextLine();
int hash = 0;
int attr = 0;
int link = 0;
int ch = 0;
if(tweet.length()>140)
{
System.out.println("Excess Characters: " + (tweet.length() - 140 ));
}
else
{
tweet=tweet.toLowerCase();
System.out.println("Length Correct");
for(ch=0; ch<tweet.length(); ch++)
{
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
hash++;
}
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
attr++;
}
if(tweet.charAt(ch) == 'h' && ((ch + 7)<=(tweet.length())))
{
String a = new String("http://");
String sub = new String(tweet.substring(ch, ch + 7));
if (sub.equals(a))
{link++;}
}
}
System.out.println("Number of Hashtags: " + hash);
System.out.println("Number of Attributions: " + attr);
System.out.println("Number of Links: " + link);
}
}
}
Because of ch++ the value of ch is getting incremented after checking this condition (ch++)<=(tweet.length()).
Explanation :
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
hash++;
}
For above code there are 4 conditions (for i=0):
tweet.charAt(ch) ch = 0
((ch++)<=(tweet.length())) ch = 0, but ch++ so the value will be increamented after the condition check.
(tweet.charAt(ch++) ch=1 (becuase of Point No. 2)
tweet.charAt(ch++) ch = 2 (for the same reason).
Try this:
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String tweet = scan.nextLine();
int hash = 0;
int attr = 0;
int link = 0;
int ch = 0;
if(tweet.length()>140)
{
System.out.println("Excess Characters: " + (tweet.length() - 140 ));
}
else
{
tweet=tweet.toLowerCase();
System.out.println("Length Correct");
for(ch=0; ch<tweet.length(); ch++)
{
if(tweet.charAt(ch) == '#' && ((ch+1)<(tweet.length())) && (tweet.charAt(ch+1)!=' ' && tweet.charAt(ch+1)!='\t'))
{
hash++;
}
if(tweet.charAt(ch) == '#' && ((ch+1)<(tweet.length())) && (tweet.charAt(ch+1)!=' ' && tweet.charAt(ch+1)!='\t'))
{
attr++;
}
if(tweet.charAt(ch) == 'h' && ((ch + 7)<(tweet.length())))
{
String a = new String("http://");
String sub = new String(tweet.substring(ch, ch + 7));
if (sub.equals(a))
{link++;}
}
}
System.out.println("Number of Hashtags: " + hash);
System.out.println("Number of Attributions: " + attr);
System.out.println("Number of Links: " + link);
}
}
}
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("_____________");
}
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....