Validating the amount of command line arguments - java

I am trying to validate that there are only three arguments passed. In this program I am looking to pass two integers using command line arguments that look like 23 23 +. But I want an error to display if they enter less than three arguments or more than three arguments. As is right now, it gives the error message when there is more than three arguments but not less than three. Any help would be great please.
public class Arithmetic {
public static void main(String[] args) {
// setting up the variable firstNumber and secondNumber
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
String arithmetic = args[2];
int length = args.length;
if(length != 3){
System.out.println("Your suppose to enter an int, int then an operation sign like +,-,X or /.");
return;
}
if (arithmetic.equals("+")) {
int addition = firstNumber + secondNumber;
System.out.println(args[0]+ " " + args[2] + " " + args[1] + " = " + addition);
int total = String.valueOf(addition).length();
System.out.println(addition + " has the length of " + total);
} else if (arithmetic.equals("-")) {
int minus = firstNumber - secondNumber;
System.out.println(args[0]+ " " + args[2] + " " + args[1]+ " = " + minus);
int total = String.valueOf(minus).length();
System.out.println(minus + " has the length of " + total);
} else if (arithmetic.equals("/")) {
int division = firstNumber / secondNumber;
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + division);
int total = String.valueOf(division).length();
System.out.println(division + " has the length of " + total);
} else if (arithmetic.equals("x")) {
int multiply = firstNumber * secondNumber;
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + multiply);
int total = String.valueOf(multiply).length();
System.out.println(multiply + " has the length of " + total);
}
//following prints out to the console what the length of each argument is.
System.out.println(args[0] + " has the length of " + args[0].length());
System.out.println(args[1] + " has the length of " + args[1].length());
System.out.println("The arguments that was passed would have been " + args[0]+ " " + args[1] + " " + args[2]);
}
}

You have code lines that assume that there are at least 3 arguments before you check how many arguments there are. Move these lines:
// setting up the variable firstNumber and secondNumber
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
String arithmetic = args[2];
below your "!= 3" check. Otherwise if you enter less than 3 command line arguments, you'll get an ArrayIndexOutOfBoundsException on one of those lines before you check how many arguments you have.

Related

Java error handling for project- Line matched except underscores: Invalid Event Code_?

