JAVA Command line arguments to get info - java

I just have a small question which i cant understand , i hope i can get some help please .
I Want to write a program that get the info into my program using the command line, example (java xx 10 20). In my program i got something like this
int coffeeCups= Integer.parseInt(args[0]);
int coffeeShots= Integer.parseInt(args[1]);
if (args.length==0)
{
System.out.print ("No arguments..");
System.exit(0);
}
else if (args.length==1)
{System.out.println("not enough arg..");
System.exit(0);
}
else if (args.length>2)
{System.out.println("too many arg.");
System.exit(0);
}
else if (Integer.parseInt(args[0]<0) && Integer.oarseInt(args[1]<0)
{system.out.println("negative chain arg");
System.exit(0); }
else if (Integer.parseInt(args[0]<0) || Integer.oarseInt(args[1]<0)
{system.out.println("negative arg");
System.exit(0);}
I Want to enter only TWO POSITIVE INTEGERS INTO MY COMMAND LINE.. otherwise it should reject my inputs, but the thing is that sometime i came with en error like that (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0) and sometimes my program runs without even entering any two integers in the COMMAND LINE...
I gotta finish my code as soon as possible, and i'de appreciate ur help
P.S. dont worry about the my identation as my program is not done yet

First of all, you may want to use a command-line-arguments parsing facility.
You're trying to access indices that do not exist:
// who said there is a first argument?
int coffeeCups = Integer.parseInt(args[0]);
// who said there is a second argument?
int coffeeShots = Integer.parseInt(args[1]);
You need to first check, then access:
// this is just like using sentinel value. If you're not familiar with
// shortend `if` see notes.
int coffeeCups = args.length > 1 ? Integer.parseInt(args[0]) : null;
int coffeeShots = args.length > 2 ? Integer.parseInt(args[1]) : null;
if (coffeeCups == null || coffeeShots == null){
throw new Exception("Not enough arguments");
}
if (args.length > 2){
throw new Exception("Too many arguments");
}
There is also the case in which the arguments are not Integers. You will get a NumberFormatException if that's the case...
Notes:
Short if notation (x ? y : z) is used to return y in case x is true, otherwise it returns z.

Related

Trying to Make an Average Finder, Not Using ReadLine(), using Only Console

New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;

Trouble with nested if-else statements

I am having problems with nesting some if-else statements, at least that is what I think the problem is. I have butchered this code several times trying to figure it out, so I decided to put it back to the original state and ask for some help. A user is asked to input an odd number between 3 and 15. I need to validate that input and if it is not between 3 and 15, output an error message. Same goes if it is not an odd number, it needs to output a different number. When running the code below, if I enter an even number, letter, or number <3 or >15 I get both error messages. If the input is an odd number between 3 and 15, it works fine. I know I have to differentiate between the two errors, just have not been able figure out how to do it and make the code run/work properly. Have also tried else if with no luck. Sure it is something silly, since most of my mistakes seem to be on the silly side. Thanks for your help!
public static void main(String[] args) {
// Declare variables
String inputString;
boolean done = false;
int numRows = 0;
// Prompt for user input
do
{
inputString = JOptionPane
.showInputDialog("Enter number of rows (odd number between 3 and 15): ");
// Validating input
try
{
numRows = Integer.parseInt(inputString);
}
catch (NumberFormatException e)
{
done = true;
}
if(numRows % 2 == 0) // Validating input is an odd number
done = true;
if((numRows < 3) || (numRows > 15))// Validating input is between 3 and 15
done = true;
else
done = false;
if(done)
JOptionPane.showMessageDialog(null, "Error, not an ODD number. Re-enter odd number between 3 and 15",
"Error", JOptionPane.ERROR_MESSAGE);
if(done)
JOptionPane.showMessageDialog(null, "Error, number not between 3 and 15. Re-enter odd number between 3 and 15",
"Error", JOptionPane.ERROR_MESSAGE);
}
while(done);
}
The interesting thing here is, you don't need the if statements. You can greatly simplify (and fix) your boolean expressions.
First, let's establish the behavior of (numRows < 3) || (numRows > 15). For this to be true, either numRows has to be strictly less than 3, or strictly greater than 15. This does not validate a range of numbers - you need to switch this to an AND statement. But even just doing that doesn't validate the correct range - you'll be validating everything that isn't between 3 and 15!
To fix that, you need to flip your inequalities.
You now have (numRows >= 3) && (numRows <= 15). For this to be true, numRows must be between the bounds of 3 and 15, inclusive.
Now, let's combine that with the check for odd/even, and you arrive at this:
done = (numRows % 2 == 0) || ((numRows >= 3) && (numRows <= 15));
The behavior of this statement is as such:
Either numRows is an even number, OR
numRows is bound between 3 and 15, inclusive.
I've also got some thoughts on you combining your JOptionPane statements as well, but that's more of a presentation issue than a code issue - I'll leave that as an exercise for the reader.

Search for accounts using for loops and if statements

I'm having a problem with my program. Currently, I'm making a billing account system.
Basically, I've got a great deal of the system up and running. As a feature, rather than having a user remember their position in an array, a user could carry out actions for their account by entering their account number. So, in other words, they would be prompted to enter an account number and any actions are attributed to that account.
Here is the code I have so far:
intEntry = input.nextInt();
for (count = 0; count <= ACCLIMIT; count++)
{
if (intEntry == NewAccount[count].getAccRefNo() )
{
intSelectedEntry = count;
}//end of if statement
else
{
System.out.println("Invalid ID!");
}//end of else statement
}//end of loop
System.out.println("*******Please enter the amount you wish to deposit*******") ;
valDeposit = getBalanceValidation();
parDepositAmount = Double.valueOf(valDeposit).doubleValue ();
NewAccount[intSelectedEntry].deposit(parDepositAmount);
When I run it, it crashes once I enter the ID number intEntry. It says the error is in the line of the if statement criteria, if that helps.
Please be aware I'm really new to Java, and I'd really appreciate this help explained in a simple way. (Thanks!)
Here is the error message:
Exception in thread "main" java.lang.NullPointerException
at pkgGasAccount.UsingBusinessAccount.main(UsingBusinessAccount.java:106)
Java Result: 1
Line 106 is the first line of the if statement (the criteria)
NewAccount[count] is null.
You should check that NewAccount[count] != null:
if (NewAccount[count]!= null && intEntry == NewAccount[count].getAccRefNo() )
But if you don't expect null values there, I suggest you to check why this happens.
NullPointerException is being thrown, hence I can say that your code is trying to access an array that is not defined or either pointing to a null value (default)
Since there is just one array NewAccount[], hence I would check the declaration of the same.

Java conditional statement/ initializing variable

Currently this is my code, and I need to display " Please enter a valid choice" when the user don't pick A,B,C,D,E or F as their choices. The problem is if I put the statement " Please enter a valid...." on the "else" conditional, Java would ask me to initialized the variable ActivityFactor as there will not be one if the user don't select the correct choice. Anyone know how I can fix this? Or any idea how I should code a program to do such?
if((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("A"))
ActivityFactor = 1.0;
else if ((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("B"))
ActivityFactor = 1.3;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("C"))
ActivityFactor = 1.6;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("C"))
ActivityFactor = 1.5;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("D"))
ActivityFactor = 1.7;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("D"))
ActivityFactor = 1.6;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("E"))
ActivityFactor = 2.1;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("E"))
ActivityFactor = 1.9;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("F"))
ActivityFactor = 2.4;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("F"))
ActivityFactor = 2.2;
else
{
ActivityFactor = -1;
}
//After
if(ActivityFactor != -1){
tdee = (nBMR * ActivityFactor);
System.out.println(tdee);}
else
{ System.out.println("Please enter a valid choice");
}
If non of the conditions in the if statements is true, then you don't assign anything to ActivityFactor, and it is not initialized when used in the line double TDEE = (nBMR * ActivityFactor);.
Either initialize it before the code you've shown here, give it a default value in the last case, or loop until you get a valid value.
initialise ActivityFactor to an usual value before your conditional.
For example you may do this:
// knowing that it can never be -1
// so if that value remains, you know that user entered wrong letter
ActivityFactor = -1
// then the conditional begins
if((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("A"))
...
// after conditional...
if(activityFactor != -1){
double TDEE = (nBMR * ActivityFactor);
}
By the way, I suggest you use 'activityFactor' instead of ActivityFactor.
Either initialize your variable before the loop, or place the whole loop inside a function and then do something like:
double TDEE = (nBMR * getActivityFactor());
Also, have a look at this : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
happy coding! ;)
You should do two things:
Enclose the logic in method
Throw an exception if argument do not match the method logic.
You can solve this problem throwing an exception that you will catch.
private double getTDEE (String inGender, String inActivity) {
//logic
else {
throw new IllegalArgumentException("Please enter a valid choice");
}
return (nBMR * ActivityFactor);
}
Exception tutorial
As you're already aware, the problem with your code is that execution continues regardless of whether the user has entered valid input. Due to this, much refactoring is due - I would also attempt to make the conditional statements a little bit prettier; but that's personal preference.
Possible solutions:
a) Use a loop - Then break out of the loop when the user has entered satisfactory input..
while( true ){
/* get input from the user */
/* run through validation checks...
and -break- out of the loop when they're satisfied */
}
/* do calculations here */
b) Use a function to abstract all this logic away.. (as Psyclops suggests)
Personally, I would use a combination of these approaches - have all of this logic extracted away in to a function which returns false when no valid input is entered, and then use a construct like while(! yourFunction() ) to simply loop through it until it's completed. You could using passing by reference to avoid having to use the return type for anything other than a boolean value.
I wouldnt initialise the variable before the loop! This just means the programme will continue to execute; however it wont have any appropriate data in there - which is potentially worse than the application just crashing.
I haven't exactly gifted you the answer in code - but hopefully it's a starting point to allow you to think about how to conceptually compose/design such a solution. That's generally the hardest part.. ;) Good luck.

