Trouble With Java Program using parameters and methods [closed] - methods

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am stuck here with one programming code: Here are the instructions: http://my.fit.edu/~akhademzadeh2011/courses/cse1001/f2012/ass/ass04.pdf
And, this is my code:
import java.util.*;
public class PantherSolver {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String input;
String p = "0| |";
int signcontrol = 1;
input = GUI(p);
int firstnumber = inputmethod(input);
int firstsign = sign(input,signcontrol);
String secondp = p1(firstsign,firstnumber,p);
String input2 = GUI(secondp);
}
public static String p1(int firstsign,int firstnumber, String p) {
if (firstsign>0) {
p = "0| "+ firstnumber +" |";
}
else {
p = "0| -"+ firstnumber +" |";
}
return p;
}
public static String GUI1(String secondp) {
Scanner kb = new Scanner(System.in);
String newinput = kb.nextLine();
System.out.println(" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
System.out.println(" ========================================");
System.out.println(secondp);
System.out.println("1|--------------------------------------|");
System.out.println("2| OFF +/- AC |");
System.out.println("3| 1 2 3 4 5 , |");
System.out.println("4| 6 7 8 9 0 SOLVE |");
System.out.println(" ========================================");
System.out.println(" Key: " + newinput +"");
return newinput;
}
public static String GUI(String p) {
Scanner kb = new Scanner(System.in);
System.out.println(" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
System.out.println(" ========================================");
System.out.println(p);
System.out.println("1|--------------------------------------|");
System.out.println("2| OFF +/- AC |");
System.out.println("3| 1 2 3 4 5 , |");
System.out.println("4| 6 7 8 9 0 SOLVE |");
System.out.println(" ========================================");
String input1=kb.nextLine();
System.out.println(" Key: " + input1 +"");
return input1;
}
public static int inputmethod(String input) {
Scanner kb = new Scanner(System.in);
int a = 0;
if (input.length()==2) {
if((input.charAt(0)=='0')||(input.charAt(0)=='1')) {
;
}
else if((input.charAt(0)=='2') && !((input.charAt(1)==('0'))||(input.charAt(1)==('1'))||(input.charAt(1)==('2'))||(input.charAt(1)==('S'))||(input.charAt(1)==('T'))||(input.charAt(1)==('U'))||(input.charAt(1)==('V'))||(input.charAt(1)==('W'))||(input.charAt(1)==('X'))||(input.charAt(1)==('Y'))||(input.charAt(1)==('Z')))) {
;
}
else if((input.charAt(0)=='3') && !((input.charAt(1)==('0'))||(input.charAt(1)==('2'))||(input.charAt(1)==('4'))||(input.charAt(1)==('6'))||(input.charAt(1)==('8'))||(input.charAt(1)==('T'))||(input.charAt(1)==('U')))) {
;
}
else if((input.charAt(0)=='4') && !((input.charAt(1)==('0'))||(input.charAt(1)==('2'))||(input.charAt(1)==('4'))||(input.charAt(1)==('6'))||(input.charAt(1)==('8'))||(input.charAt(1)==('U'))||(input.charAt(1)==('V'))||(input.charAt(1)==('W'))||(input.charAt(1)==('X'))||(input.charAt(1)==('Y'))||(input.charAt(1)==('Z')))) {
;
}
else if ((input.equals("20")) || (input.equals("21")) ||(input.equals("22")) ||(input.equals("2S")) ||(input.equals("2T")) ||(input.equals("2U")) ||(input.equals("2V")) ||(input.equals("2X")) ||(input.equals("2Y")) ||(input.equals("2Z")) ||(input.equals("30")) ||(input.equals("32")) ||(input.equals("34")) ||(input.equals("36")) ||(input.equals("38")) ||(input.equals("40")) ||(input.equals("42")) ||(input.equals("44")) ||(input.equals("46")) ||(input.equals("48")) ||(input.equals("4U")) ||(input.equals("4V")) ||(input.equals("4W")) ||(input.equals("4X")) ||(input.equals("4Y")) ||(input.equals("4Z"))) {
switch(input) {
case "20":
case "21":
case "22":
OFF();
break;
case "2X":
case "2Y":
case "2Z":
main(null);
break;
case "30":
a = 1;
break;
case "32":
a = 2;
break;
case "34":
a = 3;
break;
case "36":
a = 4;
break;
case "38":
a = 5;
break;
case "40":
a = 6;
break;
case "42":
a = 7;
break;
case "44":
a = 8;
break;
case "46":
a = 9;
break;
case "48":
a = 0;
break;
case "4U":
case "4V":
case "4W":
case "4X":
case "4Y":
case "4Z":
solve();
break;
}
}
else {
System.out.println("Invalid key.");
System.out.println(" Key: " + input+"");
inputmethod(input);
}
}
else {
System.out.println("Invalid key.");
System.out.println(" Key: " + input +"");
inputmethod(input);
}
return a;
}
public static int sign (String input, int signcontrol) {
int sign1 = signcontrol;
if ((input.equals("2S")) ||(input.equals("2T")) ||(input.equals("2U")) ||(input.equals("2V"))) {
sign1 = sign1 * -1;
}
else {
sign1=1;
}
return sign1;
}
public static void OFF() {
System.exit(0);
}
public static void solve() {
}
}
Where do I go from here? I'm stuck in many places. Can someone guide me? First, I'm having problems with the methods. I used a couple of methods to display the "Panther Solver" and get the input.
The assignment asks to display the "Panther Solve", then the user picks what digits he/she wants. IE "32" means 2. This is very tricky though. If the user selects the +/- sign before a digit, it changes the value that he/she is about the input to a negative. It however does NOT display the negative sign right away, but only after he/she selects the digits.
Each time you select the digit and press enter, the screen pretty much reloads itself, and in the answer key, it displays what you typed. In the "0", row, it also displays what you just selected.
If you select the +/- sign after a digit is selected, nothing will happen. If you select any valid key that does not correlate to an input, nothing should happen. Just like the quadratic equation, with a,b,c, you type in your first response (a), then input comma, then go to b, then comma, then c, then solve. Each time you input, the input is evaluated.
In the input, all letters must be capitalized, if required, or else you would return and "Invalid Key". Also, for the equation, if a=0, return "Error".
I also have to formulate a solution for imaginary numbers, using i.
I am stuck in all parts. My questions are, where do I go from here in my code.
My first problem is getting the "Panther Solver" to display first, then accept the input. The next one is evaluated the negative/positive sign, and if it comes after or before the number. If it comes after, do nothing. If before, change the value to negative.
The other one is trying to make a loop for all of this in the main statement. Because for "a" in the quadratic equation, the user could want to enter "100". So I have to loop that.
Last, on the "0" row, I have to display the previous user input, just like an actual calculator. I'm having trouble getting that, and making it fit. For example, "a" starts at two spaces from the enter. Obviously as much input is entered, "a" moves to the left.
Thanks

Like all beginners, you're making the problem too difficult by failing to decompose it into small enough chunks.
Forget about user input and interfaces. Get the base solver algorithm working with hard wired inputs that you know the answer to. Write it, test it, and put it aside. Then start developing another class that deals only with getting input values and passing them to the class that actually does the work.
When you find yourself overwhelmed by too much detail, simplify the problem into smaller parts that you can deal with. Then knit them together to solve your larger problem.
It's call decomposition. It's the basis for all problem solving, especially programming and computer science.
For goodness' sake, it's solving a quadratic equation. Panther? Unnecessarily confusing.
Don't be fooled by the name. Forget about all that fancy output and get the base solver working. There are special cases you'll need to concern yourself with:
Two real roots.
One zero root, one real root.
Two complex conjugate roots.

Related

Homework assignment with error with sentinel loops

Ok, so I am working on this class assignment where I have to write a program that uses a sentinel value controlled loop to input student scores and displays the count of students and the average of all scores when a -1 is entered. A title is to be displayed when the program first begins. Valid score values are from 0 to 100. When a value in excess of 100 is entered, it is not to be included in the total and the number of students is not to be incremented. When a value of -1 is entered, the list is ended and the program displays the number of valid scores entered and the average score. If a -1 is entered as the first input, no error is to be reported and a message is to be displayed that no scores were entered.
Now, I was originally able to get the program to give me an output where it allowed me to enter the grades but what I realized was that when I entered "999" or "-1" the program didn't stop and average the grades I inputted from the keyboard and so I've been trying to fix it and now I'm at a stump and don't have a clue on how to fix it. I'm a beginner at this Java Programming and using NetBeans software. Honestly, I have to constantly look up what the errors mean because I don't have a clue. I could really get some help since my professor had to evacuate last week he hasn't been able to have access to his computers so I'm at this alone.
The errors I'm getting right now are:
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:38: error: unclosed character literal
else (studentCount == '999');{
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:38: error: not a statement
else (studentCount == '999');{
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:38: error: 'else' without 'if'
else (studentCount == '999');{
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:38: error: unclosed character literal
else (studentCount == '999');{
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:40: error: class expected
studentCount = int.next();
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:40: error: ';' expected
studentCount = int.next();
6 errors
HOW DO I FIX THIS LOL? please help me, I'm so behind in my class because I haven't been able to get this project done. Below is my entire code.
public class StudentsScoreReport {
public static final int SCORE_COUNT = 5;
public static void main(String[] args) {
// Define Constants
double studentCount= 0; //students inital grade
double totalScore = 0; // students grades combined
double averageScore; // average score from the number of students
int scoreCount = 0; // output score from the calculated average score
// create the Scanner object.
Scanner stdin = new Scanner(System.in);
// INPUT: Title at the top of the out
System.out.println ("Kristina Rosado's Students Score Report");
System.out.println ("Enter a students score, 0 - 100, 999 to quit"); //input score from keyboard
// PROCESS: Read the scores for the first city
// NOTE: the program's score starts at 0, but people count from 1
if (studentCount == 0 && totalScore == 0 ){
averageScore = (totalScore / studentCount);
} // users input -1 at the first time
else {
averageScore = totalScore / studentCount;
System.out.printf ("%d student scores were entered\n", studentCount);
System.out.printf ("\nThe average of score of %d students is %.2f", studentCount, averageScore);
else (studentCount == '999');{
System.out.println ("Thank you for your entries");
studentCount = int.next();
}
}
while (studentCount != -1){
if (studentCount < -1) {
System.out.print("Please try again");
System.out.printf ("Enter the score for the next student #%d: ", scoreCount+1);
// input the next score
studentCount = stdin.nextDouble();
} else if (studentCount > 100) {
System.out.print("Please try again");
System.out.printf ("Enter the score for the next student #%d: ", scoreCount+1);
// input the next score
studentCount = stdin.nextDouble();
} // end of for loop
// end of for loop
}
System.out.println ("Illegal entry for score");{
System.out.println("There is no student score entered ");
averageScore = totalScore / scoreCount;
System.out.printf("\nThe average score for %d students is %8.2f\n", scoreCount, averageScore);
}
}// end of public static void main(String[] args);
} // end of public class StudentsScoreReport;enter code here
Can I just ask what language this is in. I can see multiple syntax errors but I just want to put it through an IDE first.

Simple encryption algorithm for homework. not getting decryption working properly

This is a homework question that I can't get my head around at all
Its a very simple encryption algorithm. You start with a string of characters as your alphabet:
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, .
Then ask the user to enter there own string that will act as a map such as:
0987654321! .,POIUYTREWQASDFGHJKLMNBVCXZ
Then the program uses this to make a map and allows you to enter text that gets encrypted.
For example MY NAME IS JOSEPH would be encrypted as .AX,0.6X2YX1PY6O3
This is all very easy, however he said that its a one to one mapping and thus implied that if I enter .AX,0.6X2YX1PY6O3 back into the program I will get out MY NAME IS JOSEPH
This doesn't happen, because .AX,0.6X2YX1PY6O3 becomes Z0QCDZQGAQFOALDH
The mapping only works to decrypt when you go backwards but the question implies that the program just loops and runs the one algorithm every time.
Even if some could say that it is possible I would be happy, I have pages and pages of paper filled up with possible workings, but I came up with nothing, the only solution to run the algorithm backwards back I don't think we are allowed to do that.
Any ideas?
Edit:
Unfortunately I can't get this to work (Using the orbit computation idea) What am I doing wrong?
//import scanner class
import java.util.Scanner;
public class Encryption {
static Scanner inputString = new Scanner(System.in);
//define alphabet
private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, .";
private static String map;
private static int[] encryptionMap = new int[40];//mapping int array
private static boolean exit = false;
private static boolean valid = true;
public static void main(String[] args) {
String encrypt, userInput;
userInput = new String();
System.out.println("This program takes a large reordered string");
System.out.println("and uses it to encrypt your data");
System.out.println("Please enter a mapping string of 40 length and the same characters as below but in different order:");
System.out.println(alpha);
//getMap();//don't get user input for map, for testing!
map=".ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, ";//forced input for testing only!
do{
if (valid == true){
System.out.println("Enter Q to quit, otherwise enter a string:");
userInput = getInput();
if (userInput.charAt(0) != 'Q' ){//&& userInput.length()<2){
encrypt = encrypt(userInput);
for (int x=0; x<39; x++){//here I am trying to get the orbit computation going
encrypt = encrypt(encrypt);
}
System.out.println("You entered: "+userInput);
System.out.println("Encrypted Version: "+encrypt);
}else if (userInput.charAt(0) == 'Q'){//&& userInput.length()<2){
exit = true;
}
}
else if (valid == false){
System.out.println("Error, your string for mapping is incorrect");
valid = true;//reset condition to repeat
}
}while(exit == false);
System.out.println("Good bye");
}
static String encrypt(String userInput){
//use mapping array to encypt data
String encrypt;
StringBuffer tmp = new StringBuffer();
char current;
int alphaPosition;
int temp;
//run through the user string
for (int x=0; x<userInput.length(); x++){
//get character
current = userInput.charAt(x);
//get location of current character in alphabet
alphaPosition = alpha.indexOf(current);
//encryptionMap.charAt(alphaPosition)
tmp.append(map.charAt(alphaPosition));
}
encrypt = tmp.toString();
return(encrypt);
}
static void getMap(){
//get a mapping string and validate from the user
map = getInput();
//validate code
if (map.length() != 40){
valid = false;
}
else{
for (int x=0; x<40; x++){
if (map.indexOf(alpha.charAt(x)) == -1){
valid = false;
}
}
}
if (valid == true){
for (int x=0; x<40; x++){
int a = (int)(alpha.charAt(x));
int y = (int)( map.charAt(x));
//create encryption map
encryptionMap[x]=(a-y);
}
}
}
static String getInput(){
//get input(this repeats)
String input = inputString.nextLine();
input = input.toUpperCase();
if ("QUIT".equals(input) || "END".equals(input) || "NO".equals(input) || "N".equals(input)){
StringBuffer tmp = new StringBuffer();
tmp.append('Q');
input = tmp.toString();
}
return(input);
}
}
You will (probably) not get your original string back if you apply that substitution again. I say probably because you can construct such inputs (they all do things like if A->B then B->A). But most inputs won't do that. You would have to construct the reverse map to decrypt.
However, there is a trick you can do if you're only allowed to go forward. Keep applying the mapping and you'll eventually return to your original input. The number of times you'll have to do that depends on your input. To figure out how many times, compute the orbit of each character, and take the least common multiple of all the orbit sizes. For your input the orbits are size 1 (T->T, W->W), 2 (B->9->B H->3->H U->R->U P->O->P), 4 (C->8->N->,->C), 9 (A->...->Y->A), and 17 (E->...->V->E). The LCM of all those is 612, so 611 forward mappings applied to the ciphertext will return you to the plaintext.
Well, you can get your string back this way only if you do reverse mapping. One to one mapping means that a single letter of your default alphabet maps to only one letter of your new alphabet and vice versa. I.e. you can't map ABCD to ABBA. It doesn't imply that you can get your initial string by doing a second round of encryption.
The thing you have described can be achieved if you use a finite alphabet and a displacement to encode your string. You can choose the displacement in such a way that after a number of rounds of encryption totalDisplacement mod alphabetSize == 0 Than you will get your string back going only forward.

Creating a unique filename from a list of alphanumeric strings

I apologize for creating a similar thread to many that are out there now, but I mainly wanted to also get some insight on some methods.
I have a list of Strings (could be just 1 or over a 1000)
Format = XXX-XXXXX-XX where each one is alphanumeric
I am trying to generate a unique string (currently 18 in length but probably could be longer ensuring not to maximize file length or path length) that I could reproduce if I have that same list. Order doesn't matter; although I may be interested if its easier to restrict the order as well.
My current Java code is follows (which failed today, hence why I am here):
public String createOutputFileName(ArrayList alInput, EnumFPFunction efpf, boolean pHeaders) {
/* create file name based on input list */
String sFileName = "";
long partNum = 0;
for (String sGPN : alInput) {
sGPN = sGPN.replaceAll("-", ""); //remove dashes
partNum += Long.parseLong(sGPN, 36); //(base 36)
}
sFileName = Long.toString(partNum);
if (sFileName.length() > 19) {
sFileName.substring(0, 18); //Max length of 19
}
return alInput;
}
So obviously just adding them did not work out so well I found out (also think I should take last 18 digits and not first 18)
Are there any good methods out there (possibly CRC related) that would work?
To assist with my key creation:
The first 3 characters are almost always numeric and would probably have many duplicate (out of 100, there may only be 10 different starting numbers)
These characters are not allowed - I,O
There will never be a character then a number in the last two alphachar subset.
I would use the system time. Here's how you might do it in Java:
public String createOutputFileName() {
long mills = System.currentTimeMillis();
long nanos = System.nanoTime();
return mills + " " + nanos;
}
If you want to add some information about the items and their part numbers, you can, of course!
======== EDIT: "What do I mean by batch object" =========
class Batch {
ArrayList<Item> itemsToProcess;
String inputFilename; // input to external process
boolean processingFinished;
public Batch(ArrayList<Item> itemsToProcess) {
this.itemsToProcess = itemsToProcess;
inputFilename = null;
processingFinished = false;
}
public void processWithExternal() {
if(inputFilename != null || processingFinished) {
throw new IllegalStateException("Cannot initiate process more than once!");
}
String base = System.currentTimeMillis() + " " + System.nanoTime();
this.inputFilename = base + "_input";
writeItemsToFile();
// however you build your process, do it here
Process p = new ProcessBuilder("myProcess","myargs", inputFilename);
p.start();
p.waitFor();
processingFinished = true;
}
private void writeItemsToFile() {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(inputFilename)));
int flushcount = 0;
for(Item item : itemsToProcess) {
String output = item.getFileRepresentation();
out.println(output);
if(++flushcount % 10 == 0) out.flush();
}
out.flush();
out.close();
}
}
In addition to GlowCoder's response, I have thought of another "decent one" that would work.
Instead of just adding the list in base 36, I would do two separate things to the same list.
In this case, since there is no way for negative or decimal numbers, adding every number and multiplying every number separately and concatenating these base36 number strings isn't a bad way either.
In my case, I would take the last nine digits of the added number and last nine of the multiplied number. This would eliminate my previous errors and make it quite robust. It obviously is still possible for errors once overflow starts occurring, but could also work in this case. Extending the allowable string length would make it more robust as well.
Sample code:
public String createOutputFileName(ArrayList alInput, EnumFPFunction efpf, boolean pHeaders) {
/* create file name based on input list */
String sFileName1 = "";
String sFileName2 = "";
long partNum1 = 0; // Starting point for addition
long partNum2 = 1; // Starting point for multiplication
for (String sGPN : alInput) {
//remove dashes
sGPN = sGPN.replaceAll("-", "");
partNum1 += Long.parseLong(sGPN, 36); //(base 36)
partNum2 *= Long.parseLong(sGPN, 36); //(base 36)
}
// Initial strings
sFileName1 = "000000000" + Long.toString(partNum1, 36); // base 36
sFileName2 = "000000000" + Long.toString(partNum2, 36); // base 36
// Cropped strings
sFileName1 = sFileName1.substring(sFileName1.length()-9, sFileName1.length());
sFileName2 = sFileName2.substring(sFileName2.length()-9, sFileName2.length());
return sFileName1 + sFileName2;
}

For loop construction and code complexity [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
My group is having some discussion and strong feelings about for loop construction.
I have favored loops like:
size_t x;
for (x = 0; x < LIMIT; ++x) {
if (something) {
break;
}
...
}
// If we found what we're looking for, process it.
if (x < LIMIT) {
...
}
But others seem to prefer a Boolean flag like:
size_t x;
bool found = false;
for (x = 0; x < LIMIT && !found; ++x) {
if (something) {
found = true;
}
else {
...
}
}
// If we found what we're looking for, process it.
if (found) {
...
}
(And, where the language allows, using "for (int x = 0; ...".)
The first style has one less variable to keep track of and a simpler loop header. Albeit at the cost of "overloading" the loop control variable and (some would complain), the use of break.
The second style has clearly defined roles for the variables but a more complex loop condition and loop body (either an else, or a continue after found is set, or a "if (!found)" in the balance of the loop).
I think that the first style wins on code complexity. I'm looking for opinions from a broader audience. Pointers to actual research on which is easier to read and maintain would be even better. "It doesn't matter, take it out of your standard" is a fine answer, too.
OTOH, this may be the wrong question. I'm beginning to think that the right rule is "if you have to break out of a for, it's really a while."
bool found = false;
x = 0;
while (!found && x < LIMIT) {
if (something) {
found = true;
...handle the thing...
}
else {
...
}
++x;
}
Does what the first two examples do but in fewer lines. It does divide the initialization, test, and increment of x across three lines, though.
I'd actually dare to suggest consideration of GOTO to break out of loops in such cases:
for (size_t x = 0; x < LIMIT && !found; ++x) {
if (something)
goto found;
else {
...
}
}
// not found
...
return;
found:
...
return;
I consider this form to be both succint and readable. It may do some good in many simple cases (say, when there is no common processing in this function, in both found/unfound cases).
And about the general frowning goto receives, I find it to be a common misinterpretation of Dijkstra's original claims: his arguments favoured structured loop clauses, as for or while, over a primitive loop-via-goto, that still had a lot of presence circa 1968. Even the almighty Knuth eventualy says -
The new morality that I propose may
perhaps be stated thus: "Certain go to
statements which arise in connection with
well-understood transformations are acceptable, provided that the program documentation explains what the transformation was."
Others here occasionaly think the same.
While I disagree that an extra else really makes the 2nd more complicated, I think it's primarily a matter of aesthetics and keeping to your standard.
Personally, I have a probably irrational dislike of breaks and continues, so I'm MUCH more likely to use the found variable.
Also, note that you CAN add the found variable to the 1st implementation and do
if(something)
{
found = true;
break;
}
if you want to avoid the variable overloading problem at the expense of the extra variable, but still want the simple loop terminator...
The former example duplicates the x < LIMIT condition, whereas the latter doesn't.
With the former, if you want to change that condition, you have to remember to do it in two places.
I would prefer a different one altogether:
for (int x = 0; x < LIMIT; ++x) {
if (something) {
// If we found what we're looking for, process it.
...
break;
}
...
}
It seems you have not any trouble you mention about one or the other... ;-)
no duplication of condition, or readability problem
no additional variable
I don't have any references to hand (-1! -1!), but I seem to recall that having multiple exit points (from a function, from a loop) has been shown to cause issues with maintainability (I used to know someone who wrote code for the UK military and it was Verboten to do so). But more importantly, as RichieHindle points out, having a duplicate condition is a Bad Thing, it cries out for introducing bugs by changing one and not the other.
If you weren't using the condition later, I wouldn't be bothered either way. Since you are, the second is the way to go.
This sort of argument has been fought out here before (probably many times) such as in this question.
There are those that will argue that purity of code is all-important and they'll complain bitterly that your first option doesn't have identical post-conditions for all cases.
What I would answer is "Twaddle!". I'm a pragmatist, not a purist. I'm as against too much spaghetti code as much as the next engineer but some of the hideous terminating conditions I've seen in for loops are far worse than using a couple of breaks within your loop.
I will always go for readability of code over "purity" simply because I have to maintain it.
This looks like a place for a while loop. For loops are Syntactic Sugar on top of a While loop anyway. The general rule is that if you have to break out of a For loop, then use a While loop instead.
package com.company;
import java.io.*;
import java.util.Scanner;
public class Main {
// "line.separator" is a system property that is a platform independent and it is one way
// of getting a newline from your environment.
private static String NEWLINE = System.getProperty("line.separator");
public static void main(String[] args) {
// write your code here
boolean itsdone = false;
String userInputFileName;
String FirstName = null;
String LastName = null;
String user_junk;
String userOutputFileName;
String outString;
int Age = -1;
int rint = 0;
int myMAX = 100;
int MyArr2[] = new int[myMAX];
int itemCount = 0;
double average = 0;
double total = 0;
boolean ageDone = false;
Scanner inScan = new Scanner(System.in);
System.out.println("Enter First Name");
FirstName = inScan.next();
System.out.println("Enter Last Name");
LastName = inScan.next();
ageDone = false;
while (!ageDone) {
System.out.println("Enter Your Age");
if (inScan.hasNextInt()) {
Age = inScan.nextInt();
System.out.println(FirstName + " " + LastName + " " + "is " + Age + " Years old");
ageDone = true;
} else {
System.out.println("Your Age Needs to Have an Integer Value... Enter an Integer Value");
user_junk = inScan.next();
ageDone = false;
}
}
try {
File outputFile = new File("firstOutFile.txt");
if (outputFile.createNewFile()){
System.out.println("firstOutFile.txt was created"); // if file was created
}
else {
System.out.println("firstOutFile.txt existed and is being overwritten."); // if file had already existed
}
// --------------------------------
// If the file creation of access permissions to write into it
// are incorrect the program throws an exception
//
if ((outputFile.isFile()|| outputFile.canWrite())){
BufferedWriter fileOut = new BufferedWriter(new FileWriter(outputFile));
fileOut.write("==================================================================");
fileOut.write(NEWLINE + NEWLINE +" You Information is..." + NEWLINE + NEWLINE);
fileOut.write(NEWLINE + FirstName + " " + LastName + " " + Age + NEWLINE);
fileOut.write("==================================================================");
fileOut.close();
}
else {
throw new IOException();
}
} // end of try
catch (IOException e) { // in case for some reason the output file could not be created
System.err.format("IOException: %s%n", e);
e.printStackTrace();
}
} // end main method
}

Algorithm to format text to Pascal or camel casing

Using this question as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.
For example:
mynameisfred
becomes
Camel: myNameIsFred
Pascal: MyNameIsFred
I found a thread with a bunch of Perl guys arguing the toss on this question over at http://www.perlmonks.org/?node_id=336331.
I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:-
camelCase("hithisisatest");
The output could be:-
"hiThisIsATest"
Or:-
"hitHisIsATest"
There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at http://norvig.com/spell-correct.html which might help algorithm-wise, I wrote a C# implementation if C#'s your language).
I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this_is_a_test and converts that. That'd be simple to implement, i.e. in pseudocode:-
SetPhraseCase(phrase, CamelOrPascal):
if no delimiters
if camelCase
return lowerFirstLetter(phrase)
else
return capitaliseFirstLetter(phrase)
words = splitOnDelimiter(phrase)
if camelCase
ret = lowerFirstLetter(first word)
else
ret = capitaliseFirstLetter(first word)
for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])
return ret
capitaliseFirstLetter(word):
if len(word) <= 1 return upper(word)
return upper(word[0]) + word[1..len(word)]
lowerFirstLetter(word):
if len(word) <= 1 return lower(word)
return lower(word[0]) + word[1..len(word)]
You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished.
A C# implementation of the above described algorithm is as follows (complete console program with test harness):-
using System;
class Program {
static void Main(string[] args) {
var caseAlgorithm = new CaseAlgorithm('_');
while (true) {
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) return;
Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'",
input,
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));
}
}
}
public class CaseAlgorithm {
public enum CaseMode { PascalCase, CamelCase }
private char delimiterChar;
public CaseAlgorithm(char inDelimiterChar) {
delimiterChar = inDelimiterChar;
}
public string SetPhraseCase(string phrase, CaseMode caseMode) {
// You might want to do some sanity checks here like making sure
// there's no invalid characters, etc.
if (string.IsNullOrEmpty(phrase)) return phrase;
// .Split() will simply return a string[] of size 1 if no delimiter present so
// no need to explicitly check this.
var words = phrase.Split(delimiterChar);
// Set first word accordingly.
string ret = setWordCase(words[0], caseMode);
// If there are other words, set them all to pascal case.
if (words.Length > 1) {
for (int i = 1; i < words.Length; ++i)
ret += setWordCase(words[i], CaseMode.PascalCase);
}
return ret;
}
private string setWordCase(string word, CaseMode caseMode) {
switch (caseMode) {
case CaseMode.CamelCase:
return lowerFirstLetter(word);
case CaseMode.PascalCase:
return capitaliseFirstLetter(word);
default:
throw new NotImplementedException(
string.Format("Case mode '{0}' is not recognised.", caseMode.ToString()));
}
}
private string lowerFirstLetter(string word) {
return char.ToLower(word[0]) + word.Substring(1);
}
private string capitaliseFirstLetter(string word) {
return char.ToUpper(word[0]) + word.Substring(1);
}
}
The only way to do that would be to run each section of the word through a dictionary.
"mynameisfred" is just an array of characters, splitting it up into my Name Is Fred means understanding what the joining of each of those characters means.
You could do it easily if your input was separated in some way, e.g. "my name is fred" or "my_name_is_fred".

Resources