Input to exit java program when blank line entered - java

I have written a RPN Calculator in Java, but I am struggling to get my code to exit when the user enters a blank line instead of an equation. The program needs to loop until this blank line is entered.
Below is my source code.
$`import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
import java.io.FileNotFoundException;
public class Calculator {
private static Scanner input;
public static int invalidlines = 0;
public static int validlines = 0;
public static ArrayList<String> validList = new ArrayList<String>();
public void FileNotFoundException(){
System.out.println("Please enter a valid expression!");
}
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
}
catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
}
else
{
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
}
else
{
return false;
}
}
}
public static void main(String[] args) throws IOException {
input = new Scanner(System.in);
String keyboardInput = new String();
String currentLine = new String();
Scanner kbScan = new Scanner(System.in);
System.out.println("Please press the letter F for file input or K for keyboard input");
String inputString = new String(input.nextLine());
int answer = 0;
while (true){
if (inputString.equals("K") || inputString.equals("k")) {
System.out.println("Please enter an equation");
keyboardInput = kbScan.nextLine();
}
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
if (inputString.equals("") || inputString.equals(""));
{
System.exit(0);
}
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch(equation[2]) { // This case switch checks the third position of the string to decide which operator is being used. It then works out the answer and breaks to the next instruction
case("+"):
answer = num1 + num2;
break;
case("-"):
answer = num1 - num2;
break;
case("/"):
answer = num1 / num2;
break;
case("*"):
answer = num1 * num2;
break;
}
System.out.println("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
System.out.println("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
}
else{
System.out.println("The equation you entered is invalid");
}
if (inputString.equals("f") || inputString.equals("F")) {
try{
//Open the file
System.out.println("Enter File Name: ");
FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
String strLine; // create string vars
//loop to read the file line by line
while ((strLine = br.readLine()) != null) { // Whilst the buffered readers read line method is not null, read and validate it.
currentLine = strLine;
if(isValidLine(currentLine))
{
validList.add(currentLine);
validlines++;
String[] filearray = new String[3];
filearray = currentLine.split(" ");
int val1 = Integer.parseInt(filearray[0]);
int val2 = Integer.parseInt(filearray[1]);
System.out.println("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
switch(filearray[2]) {
case("+"):
answer = val1 + val2;
break;
case("-"):
answer = val1 - val2;
break;
case("/"):
answer = val1 / val2;
break;
case("*"):
answer = val1 * val2;
break;
}
System.out.println("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Please Enter a valid file name");
}
}
}
}
}

Just use following code to check the variable in which you are taking the user input,whether it's empty or not?
I am assuming you are taking in a variable called inputString,then the code should be-
if(inputString.isEmpty())
{
System.exit(0);
}

maybe you should use break instead of System.exit(0).
Also, I would check for empty input as soon as I read the input.

Related

How do I use InputMismatchExeption to catch strings? (Java)

I'm a novice java programmer and need to adjust this code so it catches two strings instead of variables.
Here is the original code we are supposed to use:
import java.util.Scanner;
import java.util.InputMismatchException;
public class Part4 {
public static void main(String[] args) {
int userNum = 0;
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
String dump = null;
while (!inputOK) {
System.out.print("Enter a number: ");
try {
userNum = screen.nextInt();
dump = screen.nextLine();
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal integer, " +
"please try again!");
} // end try-catch block
} // end input loop
screen.close();
userNum = userNum + 20;
System.out.println("Your number plus 20 is " + userNum);
}
}
and here is my failed attempt:
import java.util.Scanner;
import java.util.InputMismatchException;
public class testClass {
public static void main(String[] args) {
String letter = new String();
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
String dump = null;
while (!inputOK) {
System.out.print("Enter ('y' or 'n': )");
try {
letter = screen.nextLine();
dump = screen.nextLine();
inputOK = true;
} catch (InputMismatchException e) {
dump = screen.nextLine();
System.out.println("\"" + dump + "\" is not a legal letter, " +
"please try again!");
}
}
screen.close();
System.out.println("That is a valid letter");
}
}
If anyone could help that would be much appreciated.
Thanks :)
First off InputMismatchException will only be thrown
to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
Since anything but y and n are still String's this won't be thrown. Instead you can throw a new InputMismatchException if it is not y or n:
String letter = new String();
Scanner screen = new Scanner(System.in);
boolean inputOK = false;
while (!inputOK) {
System.out.println("Enter ('y' or 'n': )");
try {
letter = screen.nextLine();
if(!letter.equals("y") && !letter.equals("n")) {
throw new InputMismatchException();
}
inputOK = true;
} catch (InputMismatchException e) {
System.out.println("\"" + letter + "\" is not a legal letter, " +
"please try again!");
}
}
System.out.println("That is a valid letter");
Also it is not good practice to close System.in. The general rule is if you did not open a resource, you should not close it

Scanner skipping nextLine(); after do while loop

as you can probably see I am a newbie in java. Below is a simple calculator program which asks for the user to input a symbol such as + or -. The user then inputs 2 numbers and depending on the operator symbol chosen a method will be called. A do while loop allows the user to repeat the process. The problem is that after the program loops, the following line: "String symb = inp.nextLine();" is skipped. I have already tried searching for a solution however I only found a fix if the nextLine is called after nextInt. Thank you in advance for your patience.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp = new Scanner(System.in);
Methods operation = new Methods();
boolean loop = false;
do {
System.out.println("Enter an operator symbol - +, -, * or /");
String symb = inp.nextLine(); //this is the line which is skipped
System.out.println("Enter a number");
int num1 = inp.nextInt();
inp.nextLine();
System.out.println("Enter a second number");
int num2 = inp.nextInt();
inp.nextLine();
switch(symb) {
case "+" :
operation.setA(num1);
operation.setB(num2);
int totalAddition = operation.addNums(num1,num2);
System.out.println("The result is - " + totalAddition);
break;
case "-" :
operation.setA(num1);
operation.setB(num2);
int totalSubtract = operation.subtractNums(num1,num2);
System.out.println("The result is - " + totalSubtract);
break;
case "*" :
operation.setA(num1);
operation.setB(num2);
int totalMult = operation.multNums(num1,num2);
System.out.println("The result is - " + totalMult);
break;
case "/" :
operation.setA(num1);
operation.setB(num2);
int totalDiv = operation.divNums(num1,num2);
System.out.println("The result is - " + totalDiv);
break;
}
System.out.println("Would you like to exit? Y/N");
char ans = inp.next().charAt(0);
if(ans == 'Y' || ans == 'y') {
loop = true;
inp.close();
System.exit(0);
}
else {
loop = false;
}
}
while(loop == false);
}
}

How to prevent string from printing repeatedly in while loop?

I'm currently working on some exercises given to me by my teacher. These are for the holidays so I won't be able to ask for help there.
I have this piece of code which creates a multiplication table from an integer defined by the user, ranging from a minimum and maximum also defined by the user.
Before setting any of my variables to the next integer in my Scanner, I do a check to see if the Scanner actually has an integer. This works fine but I don't want it to print out the error message a billion times.
Any tips/tricks or other special ways of getting around this?
public class MultiplicationTable
{
private int intervalMin;
private int intervalMax;
private int multiplier;
private int result;
private Scanner sc;
public MultiplicationTable()
{
multiplier = 0;
intervalMin = 0;
sc = new Scanner(System.in);
while (multiplier == 0)
{
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt())
{
multiplier = sc.nextInt();
}
else
{
System.out.println("Input is not an integer\n");
}
}
while (intervalMin == 0)
{
System.out.println("\nPlease enter the integer defining the start of the table");
if (sc.hasNextInt())
{
intervalMin = sc.nextInt();
}
else
{
System.out.println("Input is 0 or not an integer\n");
}
}
while (intervalMax == 0)
{
System.out.println("\nPlease enter the integer defining the end of the table");
if (sc.hasNextInt())
{
int i = sc.nextInt();
if (i > intervalMin)
{
intervalMax = i;
}
else
{
System.out.println("\nEnd integer must be greater than start integer");
}
}
else
{
System.out.println("Input is 0 or not an integer");
}
}
System.out.println("\nTable for integer " + multiplier + " from " + intervalMin + " to " + intervalMax + "\n");
for (int i = intervalMin; i <= intervalMax; i++)
{
result = i * multiplier;
System.out.println(i + " * " + multiplier + " = " + result);
}
}
}
You didn't consume what user entered into the scanner buffer, that's why sc.hasNextInt() keeps getting executed without waiting for the next user input.
The solution is to add sc.nextLine() after the if condition.
For example:
boolean gotInteger = false;
while (!gotInteger) {
System.out.println("Please enter the integer you wish to show the table for");
if (sc.hasNextInt()) {
multiplier = sc.nextInt();
gotInteger = true;
} else {
System.out.println("Input is not an integer\n");
}
sc.nextLine();
}
Pleas try this, just wrap all your code inside try catch:
try {
while (intervalMax == 0) {
System . out . println("\nPlease enter the integer defining the end of the table");
if (sc . hasNextInt()) {
int i = sc . nextInt();
if (i > intervalMin) {
intervalMax = i;
} else {
throw new Exception("\nEnd integer must be greater than start integer");
}
}
}
} catch (Exception e) {
System . out . println(e . getMessage());
}

How to compare two elements from different arrays in Arraylist?

I've created two arrays with ArrayList (java), aList1 and aList2. Both will have a mix of doubles and strings. How do I directly compare the individual contents of aList1 to their corresponding individual contents in aList2 For example, if the first value or string in aList1 doesn't match the first value or string in aList2, there should be a message saying that the two don't match. This should go on for every element of each ArrayList.
Thanks!
EDITED:
Here was my initial attempt:
if (!aList1.get(0).equals(aList2.get(0))) {
JOptionPane.showMessageDialog(null, "#1 is incorrect.");
}
if (!aList1.get(1).equals(aList2.get(1))) {
JOptionPane.showMessageDialog(null, "#2 is incorrect.");
}
And so on, by comparing each element from aList1 to aList2, and seeing if they are not equal (whether they be doubles or strings). The corresponding elements and the sizes of the arrays will always be the same. So for example, if aList1 = {0,1,2,3,4,dog}, aList2 could contain {10,2,5,2,cat}.
EDIT: The whole code.
import javax.swing.JOptionPane;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
public class KevinMath2 {
static File filename = new File("homework.txt");
static ArrayList <Object> aList = new ArrayList <Object> ();
static String homework = " ";
static File filename2 = new File("homework2.txt");
static ArrayList <Object> aList2 = new ArrayList <Object> ();
static String homework2 = " ";
public static void main(String[] args) {
// TODO Auto-generated method stub
String initialInput = JOptionPane.showInputDialog(null, "Would you like to add answers or check answers?");
String again;
char repeat;
do {
switch (initialInput) {
case "Add answers":
char answerfinal1;
String answerPass = JOptionPane.showInputDialog(null, "Please enter the password");
while (!answerPass.equals("Victor")) {
JOptionPane.showMessageDialog(null, "Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null, "Please enter the password.");
}
do {
do {
String options = JOptionPane.showInputDialog(null, "Enter the date of the desired" +
" answers to add (M/D/Y)");
switch (options) {
case "05/29/15":
while (!homework.isEmpty()) {
homework = JOptionPane.showInputDialog("Please enter the answers, in order. After "
+ "the last answer, leave the next answer"
+ " blank, and click OK.");
if (!homework.isEmpty()) aList.add(homework);
}
try {
FileWriter fw = new FileWriter (filename);
Writer output = new BufferedWriter (fw);
int sz = aList.size();
for (int i=0; i < sz; i++) {
output.write(aList.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Oops! I cannot create that file.");
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
break;
}
} while (!homework.isEmpty());
String final1 = JOptionPane.showInputDialog(null, "Is this correct: " + aList.get(0) + " "
+ aList.get(1) + " " + aList.get(2) + " " +
aList.get(3) + " " + aList.get(4) + "? (Yes or No)");
answerfinal1 = final1.charAt(0);
} while (answerfinal1 == 'n' || answerfinal1 == 'N');
break;
//Need to store the array permanently
case "Check answers": //Need to make it so it stores array of Kevin's answers permanently
char answerfinal2;
String checkPass = JOptionPane.showInputDialog(null, "Please enter the password");
while (!checkPass.equals("Kevin")) {
JOptionPane.showMessageDialog(null, "Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null, "Please enter the password.");
}
do {
do {
String options2 = JOptionPane.showInputDialog(null, "Enter the date of the desired" +
" answers to check (M/D/Y)");
switch (options2) {
case "05/29/15":
while (!homework2.isEmpty()) {
homework2 = JOptionPane.showInputDialog("Please enter the answers, in order. After "
+ "the last answer, leave the next answer" +
" blank, and click OK.");
if (!homework2.isEmpty()) aList2.add(homework2);
}
try {
FileWriter fw = new FileWriter (filename2);
Writer output = new BufferedWriter (fw);
int sz = aList2.size();
for (int i=0; i < sz; i++) {
output.write(aList2.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Oops! I cannot create that file.");
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
}
} while (!homework2.isEmpty());
String final2 = JOptionPane.showInputDialog(null, "Is this correct: " + aList2.get(0) + " "
+ aList2.get(1) + " " + aList2.get(2) + " " +
aList2.get(3) + " " + aList2.get(4) + "? (Yes or No)");
answerfinal2 = final2.charAt(0);
} while (answerfinal2 == 'n' || answerfinal2 == 'N');
int i = 0; // counter variable
if (aList.size() == aList2.size()) { // Check if both lists are equal
for (Object obj : aList) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a string
if (!aList.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i + " is wrong.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (!aList.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i + " is wrong.");
}
}
i++;
}
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
break;
}
again = JOptionPane.showInputDialog(null, "Would you like to check another answer, or "+
"add another answer? (Yes or No)");
repeat = again.charAt(0);
} while (repeat == 'y' || repeat == 'Y');
JOptionPane.showMessageDialog(null, "Thanks for using this program");
}
}
Try using a for loop to iterate through the first ArrayList and use the counter ('i' in the example below) from that for loop to compare each of the indices that you loop through using the get method provided by ArrayList.
for (int i = 0; i < aList1.size(); i++) {
if (!aList1.get(i).equals(aList2.get(i)))
//output whatever you want it to say
}
Edit: changed to .equals instead of == as suggestion. Good catch.
Compare their datatypes of both the elements of your list if they match then try to compare their contents
For comparing the datatype follow the below mentioned code
int a = 10;
Object o = a;
System.out.println(o.getClass().getSimpleName());
If the datatype matches then try to compare their contents
I agree with coal175s answer but since you say you are mixing types in your arrayLists, you should your the .equals() method to compare them.
if !(aList1.get(i).equals(aList2.get(i))) {
Two things to consider:
Do both ArrayList have the same size
When you're checking elements, must they be the same data type, or can we cast everything to a String and then compare. I will assume they must be the same data type.
Having said that:
public static void main(String[] args) throws Exception {
List<Object> list1 = new ArrayList<>(Arrays.asList(1234, 123.45, "999", 444.444, 999.999));
List<Object> list2 = new ArrayList<>(Arrays.asList("1234", 123.45, "9991", 444.444));
for (int i = 0; i < list1.size(); i++) {
// Only check against parallel list if the index is in the bounds
if (i < list2.size()) {
// Check if the data types match
if (!list1.get(i).getClass().getName().equals(list2.get(i).getClass().getName())) {
System.out.println(String.format("%s: %s != %s: %s",
list1.get(i).getClass().getName(), list1.get(i),
list2.get(i).getClass().getName(), list2.get(i)));
}
// Check if the values match if the datatypes match
else if (!list1.get(i).equals(list2.get(i))) {
System.out.println(String.format("%s != %s", list1.get(i), list2.get(i)));
}
}
}
}
Results (999.999 from list1 does not get checked):
java.lang.Integer: 1234 != java.lang.String: 1234
999 != 9991
You should initialise your List object with Object generics i.e. List<Object> list = new ArrayList<>(); so you can add both String and Double in your list.
Here is an ideal solution to compare two arrays.
List<Object> aList1 = new ArrayList<Object>();
List<Object> aList2 = new ArrayList<Object>();
aList1.add("abc");
aList1.add(25);
aList2.add("abc");
aList2.add(25);
int i = 0; // counter variable
if (aList1.size() == aList2.size()) { // Check if both lists are equal
for (Object obj : aList1) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a string
if (aList1.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, (i+1) + " is correct.");
} else {
JOptionPane.showMessageDialog(null, (i+1) + " is incorrect.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (aList1.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, (i+1) + " is correct.");
} else {
JOptionPane.showMessageDialog(null, (i+1) + " is incorrect.");
}
}
if (obj.getClass() == Integer.class) {
JOptionPane.showMessageDialog(null, "Integer is found");
}
i++;
}
}
Your code is very hard to follow, when you write a program please try to follow Java conventions.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class KevinMath2 {
static File filename = new File("homework.txt");
static ArrayList<Object> aList = new ArrayList<Object>();
static String homework = "";
static File filename2 = new File("homework2.txt");
static ArrayList<Object> aList2 = new ArrayList<Object>();
static String homework2 = "";
static String answerPass = "";
static final int TOTAL_QUESTIONS = 5;
public static void main(String[] args) {
String initialInput = JOptionPane.showInputDialog(null,
"Enter Add answers / Check answers to continue");
switch (initialInput) {
case "Add answers":
answers("Victor", aList, filename);
int choice = JOptionPane.showConfirmDialog(null,
"Would you like to compare your answers?", "Yes/No", JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
answers("Kevin", aList2, filename2);
checkAnswers(aList, aList2);
}
break;
// Need to store the array permanently
case "Check answers": // Need to make it so it stores array of
// Kevin's answers permanently
answers("Kevin", aList2, filename2);
if (aList.size() == 0) {
JOptionPane.showMessageDialog(null,
"Please add answers to compare.");
answers("Victor", aList, filename);
}
checkAnswers(aList, aList2);
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
break;
}
// exit the program
JOptionPane.showMessageDialog(null, "Thanks for using this program");
}
public static void answers(String pass, ArrayList<Object> list, File f) {
answerPass = JOptionPane.showInputDialog(null,
"Please enter the password");
// validate user
while (!answerPass.equals(pass)) {
JOptionPane.showMessageDialog(null,
"Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null,
"Please enter the password.");
}
// add answers
String final1 = "";
do {
clearFile(f);
list.clear();
// validate the date of the answers
String options = JOptionPane.showInputDialog(null,
"Enter the date of the desired" + " answers (MM/DD/YY)");
// add your answers
enterAnswers(options, list, f);
// verify the answers
final1 = JOptionPane.showInputDialog(null, "Is this correct: "
+ list.get(0) + " " + list.get(1) + " " + list.get(2) + " "
+ list.get(3) + " " + list.get(4) + "? (Y/N)");
} while (final1.charAt(0) == 'n' || final1.charAt(0) == 'N');
}
public static void enterAnswers(String options, ArrayList<Object> list,
File f) {
switch (options) {
case "05/29/15":
boolean valid = false;
for (int i = 0; i < 5; i++) {
while (!valid) {
homework = JOptionPane
.showInputDialog("Please enter your answer for question "
+ (i + 1));
if (!homework.isEmpty())
valid = true;
}
list.add(homework);
valid = false;
}
writeFile(f, list); // write the answers to a file
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
}
}
public static void writeFile(File filename, ArrayList<Object> list) {
try {
FileWriter fw = new FileWriter(filename);
Writer output = new BufferedWriter(fw);
for (int j = 0; j < list.size(); j++) {
output.write(list.get(j) + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Oops! I cannot create that file.");
}
}
public static void clearFile(File filename) {
try {
FileWriter fw = new FileWriter(filename);
Writer output = new BufferedWriter(fw);
output.write("");
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Oops! I cannot create that file.");
}
}
public static void checkAnswers(ArrayList<Object> a, ArrayList<Object> b) {
int i = 0; // counter variable
if (a.size() == b.size()) { // Check if both lists are
// equal
for (Object obj : a) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a
// string
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
if (obj.getClass() == Integer.class) { // or an integer
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
i++;
}
}
}
}
Answer is based on the assumption
Add answers to an ArrayList.
Compare your answers from another ArrayList.
You aren't comparing your answers from the written files.
You are writing your 'Added answers' to a file, but you aren't reading that file back again to compare against your 'Check answers'. To do that, write another method to read in the homework.txt file, store each line to your aList, then compare against aList2.

String sentinel on integer input Java

I already posted the question about my example, it was different problem. I came up to another problem. When i choose option 3(multiply) i get result to be zero. And if i choose option 4, cannot divide by zero(zero is my sentinel). How can i make sentinel to be string or char when i use int to input numbers to be calculated? Here is the code.
import java.util.Scanner;
public class SwitchLoopNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numbers = 0;
int result = 0;
int option;
boolean quit = true;
String done = "";
do {
System.out.println("CALCULATOR MENU");
System.out.println("********** ****");
System.out.println("\n1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
while (quit) {
switch (option) {
case 1:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result += numbers;
break;
case 2:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result = numbers - result;
break;
case 3:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result *= numbers;
break;
case 4:
System.out.print("Enter a number, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = false;
}
result = result / numbers;
break;
}
}
System.out.println("The total is: " + result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
numbers = 0;
result = 0;
quit = true;
} while ("y".equalsIgnoreCase(done));
System.out.println("Thank you for using calculator");
}
}
Your main problem was that you have initialized result to zero, and it's a good approach for addition and subtraction, but when it comes to multiplication it is not going to work. So, as a solution for that problem you have to set the variable as an Integer, so you can change it as you want inside the loop depending on what operation you are trying to do. Also, it's better because the class Integer allows you to assign its variable to null, which can be so handy in this kind of situations(e.g. better than using 0). Another problem you had was the way you declared an end of your current operation and get the result back. You used 0 as a way of stoping your loop, however, 0 can be used as a number within your calculation. Therefore, you should scan the input as a string then if the user entered = sign, the loop ends and it gives back the result. Then, you can also use the feature that is given to us by the Integer class which allows us to parse integer from a string and use them as regular numbers. Along with that, you had some syntax "errors" and declarations that you could've come with a better way of writing it.
In overall, if you wanted to make a real calculator, this is absolutely not the best approach to do it, because you may face many mathematical problems and exceptions, but its not very bad as a start.
This fix most of your problems:
import java.util.Scanner;
public class SwitchLoopNumbers {
public static void main(String[] args) {
String number;
String process = "";
Integer result = null;
int option = 0;
boolean startOver = true;
while (true) {
Scanner scan = new Scanner(System.in);
if (startOver) {
System.out.print("CALCULATOR MENU" + "\n"
+ "****************" + "\n"
+ "1. Add" + "\n"
+ "2. Substract" + "\n"
+ "3. Multiply" + "\n"
+ "4. Divide" + "\n"
+ "****************" + "\n"
+ "Enter your option >> ");
option = scan.nextInt();
}
switch (option) {
case 1:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ + \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " + ";
option = 1;
startOver = false;
continue;
} else {
result = result + Integer.parseInt(number);
process += number + " + ";
option = 1;
startOver = false;
continue;
}
case 2:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[- \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " - ";
option = 2;
startOver = false;
continue;
} else {
result = result - Integer.parseInt(number);
process += number + " - ";
option = 2;
startOver = false;
continue;
}
case 3:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ * \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " * ";
option = 3;
startOver = false;
continue;
} else {
result = result * Integer.parseInt(number);
process += number + " * ";
option = 3;
startOver = false;
continue;
}
case 4:
System.out.print("Enter a number, or '=' to get the result >> ");
number = scan.next();
if ("=".equals(number)) {
process = process.replaceFirst("[ / \t]+$", " = ");
break;
} else if (result == null) {
result = Integer.parseInt(number);
process += number + " / ";
option = 4;
startOver = false;
continue;
} else {
result = result / Integer.parseInt(number);
process += number + " / ";
option = 4;
startOver = false;
continue;
}
}
System.out.println("The result of " + process.replace("+ 0 ", "") + result);
System.out.print("Back to main menu? [y/n]: ");
if (scan.next().equalsIgnoreCase("y")) {
process = "";
result = null;
startOver = true;
} else if (scan.next().equalsIgnoreCase("n")) {
System.out.println("Thank you for using calculator.");
break;
} else {
System.out.println("Wrong input!");
break;
}
}
}
}

Categories

Resources