Python Program converted into Java

Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time.
Could someone please help with what I've done and umm give me some advice? Maybe a good site for a beginner.... Someone that kinda knows Python (only from a first CS course perspective).
1) In python
def winCraps():
roll = rollDice()
if roll == 7 or roll == 11:
return True
elif roll == 2 or roll == 3 or roll == 12:
return False
else:
return rollForPoint(roll)
This is my attempt at the conversion of it over to java
public int winCraps{
roll = rollDice();
if (roll = 7 && 11){
return (true);
}
else (roll =2 && 3 && 12){
return(false);
}
else{
return rollforPoint(roll);
}
}
2) Python
def rollDice():
raw_input("Press <Enter> to roll...")
die1 = randrange(1,7)
die2 = randrange(1,7)
sum = die1 + die2
print "You rolled", die1, "+", die2, "=", sum
return sum
This one confused the hell out of me. What would randrange be in Java??
Java
static int rollDice(){
System.out.print("Press <Enter> to roll...");
double die1 = Math.random();
double die2 = Math.random();
die1 = (int) die1*6+1;
die2 = (int) die2*6+1;
int sum = (int)die1 + (int)die2;
System.out.println("You rolled "+die1+ " + "+die2+ " = "+sum+".");
return sum;
}
*please bear in mind that I'm just learning this stuff lol
You need to fix your if statements the "==" operator checks for equality, and you must put the variable you are checking against in each section of the statement.
public int winCraps{
roll = rollDice();
if (roll == 7 || roll == 11) {
return true;
}
else if(roll == 2 || roll == 3 || roll == 12) {
return false;
}
else{
return rollforPoint(roll);
}
}
In you rollDice() method, the way you assign values to each die is incorrect. I recommend reading up on random numbers (since this is homework, I'll leave that to you).
Also, remember in java you must always end each statement with a semicolon
What would randrange be in Java?
You can get a random integer in a specific range from Java's Random class by calling the nextInt(int n) method. For example,
Random rand = new Random();
int a = rand.nextInt(7);
will give you a random integer >= 0 and < 7. This isn't exactly the same as randrange in Python, but you could use it as the index to an array of objects, or as the value of a roll of a single die.
Randrange can be replaced by methods in java.util.Random. Like Python, Java has an extensive standard library which you should reference.
1) In Java "OR" operator is "||" not "&&" and comparison operator is "==" as in Python
So
if roll == 7 or roll == 11:
Should be
if( roll == 7 || roll == 11 ) {
and not
if( roll = 7 && 11 ){
2) randrange is : random generator from there you can search: Random in Java
Which will lead you to something like: Random.nextInt()
Use this algorithm ( a) search Internet for Python function, b) understand what it does c) search it in java ) for the next assignment you have and you're done.
You can always ask here again, that's what this site is all about after all
I'd recommend that you look up the docs on randrange(). Once you know exactly what it does, google for the those keywords, plus the word Java.
One thing you'll quickly discover in working with languages is that the APIs can be very different. There might not be an equivalent of randrange in Java, but you might be able to find two or three functions that you can combine to do the same thing.
System.out.print isn't going to cause the system to wait for someone to hit the enter key. For that, you need to do something with System.in, most likely System.in.read(), as it blocks while waiting for input.
Also, in Java, a program starts executing with the main method. To be exact, an executable class starts something like this:
// You'll need the Random class, as per other answers
import java.util.Random;
// assuming WinCraps is the class name
public class WinCraps {
// args in this example is a string array of command-line arguments
public static void main(String[] args) {
// This is where your main method (that calls winCraps?) would be
}
// Other methods
}
Also, any method in this class called directly from main must also be static.
Write out in English what the Python program does. Go through it line by line and explain to yourself what computations are evoked, in other words...what is happening?
Afterwards, write the Java program from that description.
Never ever try to convert the text of a program from one language to another. You'll run into a LOT of problems that way because every language is different, no matter how similar they look.
One major error in your first program that you have in the Java conversion is the conditionals.
Something like (roll =2 && 3 && 12) assigns 2 to roll and then applies AND operators. You also forgot the if. You have elseif in Python.
You want something like:
else if(roll==2 || roll==3 || roll==12)
As for random numbers, there is a function for that in Java.

Categories