I completed this java project for a class, but I cannot seem to fix the error I'm getting for the web software that grades it- it's called webcat. I've tried the test input the software suggests for a reference test against my solution, and my output looks exactly the same, but I still lost points for this error-
"Error in method main of class Event: Line number 2 of your output is incorrect (line numbers begin at 1). Your main method does not print the correct output when the input is "This is a short test " (input less than 26 characters) [] Line matched except underscores: Invalid Event Code_".
How can I fix this error when the expected ouput looks fine? Thanks in advance!
Code:
public class Event {
/**
* accepts coded event info, prints the info back to std output, and
actual cost and prize number.
*
* #param args Command line arguments - not used.
*/
public static void main(String[] args) {
// variables needed
String shrink, event, date, time, section, row, seat;
double price, discount, cost;
int prizeNum;
// accept input
Scanner userInput = new Scanner(System.in);
// format the numbers
DecimalFormat formatNum = new DecimalFormat("$#,##0.00");
// enter input and trim the space
System.out.print("Enter your event code: ");
shrink = userInput.nextLine().trim();
if (shrink.length() < 26) {
System.out.println();
System.out.println("Invalid Event Code");
System.out.println("Event code must have at least 26 characters.");
return;
}
// locates spot in index of code and assigns
event = shrink.substring(25, shrink.length());
date = shrink.substring(0, 8);
time = shrink.substring(8, 12);
section = shrink.substring(19, 21);
row = shrink.substring(21, 23);
seat = shrink.substring(23, 25);
price = Double.parseDouble(shrink.substring(12, 15)
+ "." + shrink.substring(15, 17));
discount = Double.parseDouble(shrink.substring(17, 19));
// calculates final cost
cost = price - (price * (discount / 100));
// random final number
prizeNum = (int) (Math.random() * 1000 + 1);
// prints the data to std output
System.out.println();
System.out.print("Event: " + event + " " + " " + " ");
System.out.print("Date: " + date.substring(0, 2) + "/"
+ date.substring(2, 4) + "/" + date.substring(4, 8) + " "
+ " " + " ");
System.out.println("Time: " + time.substring(0, 2) + ":"
+ time.substring(2, 4) + " " + " " + " ");
System.out.print("Section: " + section + " " + " " + " ");
System.out.print("Row: " + row + " " + " " + " ");
System.out.println("Seat: " + seat);
System.out.print("Price: " + formatNum.format(price) + " " + " " + " ");
// formats discount before print
formatNum.applyPattern("#.#'%'");
System.out.print("Discount: " + formatNum.format(discount) + " "
+ " " + " ");
// formats cost before print
formatNum.applyPattern("$#,##0.00");
System.out.println("Cost: " + formatNum.format(cost));
System.out.print("Prize Number: " + prizeNum);
Output:
Enter your event code: This is a short test
Invalid Event Code
Event code must have at least 26 characters.

After asking the user for how many questions they want, how can I get my code to show that number of random problems?

I need to first ask the user to input how many problems they want to do. Then generate the first, then the second after they answer the first and so on.
public static void main(String[] args) {
int number1 = (int) (Math.random() * 40 + 10), number2 = (int) (Math.random() * 40 + 10), uanswer, ianswer, counter, icounter,
acounter, counter1, ui, aacounter, bcounter;
Scanner input = new Scanner(System.in);
System.out.println("How many problems do you want to do?");
ui = input.nextInt();
counter = 1;
icounter = 1;
acounter = counter + icounter;
{
System.out.print("What is " + number1 + " + " + number2 + "? ");
}
uanswer = input.nextInt();
ianswer = number1 + number2;
while (counter < 10000 && icounter < 1000 && acounter < 1000 && number1
+ number2 != uanswer) {
System.out.println("Incorrect, the answer is "
+ ianswer + ", " + icounter + " out of " + icounter + " incorrect. Try again?");
icounter++;
acounter++;
uanswer = input.nextInt();
}
if (ianswer == ianswer) {
aacounter = acounter - 1;
bcounter = icounter - 1;
System.out.println("Correct, the answer is " + ianswer
+ ", " + counter + " out of " + aacounter + " correct, "
+ bcounter + " out of " + aacounter + " incorrect.");
}
}
With my current code, I only see one problem, even though I asked for 2 or more problems at the beginning.
You need to add a loop around this statement:
System.out.print("What is " + number1 + " + " + number2 + "? ");
like:
for(int i=0; i<ui; i++){
System.out.print("What is " + number1 + " + " + number2 + "? ");
...

How to search a token for a specific word in Java?

I have a segment of code that splits a string into tokens and prints them each out on a new line. I am having a hard time writing a code that determines if a word is a reserved word or not. I have to print "Reserved word is: " if the word is a java keyword, otherwise print "Current word is: ". Here is my code so far:
package projectweek3;
/**
*
* Name -
* Email Address -
* Date -
*
*/
public class Week3Project {
final static String program = "/*\n" +
" * To change this license header, choose License Headers in Project Properties.\n" +
" * To change this template file, choose Tools | Templates\n" +
" * and open the template in the editor.\n" +
" */\n" +
"package testapplication2;\n" +
"\n" +
"import java.util.Scanner;\n" +
"\n" +
"/**\n" +
" *\n" +
" * #author james\n" +
" */\n" +
"public class TestApplication2 {\n" +
"\n" +
" /**\n" +
" * #param args the command line arguments\n" +
" */\n" +
" public static void main(String[] args) {\n" +
" Scanner input = new Scanner(System.in);\n" +
" \n" +
" System.out.println(\"Enter integer #1\");\n" +
" int num1 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #2\");\n" +
" int num2 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #3\");\n" +
" int num3 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #4\");\n" +
" int num4 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #5\");\n" +
" int num5 = input.nextInt();\n" +
" \n" +
" //determine the sum\n" +
" int sum = num1 + num2 + num3 + num4 + num5;\n" +
" \n" +
" //this is helpful to make sure your sum is correct\n" +
" System.out.println(\"The sum is: \" + sum);\n" +
" \n" +
" //why doesn't this generate the sum correctly\n" +
" double average = sum / 5;\n" +
" \n" +
" //The average, lets hope its right...\n" +
" System.out.println(\"The average of your numbers is: \" + average);\n" +
" \n" +
" }\n" +
" \n" +
"}\n" +
"";
**public static void main(String[] args)
{
String str = program;
String s = "";
for (int i = 0; i < str.length(); i++) {
s += str.charAt(i) + "";
if (str.charAt(i) == ' ' || str.charAt(i) == '\t' || str.charAt(i) == '\n' || (str.charAt(i) == ' ' && str.charAt(i) == '\n')) {
String currentWord = s.toString();
String res = "int";
if (currentWord.equals(res)) {
System.out.println("Reserved word is: [" + currentWord + "]");
}
else {
System.out.println("Current word is: [" + currentWord + "]");
}
s = "";//Clear the string to get it ready to build next token.
}
}**
I would reconsider the way you're looping through the "program."
Instead of going through character by character, use the Java String.split() function.
String program = "int num1 = input.nextInt();\n";
String[] words = program.split("[\\n\\s\\t]");
for (String word : words) {
System.out.println(word);
}
Output:
int
num1
=
input.nextInt();
EDIT:
Since you can't use String.split(), your looping solution looks good. To check if the current word is reserved, try using Set.contains().
Set<String> reserved = new HashSet<>();
reserved.add("int");
// ...
if reserved.contains(word) {
System.out.println("Reserved word is: " + word);
} else {
System.out.println("Current word is: " + word);
}
That is, assuming you're allowed to use Set.

Storing Statistics in Java Calculator

Having difficulty storing the following statistics to be printed when the program terminates. I have been able to store the total number of valid and invalid expressions however I am having difficulty with the following:
The highest overall result value.
The lowest overall result value.
The aggregate of all result values, i.e. all results added together.
The average result value
Any guidance for any of the above would be much appreciated.
Scanner input = new Scanner(System.in); // Creating new scanner to take user choice input
int validExpressions = 0;
int invalidExpressions = 0;
int lowestval = 0;
int highestval;
while (true) {
System.out.println("Enter K to enter a postfix expression or F to open a text file:"); // requesting user input
String choice = input.nextLine(); // Taking user input from keyboard, either K for manual entry or F for file input
float answer; // Variable used to store answers.
if ("F".equals(choice)) {
System.out.println("Please enter the name of a .txt file:"); // user prompted to enter the name of the text file
String file = input.nextLine(); // File name will be stored in a String (file) to be used later
File txtfile = new File(file);
Scanner reader = new Scanner(txtfile); // Creating a new scanner which reads the text file
while (reader.hasNextLine()) { // The new scanner (reader) reads each line of the text file
String expression = reader.nextLine(); // Each line is stored in a String called Expression
String[] parts = expression.split(" "); // The string is split into three parts; two numbers and an operator
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
float number1 = Float.parseFloat(part1); // Parts one and two are both converted from a String to a Float
float number2 = Float.parseFloat(part2);
// Program processes the operator and applies it to Float number1 and Float number2 before outputting the
// expression and the correct answer
if ("+".equals(part3)) {
answer = number1 + number2;
System.out.println(part1 + " " + "+" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(part3)) {
answer = number1 - number2;
System.out.println(part1 + " " + "-" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(part3)) {
answer = number1 * number2;
System.out.println(part1 + " " + "*" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(part3)) {
answer = number1 / number2;
System.out.println(part1 + " " + "/" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
}
}
} else if ("K".equals(choice)) // If the user enters K input will be taken from the keyboard
System.out.println("Please enter a post-fix expression:"); // User is prompted to enter a post fix expression
Scanner expression = new Scanner(System.in); // Creating a new Scanner called Expression to read user input
String exp = expression.nextLine(); // The user's input is stored in a string
String[] elements = exp.split(" "); // Expression is split into three elements, two numbers and an operator
String element1 = elements[0];
String element2 = elements[1];
String element3 = elements[2];
float num1 = Float.parseFloat(element1); // Element1 and element2 are converted to Floats and named num1 and num2
float num2 = Float.parseFloat(element2);
// Program processes the operator and applies it to Float num1 and Float num2 before outputting the
// expression and the correct answer
if ("+".equals(element3)) {
answer = num1 + num2;
System.out.println(element1 + " " + "+" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(element3)) {
answer = num1 - num2;
System.out.println(element1 + " " + "-" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(element3)) {
answer = num1 * num2;
System.out.println(element1 + " " + "*" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(element3)) {
answer = num1 / num2;
System.out.println(element1 + " " + "/" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
if (choice.isEmpty()) { // If the user does not enter K or F the program will exit
System.out.println("Evaluations Complete");
System.out.println("-------------------------");
System.out.println("Valid expressions: " + validExpressions);
System.out.println("Invalid expressions: " + invalidExpressions);
System.exit(0);
}
}
}
}
}
I have changed something wrong on logic and syntax,but I have not debuged it ,you may have a try.
Scanner input = new Scanner(System.in); // Creating new scanner to take user choice input
int validExpressions = 0;
int invalidExpressions = 0;
float lowestval = 0;
float highestval =0 ;
float total=0;
while (true) {
System.out.println("Enter K to enter a postfix expression or F to open a text file:"); // requesting user input
String choice = input.nextLine(); // Taking user input from keyboard, either K for manual entry or F for file input
float answer; // Variable used to store answers.
if ("F".equals(choice)) {
System.out.println("Please enter the name of a .txt file:"); // user prompted to enter the name of the text file
String file = input.nextLine(); // File name will be stored in a String (file) to be used later
File txtfile = new File(file);
Scanner reader = new Scanner(txtfile); // Creating a new scanner which reads the text file
while (reader.hasNextLine()) { // The new scanner (reader) reads each line of the text file
String expression = reader.nextLine(); // Each line is stored in a String called Expression
String[] parts = expression.split(" "); // The string is split into three parts; two numbers and an operator
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
float number1 = Float.parseFloat(part1); // Parts one and two are both converted from a String to a Float
float number2 = Float.parseFloat(part2);
// Program processes the operator and applies it to Float number1 and Float number2 before outputting the
// expression and the correct answer
if ("+".equals(part3)) {
answer = number1 + number2;
System.out.println(part1 + " " + "+" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(part3)) {
answer = number1 - number2;
System.out.println(part1 + " " + "-" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(part3)) {
answer = number1 * number2;
System.out.println(part1 + " " + "*" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(part3)) {
answer = number1 / number2;
System.out.println(part1 + " " + "/" + " " + part2 + " " + "=" + " " + answer);
validExpressions++;
} else{
invalidExcepressions++;
continue;
}
highestval=(highestval>=answer)?highestval:answer;
lowestval=(lowestval<=answer)?lowestval:answer;
total+=answer;
}
} else if ("K".equals(choice)){ // If the user enters K input will be taken from the keyboard
System.out.println("Please enter a post-fix expression:"); // User is prompted to enter a post fix expression
Scanner expression = new Scanner(System.in); // Creating a new Scanner called Expression to read user input
String exp = expression.nextLine(); // The user's input is stored in a string
String[] elements = exp.split(" "); // Expression is split into three elements, two numbers and an operator
String element1 = elements[0];
String element2 = elements[1];
String element3 = elements[2];
float num1 = Float.parseFloat(element1); // Element1 and element2 are converted to Floats and named num1 and num2
float num2 = Float.parseFloat(element2);
// Program processes the operator and applies it to Float num1 and Float num2 before outputting the
// expression and the correct answer
if ("+".equals(element3)) {
answer = num1 + num2;
System.out.println(element1 + " " + "+" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("-".equals(element3)) {
answer = num1 - num2;
System.out.println(element1 + " " + "-" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("*".equals(element3)) {
answer = num1 * num2;
System.out.println(element1 + " " + "*" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
} else if ("/".equals(element3)) {
answer = num1 / num2;
System.out.println(element1 + " " + "/" + " " + element2 + " " + "=" + " " + answer);
validExpressions++;
}else{
invalidExceotions++;
continue;
}
highestval=(highestval>=answer)?highestval:answer;
lowestval=(lowestval<=answer)?lowestval:answer;
total+=answer;
}else if (choice.isEmpty()) { // If the user does not enter K or F the program will exit
System.out.println("Evaluations Complete");
System.out.println("-------------------------");
System.out.println("Valid expressions: " + validExpressions);
System.out.println("Invalid expressions: " + invalidExpressions);
System.out.println("Total :"+total);
System.out.println("Average :"+total/validExceptions);
System.exit(0);
}
}

Methods/functions in Java

With the given code I was given the directions: Java lets us use Methods/Functions so we can store procedures that we may use more than once, so I would like you to update your code where there is common tasks it can be done inside a method/function. Any idea how to do this?
package fifthAssignment;
public class Arithmetic {
public static void main(String[] args) {
// setting up the variable firstNumber and secondNumber
int length = args.length;
if (length != 3) {
System.out.println("Your suppose to enter an int, int then an operation sign like +,-,X or /.");
return;
}
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
int addition = firstNumber + secondNumber;
int minus = firstNumber - secondNumber;
int division = firstNumber / secondNumber;
int multiply = firstNumber * secondNumber;
String arithmetic = args[2];
if (arithmetic.equals("+")) {
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + addition);
} else if (arithmetic.equals("-")) {
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + minus);
} else if (arithmetic.equals("/")) {
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + division);
// I could not use "*" operator as it was looking to pull down all
// the files associated with this program instead of
// using it the way I intended to use it. So in this case I changed
// the "*" to "x" so that I can get the solution you
// were looking for.
} else if (arithmetic.equals("x")) {
System.out.println(args[0] + " " + args[2] + " " + args[1] + " = " + multiply);
}
// following prints out to the console what the length of each argument
// is.
System.out.println(args[0] + " has the length of " + args[0].length());
System.out.println(args[1] + " has the length of " + args[1].length());
if (arithmetic.equals("+")) {
int total = String.valueOf(addition).length();
System.out.println(addition + " has the length of " + total);
}else if (arithmetic.equals("-")) {
int total = String.valueOf(minus).length();
System.out.println(minus + " has the length of " + total);
}else if (arithmetic.equals("/")) {
int total = String.valueOf(division).length();
System.out.println(division + " has the length of " + total);
} else if (arithmetic.equals("x")) {
int total = String.valueOf(multiply).length();
System.out.println(multiply + " has the length of " + total);
}
}
}
I'll provide a singular example, but you should do this on your own.
You have this in your code:
System.out.println(addition + " has the length of " + total);
Instead, you could potentially create a method that would work with two ints:
public void printStatus(int check, int length) {
System.out.println(check + " has the length of " + length);
}
Which would allow you to call
printStatus(addition, total);
This is just a rough example, but you can wrap a "process" of code in a method, and pass the necessary parameters needed to execute the method to it.
package fifthAssignment;
public class Arithmetic {
public static void main(String[] args) {
// setting up the variable firstNumber and secondNumber
int length = args.length;
if (length != 3) {
System.out.println("Your suppose to enter an int, int then an operation sign like +,-,X or /.");
return;
}
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[1]);
int addition = firstNumber + secondNumber;
int minus = firstNumber - secondNumber;
int division = firstNumber / secondNumber;
int multiply = firstNumber * secondNumber;
String arithmetic = args[2];
// following prints out to the console what the length of each argument
// is.
System.out.println(args[0] + " has the length of " + args[0].length());
System.out.println(args[1] + " has the length of " + args[1].length());
performOperation(arithmetic);
}
public void performOperation(String arithmetic) {
if (arithmetic.equals("+")) {
int total = String.valueOf(addition).length();
System.out.println(addition + " has the length of " + total);
} else if (arithmetic.equals("-")) {
int total = String.valueOf(minus).length();
System.out.println(minus + " has the length of " + total);
} else if (arithmetic.equals("/")) {
int total = String.valueOf(division).length();
System.out.println(division + " has the length of " + total);
} else if (arithmetic.equals("x")) {
int total = String.valueOf(multiply).length();
System.out.println(multiply + " has the length of " + total);
}
}
}

Categories

Resources