Java Gradebook Program - compilation

I am trying to make a simple gradebook program. My code is not finished yet but I am trying to structure it first. I keep getting an unresolved compilation error that for the life of me I can not figure out. I know it is something simple and stupid but I am about as much of a rookie as you get. Any help trying to overcome this error (Exception in thread "main" java.lang.Error: Unresolved compilation problem: student cannot be resolved to a variable) would be much appreciated!
import java.util.Scanner;
public class Gradebook {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
float discussionweight, hwweight, examweight, discussion, hw, exam, finalaverage;
// Initializes the input scanner
Scanner scan = new Scanner(System.in);
System.out.print("Enter the students name: ");
student = scan.next("");
// Prompts for the weight of the discussions
System.out.print ("Enter the weight of the discussions as an integer: ");
discussionweight = scan.nextFloat();
// Prompts for the discussions grade
System.out.print ("Enter the score of the discussions as an integer: ");
discussion = scan.nextFloat();
// Prompts for the weight of the homework grade in an integer
System.out.print ("Enter the weight of the homework as an integer: ");
hwweight = scan.nextFloat();
// Prompts for hw grade
System.out.print ("Enter the hw grade: ");
hw = scan.nextFloat();
System.out.print("Enter the weight of the exam as an integer");
examweight = scan.nextFloat();
System.out.print("Enter the exam grade");
exam = scan.nextFloat();
// Calculate and print the final, weighted average.
finalaverage = (((discussionweight * discussion) + (hw * hwweight) + (exam * examweight)) / 100);
System.out.println ("The final average is "+ finalaverage);
}
}
}
}

It looks like you are never declaring a variable named student.
string student = scan.next("");
Same for the rest of the variables you are using.

student = scan.next("");
you never tell the compiler what type student is.
something like String student = scan...

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.

I am getting ';' expected error,illegal start expression and else without if

i want to out put like this-
150 can be fitted in:
short
int
long
150000 can be fitted in:
int
long
1500000000 can be fitted in:
int
long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
long
import java.io.;
import java.util.;
import java.text.;
import java.math.;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
byte b;
long l;
int t, v;
int[] n;
Scanner in=new Scanner(System.in);
System.out.println("Inter the number");
v=in.nextInt();
n=new int[v];
int i=0;
while(n.hasNextInt())
{
n[i]=in.nextInt();
i++;
}
for(int k=0;k<t;k++)
{if(b<n[k])
{
System.out.println(k+"this is fit in");
System.out.println("*short");
System.out.println("*int");
System.out.println("*long");}
else if(t==n[k]){
System.out.println(n[k]+"this is fit in");
System.out.println("int");
System.out.println("long");}
else if(t<=n[k]){
System.out.println(n[k]+"this is fit in");
System.out.println("int");
System.out.println("long");}
else if((t<=n[k])&&(l==n[k])){
System.out.println(n[k]+"this is fit in");
System.out.println("long");}
else{
System.out.println(n[k]+"this not fitted any where");}}}}
A quick fix is to use an IDE like eclipse or netbeans that formats your code and makes life far easier to debug, develop in open-source and reduces the development time.
Coming to the errors: I can spot that you have missed a } at the end of the program script and I notice a syntactically wrong statement:
} else if (t <= n[k] > ) {
Please confirm to correct syntactically code and use formatting to enable fellow developers help you. Good luck!
I expect it's the fact you have no logical join (&& or ||) and value here:
else if(t<=n[k]>){
// ------------^
Also note that the type int[] has no hasNextInt method, so this line:
while(n.hasNextInt())
won't compile (as n is int[]).
There are about a half dozen other logic errors in there (using uninitialized variables, etc.), but hopefully that gets you headed the right way.

Trouble With Java Program using parameters and methods [closed]

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.

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.

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
}

Resources