I still a little bit new so I'm going to include all of my java code and then explain what I am looking for.
import java.util.Scanner;
public class Part_I{
public static Scanner input = new Scanner(System.in);
public static String strInfo;
public static int number;
public static void main(String[] args){
String presidents[][] = {
{"1 ","George"," ","Washington"," (1789-1797) ","John Adams"},
{"2 ","John"," ","Adams"," (1797-1801) ","Thomas Jefferson"},
{"3 ","Thomas"," ","Jefferson"," (1801-1809) ","Aaron Burr"},
{"4 ","James"," ","Madison"," (1809-1817) ","George Clinton"},
{"5 ","James"," ","Monroe"," (1817-1825) ","Daniel D. Tompkins"},
{"6 ","John"," Quincy ","Adams"," (1825-1829) ","John C. Calhoun"},
{"7 ","Andrew"," ","Jackson"," (1829-1837) ","John C. Calhoun"},
{"8 ","Martin"," Van ","Buren"," (1837-1841) ","Richard M. Johnson"},
{"9 ","William"," Henry ","Harrison"," (1841) ","John Tyler"},
{"10 ","John"," ","Tyler"," (1841-1845) ","None"},
{"11 ","James"," K. ","Polk"," (1845-1849) ","George M. Dallas"},
{"12 ","Zachary"," ","Taylor"," (1849-1850) ","Millard Fillmore"},
{"13 ","Millard"," ","Fillmore"," (1850-1853) ","None"},
{"14 ","Franklin"," ","Pierce"," (1853-1857) ","William King"},
{"15 ","James"," ","Buchanan"," (1857-1861) ","John C. Breckinridge"},
{"16 ","Abraham"," ","Lincoln"," (1861-1865) ","Hannibal Hamlin"},
{"17 ","Andrew"," ","Johnson"," (1865-1869) ","None"},
{"18 ","Ulysses"," S. ","Grant"," (1869-1877) ","Schuyler Colfax"},
{"19 ","Rutherford"," B. ","Hayes"," (1877-1881) ","William Wheeler"},
{"20 ","James"," A. ","Garfield"," (1881) ","Chester Arthur"},
{"21 ","Chester"," ","Arthur"," (1881-1885) ","None"},
{"22 ","Grover"," ","Cleveland"," (1885-1889) ","Thomas Hendricks"},
{"23 ","Benjamin"," ","Harrison"," (1889-1893) ","Levi P. Morton"},
{"24 ","Grover"," ","Cleveland"," (1893-1897) ","Adlai E. Stevenson"},
{"25 ","William"," ","McKinley"," (1897-1901) ","Garret Hobart"},
{"26 ","Theodore"," ","Roosevelt"," (1901-1909) ","None"},
{"27 ","William"," Howard ","Taft"," (1909-1913) ","James S. Sherman"},
{"28 ","Woodrow"," ","Wilson"," (1913-1921) ","Thomas R. Marshall"},
{"29 ","Warren"," G. ","Harding"," (1921-1923) ","Calvin Coolidge"},
{"30 ","Calvin"," ","Coolidge"," (1923-1929) ","None"},
{"31 ","Herbert"," ","Hoover"," (1929-1933) ","Charles Curtis"},
{"32 ","Franklin"," D. ","Roosevelt"," (1933-1945) ","John Nance Garner"},
{"33 ","Harry"," S. ","Truman"," (1945-1953) ","None"},
{"34 ","Dwight"," D. ","Eisenhower"," (1953-1961) ","Richard Nixon"},
{"35 ","John"," F. ","Kennedy"," (1961-1963) ","Lyndon B. Johnson"},
{"36 ","Lyndon"," B. ","Johnson"," (1963-1969) ","None"},
{"37 ","Richard"," ","Nixon"," (1969-1974) ","Spiro Agnew"},
{"38 ","Gerald"," ","Ford"," (1974-1977) ","Nelson Rockefeller"},
{"39 ","Jimmy"," ","Carter"," (1977-1981) ","Walter Mondale"},
{"40 ","Ronald"," ","Reagan"," (1981-1989) ","George Bush"},
{"41 ","George"," ","Bush"," (1989-1993) ","Dan Quayle"},
{"42 ","Bill"," ","Clinton"," (1993-2001) ","Al Gore"},
{"43 ","George"," W. ","Bush"," (2001-2009) ","Dick Cheney"},
{"44 ","Barack"," ","Obama"," (2009-2017) ","Joe Biden"},
};
System.out.println("This will display the President and VP of the United States based on the number you provide.");
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
while(strInfo != "q"){
if(isInteger(strInfo)){
number = Integer.parseInt(strInfo);
if (number >= 1 && number <=44){
System.out.println();
System.out.println(presidents[number-1][0] + "President " + presidents[number-1][1] + presidents[number-1][2] + presidents[number-1][3] + presidents[number-1][4] + "Vice President " + presidents[number-1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
}else{
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}else{
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
}
}
}
public static boolean isInteger(String strInfo){
if (strInfo == null) {
return false;
}
int length = strInfo.length();
if (length == 0) {
return false;
}
int i = 0;
if (strInfo.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = strInfo.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
}
My main concern is with the while loop.
while(strInfo != "q"){
if(isInteger(strInfo)){
number = Integer.parseInt(strInfo);
if (number >= 1 && number <=44){
System.out.println();
System.out.println(presidents[number-1][0] + "President " + presidents[number-1][1] + presidents[number-1][2] + presidents[number-1][3] + presidents[number-1][4] + "Vice President " + presidents[number-1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
}else{
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}else{
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
}
}
}
I want to make it so that it any string other than what is able to be converted to an int or "q" would say wrong input and make you input another string value. Right now, any string will make the program terminate. What should I change in that while loop and how should I change it or what should it look like instead so that if the string input is not q or convertible to an int will make wrong input display and ask for input again?
This will help you in achieving what you want to do
while (!strInfo.equals("q")) {
if (isInteger(strInfo)) {
number = Integer.parseInt(strInfo);
if (number >= 1 && number <= 44) {
System.out.println();
System.out.println(presidents[number - 1][0] + "President " + presidents[number - 1][1] + presidents[number - 1][2] + presidents[number - 1][3] + presidents[number - 1][4] + "Vice President " + presidents[number - 1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
} else {
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
} else {
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
You shouldn't check string equality using normal operators like "=" and "!=". Use the String .equals() method.
So your first line would be
while(!strInfo.equals("q"))
More info:
http://www.leepoint.net/data/expressions/22compareobjects.html
The reason your code is not working is because you are trying to compare whether the contents of two strings are equal using == operator (which only compares if the two references point to the same object). == Operator does not compare the contents of the two strings.
In order to make your code work, you would need to use equals to compare the contents of the two strings as follows :
while(!strInfo.equals("q"))
Now lets try to delve deep into why your code is not working. For that we need to understand the basic difference between == & equals
== Operator is used to compare if both the references on its either side point to the same object (Basically you can say its similar to
comparing address of the object to which the references point to).
Whereas equals in case of String compares the content of the two Strings. It is the responsibility of the creator of the class to override the default equals method to compare the objects of that class depending on what makes sense for that object. For example in case of String class the creators of the class have overriden the equals method to compare the contents of the Strings.
String a = "test"; // lets say the object guy has address : 24
String b = a; // now b points to the same object that is being referenced by a
System.out.println(a == b); // this will be true as both point to the same reference
System.out.println(a.equals(b)); // this will be true as the contents of both these strings is the same.
// Now lets consider a new strings having same content "test"
String c = "test";
System.out.println(a == c); // this will be false as both point to the different references or memory location
System.out.println(a.equals(c)); // this will be true as the contents of both these strings is the same.
I realized I made an infinite loop and everytime I enter that loop, my cancel button doesn't function and the dialog box continuously pops up.
Here's the code
String buffer = " "; //Input a string into console
boolean badInput = true;
boolean badInput2 = true;
String idNum = ""; //ask for id number
String skill = ""; // ask for skill number
int skillInt = 0; // skill is an int
//prompt user for file location
File loc = new File(JOptionPane.showInputDialog(null, "Please provide the file location: "));
RandomAccessFile store = new RandomAccessFile(loc, "rw");
//prompt user for a command
String cmd = "start";
int recLocation = 0;
while(cmd.compareToIgnoreCase("end")!=0){ //stay in program (loop) until end command is given
cmd = JOptionPane.showInputDialog(null, "Please input a command (new, old or end): ");
//creating new entry
if(cmd.compareToIgnoreCase("new")==0){
while(badInput){ //keep them in loop until they give the input in the right format
idNum = JOptionPane.showInputDialog(null, "Please input an ID number (1 - 20): ");
// else JOptionPane.CANCEL_OPTIONsetDefaultCloseOperation(JOptionPane.EXIT_ON_CLOSE);
try{
//corresponding int for ID number, which becomes the record location
//if number is not 1-20, code below
recLocation = Integer.parseInt(idNum);
if(recLocation<1 || recLocation>20){
System.out.println("Please check that your number is between 1 and 20.");
}else{
badInput = false;
break;
}
}
catch(NumberFormatException NF){ // if input isnt a number
System.out.println("Please check that your number is in the correct format.");
}
}
//ask for names
String pName = JOptionPane.showInputDialog(null, "Please input a player name: ");
String tName = JOptionPane.showInputDialog(null, "Please input a team name: ");
//ask for skill level
while(badInput2){ //keep them in the loop until they give the input in the right format
skill = JOptionPane.showInputDialog(null, "Please input a skill level (0 - 99): ");
try{
//corresponding int for skill number, to check if in the right format
skillInt = Integer.parseInt(skill);
if(skillInt<0 || skillInt>99){
System.out.println("Please check that your number is between 0 and 99.");
}else{
badInput2 = false;
break;
}
}
catch(NumberFormatException NF){ //exception or error thrown if input is not in correct format
System.out.println("Please check that your number is in the correct format.");
}
}
String date = JOptionPane.showInputDialog(null, "Please input today's date (ex: 25Jun2014): ");
//formatting id number
if (idNum.length() < 2){
idNum = idNum+buffer;
}
//formatting player name
if (pName.length() > 26){
pName = pName.substring(0, 26);
} else {
while(pName.length() < 26){
pName = pName+buffer;
}
}
//formatting team name
if (tName.length() > 26){
tName = tName.substring(0, 26);
} else {
while(tName.length() < 26){
tName = tName+buffer;
}
}
//formatting date
if (date.length() > 9){
date = date.substring(0, 9);
} else {
while(date.length() < 9){
date = date+buffer;
}
}
//formatting skill
if (skill.length() < 2){
skill = skill+buffer;
}
//create full, identifying string
String fullRecord = idNum + " " + pName + tName + skill + " " + date;
store.seek((RECORD_LENGTH+2) * (recLocation-1));
store.writeUTF(fullRecord);
//reset booleans
badInput = true;
badInput2 = true;
}
//accessing old entry
if(cmd.compareToIgnoreCase("old")==0){
idNum = JOptionPane.showInputDialog(null, "Please input an ID number (1 through 20): ");
recLocation = Integer.parseInt(idNum);
store.seek((RECORD_LENGTH+2)*(recLocation-1));
String fullRecord = store.readUTF();
//interpret information from full string
try
{idNum = fullRecord.substring(0, 5);
String pName = fullRecord.substring(5, 31);
String tName = fullRecord.substring(31, 57);
skill = fullRecord.substring(57, 62);
String date = fullRecord.substring(62, 71);
System.out.println("ID: "+idNum+" NAME: "+pName+" TEAM: "+tName+" SKILL: "+skill+" DATE: "+date);
}
catch(StringIndexOutOfBoundsException S){
System.out.println("No record found at that location.");
}
}
// JOptionPane.showMessageDialog(null, "good bye");
}
Sorry if I didn't format this right. It's my first time. I was wondering how I could get the cancel button to exit the loop. I tried using if (cmd == null) System.exit(0); but that doesn't seem to function. I'm really novice at java and I have little experience so bear with me please.
First I'd suggest using equalsIgnoreCase as your String comparison instead of compareIgnoreCase: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)
while(!cmd.equalsToIgnoreCase("end")) {
Then if one of the JOptionPane.showInputDialog()'s returns null which would mean they'd cancelled, you could have an if statement that sets the cmd string to "end". I think though you should probably try to simplify the loop because it's got a lot in it all in the one block. That makes it hard to debug.
I am trying to write to an outfile.txt using variables that are inside if statements.
when I compile it it keeps saying the variable has not been initialized when in fact they have been, one as a string and char as the other.
import java.io.*;
import java.util.Scanner;
public class program5{
// read string keyboard inputs
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
public static void main(String[] args) throws IOException{
// read string keyboard inputs
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int i, gradeA_count = 0, gradeB_count = 0, gradeC_count = 0,
gradeD_count = 0, gradeF_count = 0, first_grade,
second_grade, third_grade, fourth_grade,
total_of_grades;
String remarks, course_name, semester, instructor_name, student_name;
char grade;
double average_grade;
int[] array_of_int_numbers = new int[10];
Scanner sc = new Scanner(System.in);
// set up a outfile to write to
Writer outfile = new BufferedWriter(new FileWriter("e:outfile.txt"));
// Write the class information to the outfile
outfile.write(" CMPS 161 Program Five, Fall 2015\n\n");
// separate top and next line for ease of sight
outfile.write(" -------------------------------- \n\n");
System.out.println("Enter the course name: ");
course_name=input.readLine();
System.out.println("Enter the Semester: ");
semester=input.readLine();
System.out.println("Enter the Instructor: ");
instructor_name=input.readLine();
outfile.write("Course: " +(String.format("%-8s",course_name))+ " Semester: " +(String.format("%-10s",semester))+ " Instructor: " +(String.format("%-12s",instructor_name))+ "\n\n");
outfile.write("Array Item Student Name T1 T2 T3 T4 Avg Grade Remarks\n\n");
outfile.write("=================================================================\n\n");
// array initialization
for (i = 0; i < 1; i++) array_of_int_numbers[i] = 0;
// prompt user for a value into the array
for (i = 0; i < 1; i++){
System.out.println("Enter a Students Name: ");
student_name=input.readLine();
System.out.println("Enter the first grade: ");
first_grade=sc.nextInt();
System.out.println("Enter the second grade: ");
second_grade=sc.nextInt();
System.out.println("Enter the third grade: ");
third_grade=sc.nextInt();
System.out.println("Enter the fourth grade: ");
fourth_grade=sc.nextInt();
total_of_grades = first_grade + second_grade + third_grade + fourth_grade;
average_grade = (double) total_of_grades / 4.0;
System.out.println("Your average grade is " +(String.format("%.1f",average_grade))+ "\n");
if (average_grade >= 90){
remarks = "Excellent";
grade = 'A';
gradeA_count++;
}else if (average_grade >= 80){
remarks = "Very Good";
grade = 'B';
gradeB_count++;
}else if (average_grade >= 70){
remarks = "Good";
grade = 'C';
gradeC_count++;
}else if (average_grade >= 60){
remarks = "Poor";
grade = 'D';
gradeD_count++;
}else if (average_grade >= 0){
remarks = "Fail";
grade = 'F';
gradeF_count++;
}
outfile.write("["+i+"]"+ student_name +
"" + first_grade +
"" + second_grade +
"" + third_grade +
""+ fourth_grade +
"%" + average_grade +
"" + grade +
"" + remarks + "\n");
}
for (i = 0; i < array_of_int_numbers.length; i++){
System.out.println("array_of_int_numbers["+(i+1)+ "] = "+array_of_int_numbers[i]);
}
System.out.println("Number of A's : " + gradeA_count);
System.out.println("Number of B's : " + gradeB_count);
System.out.println("Number of C's : " + gradeC_count);
System.out.println("Number of D's : " + gradeD_count);
System.out.println("Number of F's : " + gradeF_count);
outfile.close();
} // end program
} // end class
I am new to coding (only my fifth program) and this is my first semester in college, any help would be greatly appreciated.
I am using JGrasp as my professor requires it and coding in java.
Edit:
Here are the exceptions being thrown:
program5.java:107: error: variable grade might not have been initialized
"" + grade +
^
program5.java:108: error: variable remarks might not have been initialized
"" + remarks + "\n");
^
At the beginning of the program, when you declare grade and remarks, you aren't initializing it. You must set these variables to a default value.
For example:
String remarks = "";
char grade = '0';
It doesn't really matter what they're set to right now, because they'll be changed later.
Now, if you know that average_grade will never be negative, then you can replace that last else if statement with a simple else. This is why Java thinks that the variables may not be initialized, because there is the possibility that average_grade could become negative.
I am in a situation where I want to write something(writing employee details with punchin & punchout) to a file and read it back(to show as a report of who all the employees punchedin & punchedout).
package Test;
import java.io.*;
import java.text.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws IOException {
String lastName = "";
String firstName = "";
String choice = "y";
String customerChoice = "x";
int empid = 0;
Scanner sc = new Scanner(System.in);
int currentIndex;
File file = new File("E:/output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
int[] punchedArray;
punchedArray = new int[100];
// System.out.println(t);
while (!customerChoice.equalsIgnoreCase("d") && customerChoice != "invalid" && choice.equalsIgnoreCase("y")) {
customerChoice = getValidCustomerChoice(sc);
if (customerChoice.equalsIgnoreCase("a")) {
// System.out.println("In Create Customer");
System.out.print("Enter your first name: ");
firstName = sc.next();
System.out.print("Enter your last name: ");
lastName = sc.next();
System.out.println(firstName + lastName + "with employee id" + empid);
//System.out.println(firstNameArray[newEmployeeIndex] + " " + lastNameArray[newEmployeeIndex] + " your employee ID is: " + employeeIDArray[newEmployeeIndex]);
empid++;
//sc.next();
}
if (customerChoice.equalsIgnoreCase("b")) {
System.out.println("Welcome to the punch in/out screen"+"\n");
System.out.print("Enter your employee ID: ");
currentIndex = Integer.parseInt(sc.next());
if (punchedArray[currentIndex] == 0)
{
System.out.println("You are now punched in");
punchedArray[currentIndex] = 1;
}
else if (punchedArray[currentIndex] == 1)
{
System.out.println("You are now punched out");
punchedArray[currentIndex] = 0;
}
System.out.print(firstName + " "+ lastName + " "+ "your employee ID is " + currentIndex + " and your clock date and time is: " + " "+ cal.getTime() +"\n");
String content = firstName + lastName + empid + cal.getTime();
bw.write(content);
bw.newLine();
bw.close();
}
if (customerChoice.equalsIgnoreCase("c")) {
System.out.print("Welcome to the report screen." + "\n");
System.out.print("Enter your selection (I = individual report or A= all employees):" + "\n");
customerChoice = sc.next();
if (customerChoice.equalsIgnoreCase("i")) {
System.out.println("In Individual Report");
} else if (customerChoice.equalsIgnoreCase("a")) {
System.out.println("In Consoldated Report");
}
}
if(customerChoice.equalsIgnoreCase("d"))
{
//bw.close();
break;
}
}
}
public static String getValidCustomerChoice(Scanner sc) {
String customerChoice = "";
// sc.nextLine();
boolean isValid = false;
int invalidCounter = 0;
System.out.print("Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):");
while (isValid == false && invalidCounter < 3) {
customerChoice = sc.next();
if (!customerChoice.equalsIgnoreCase("a")
&& !customerChoice.equalsIgnoreCase("b") && !customerChoice.equalsIgnoreCase("c") && !customerChoice.equalsIgnoreCase("d") && !customerChoice.equalsIgnoreCase("I") && !customerChoice.equalsIgnoreCase("A")) {
System.out.println("Invalid choice. Try again.\n");
invalidCounter++;
} else {
isValid = true;
}
sc.nextLine();
}
if (invalidCounter >= 3) {
System.out.println("Invalid three times. Program Exiting.\n");
return "invalid";
}
return customerChoice;
}
}
At line[75] bw.write(content) I am writing to a file called "output.txt"(I also want to add timestamp to those employees whom I wrote to file). But somehow the data is not going into the file, I am sure that I am making a mistake somewhere in closing that and I want to read from the same file which I wrote. Can someone please suggest me where I am going wrong?
Adding more details:
run:
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):a
Enter your first name: Sa
Enter your last name: Ka
SaKawith employee id0
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):b
Welcome to the punch in/out screen
Enter your employee ID: 0
You are now punched in
Sa Ka your employee ID is 0 and your clock date and time is: Sun Jun 08 20:19:42 EDT 2014
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):a
Enter your first name: Ka
Enter your last name: Ma
KaMawith employee id1
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):b
Welcome to the punch in/out screen
Enter your employee ID: 1
You are now punched in
Ka Ma your employee ID is 1 and your clock date and time is: Sun Jun 08 20:19:42 EDT 2014
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):c
Welcome to the report screen.
Enter your selection (I = individual report or A= all employees):
a
In Consoldated Report
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):BUILD STOPPED (total time: 1 minute 8 seconds)
So,when I go now to E drive of my Pc I just see a file named output.txt(latest modified time) but there's nothing in it. I tried to close my buffer after the loop but no luck with it. Also, Please advise on reading the data which I wrote to the file
Please advise!
Thanks
I'm not sure if I understand your issue, but like this, you can only write to the file once, since you close it after writing to it. Instead, you can use the flush() method to ensure the contents are written to the file.
Consider reading the documentation at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html.
In my test it works fine . but change bw.close(); to bw.flush(); Because the outputstream will be closed after first input. and att second input you got an exception
Right off the bat I'd suggest trying to replace your file name with E:\output.txt. I believe windows file paths use backslashes.