SavitchIn

Hi,
I am trying to figure out how to utilize the class SavitchIn.java. I have written a very basic program in emacs 21.1.1 running in a terminal on OS X 10.2.3.
The program begins with the import statement which reads: import SavitchIn.*;
I have tried putting the file SavitchIn.java in my home directory but that does not work.
Oh, and I have tried compiling the class before I test my program.
I could use some help. Thanks.

First I'm going to assume that SavitchIn is a class that you have written. If that class does not have a package statment in it then you need to have the file you are trying to use SavitchIn in, in the same folder/directory. If SavitchIn does have a package statement then you need to make sure it is in a path that is the same as its package. Then you would
import package.goes.here.SavitchIn;
The import SavitchIn.*; tells the compiler to look in the package SavitchIn for classes that it does not find elsewhere.
I'm not really familiar with Mac's so I'm not sure if there are other path and classpath issues to deal with.

Similar Messages

  • SavitchIn not found? Need help on first program

    I am using an old Java programming book written by Walter Savitch. I am running a sample program from the book in my NetBeans environment. When I run the thing, it gives me errors on the command SavitchIn. Here is the code:
    package firstprogram;
    * @author mac173
    public class Main {
    * @param args the command line arguments
    public static void main(String[] args) {
    System.out.println("Hello out there.");
    System.out.println("Want to talk some more?");
    System.out.println("Answer y for yes and n for no.");
    char answerLetter;
    answerLetter = SavitchIn.readLineNonwhiteChar();
    if (answerLetter == 'y')
    System.out.println("Nice weather we are having, huh?");
    System.out.println("Good-by.");
    System.out.println("Press any key to end program");
    String junk;
    junk = SavitchIn.readLine();
    The error messages from Netbeans:
    Compiling 1 source file to C:\Users\mac173\Documents\NetBeansProjects\FirstProgram\build\classes
    C:\Users\mac173\Documents\NetBeansProjects\FirstProgram\src\firstprogram\Main.java:23: cannot find symbol
    symbol : variable Savitchin
    location: class firstprogram.Main
    answerLetter = Savitchin.readLineNonwhiteChar();
    C:\Users\mac173\Documents\NetBeansProjects\FirstProgram\src\firstprogram\Main.java:31: cannot find symbol
    symbol : variable Savitchin
    location: class firstprogram.Main
    junk = Savitchin.readLine();
    2 errors
    BUILD FAILED (total time: 0 seconds)
    The book describes SavitchIn as a class to obtain input from the keyboard. I assume the class name and the writers names are the same because the wrote the class. Is this class now obsolete, or did I mess up the code?
    Edited by: mac173 on Aug 1, 2008 7:12 PM

    mac173 wrote:
    I do not want to change books or use the tutorials, because this book was specifically written to teach PROGRAMMING, not just JAVA.Then use the Java tutorials, or one of the other below links, to learn Java, and use that amazing wonderful fantastic most perfect one and only programming teaching book to learn whatever programming concepts the links below don't cover.
    I promise you, though, you'll gain nothing but pain by using outdated Java, and you'll have a harder time getting help. Folks here will provide help and examples based on the current Java language, APIs, and tools.
    If you're serious about learning programming, using an out-of-date book just because it's cheap is not an option.
    Sun's [basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
    Sun's [New To Java Center|http://java.sun.com/learning/new2java/index.html].Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    [http://javaalmanac.com|http://javaalmanac.com]. A couple dozen code examples that supplement [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance].
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's [Thinking in Java|http://mindview.net/Books/DownloadSites] (Available online.)
    Joshua Bloch's [Effective Java|http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=pd_bbs_1?ie=UTF8&s=books&qid=1214349768&sr=8-1]
    Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance].
    James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806]. Gosling is
    the creator of Java. It doesn't get much more authoratative than this.

  • Needs help.....Please about using different classes

    I don't know how to use differenet classes.
    Please tell me how to write class to suit Start. This stuff me up. Please .... help me
    <<My program>>
    //Start
    public class Start
    {  private Artist[] Artists;
    private Record[] records;
    private Person[] Manager;
    private TextMenu makeMenu = new TextMenu();
    public static void main(String[] args)
         Start studio = new Start();
    studio.menu();
    public Start()
    {  //Person.Manager(ManagerName,HouseNumber,StreetNumber,PhoneNumber)
         Manager = new Person[1];
         Manager[0] = new Person("Yangfan",88,"Young ST",11118888);
         //Artist(GroupID,ArtistName,HouseNumber,StreetNumber,PhoneNumber)
         Artists = new Artist[5];
    Artists[0] = new Artist(1,"Backstreet Boys",58,"Music ST",99998888);
    Artists[1] = new Artist(2,"Santana",68,"Music ST",99998899);
    Artists[2] = new Artist(3,"Macy Gray",78,"Music ST",55558888);
    Artists[3] = new Artist(4,"Ricky Martin",88,"Music AVE",77778888);
    Artists[4] = new Artist(5,"Did Rock",55,"Music Road",66667777);
    //Record(RecordingID,RecordName,Artist,StartTime,FinishTime,RecordingDate,GuestArtist1,GuestArtist2)
    records = new Record[6];
    records[0] = new Record(1,"I want it that way",Artists[0],11,12,"05/08/2001",Artists[1],Artists[3]);
    records[1] = new Record(2,"Smooth",Artists[1],11,12,"05/08/2001",Artists[1],"");
    records[2] = new Record(3,"Do something",Artists[2],11,"05/08/2001",Artists[3],"");
    records[3] = new Record(4,"Livin La Vida Loca",Artists[3],11,12,"05/08/2001",Artists[1],Artists[3]);
    records[4] = new Record(5,"Bawitdaba",Artists[4],11,13,"05/08/2001",Artists[1],"");
    records[5] = new Record(6,"The one",Artists[0],11,14,"05/08/2001",Artists[1],"");
    public void menu()
    {  String[] choices = {">>>List Manager Details",">>>List All Artist Names",">>>List An Artist Telephone-Number",">>>Show Details For One Recording",">>>Add A New Recording",">>>List The Recording Costs For All Artists",">>>List Artist's Reocording",">>>Exit Program"};
    while (true)
    {  switch (makeMenu.getChoice(choices))
    {  case 1: showAllArtists();
    break;
    case 2: showAllRecords();
    break;
    case 3: System.exit(0);
    break;
    case 4: System.exit(0);
    break;
    case 5: System.exit(0);
    break;
    case 6: System.exit(0);
    break;
    case 7: System.exit(0);
    break;
    case 8: System.exit(0);
    break;
    default:
    public void showAllArtists()
    {  int numArtists = Artists.length;
    for(int i = 0; i < numArtists; i++)
    {  Artists[i].displayArtistDetails();
    public void showAllRecords()
    {  for (int i = 0; i < records.length; i++)
    {  System.out.println();
    records.printRecordDetails();
    <<Assignment>>
    Due - midnight, Wednesday August 22nd
    This assignment will test your knowledge of Java programming using classes, encapsulation and javadoc.
    The base requirements
    Write a complete Java class to manage a Digital Recording Studio. The studio wants to keep a list of all Artists that use the studio and also wishes to keep track of all Recordings that have been made. An important function of the program is to calculate the time spent making a recording and charge the Artist for the time used.
    You must create at least the following classes, Start, Studio, Person, Artist, Recording, Address. You may create other classes if needed as well
    Start will contain main(), create one instance of a Studio and execute a Menu of commands to test your code. Studio should contain a studio name, an array of Artist and an array of Recording plus the studio manager (a Person). Each Artist should contain the name of the group and an Address. Each Person will have a name and a home address. Each recording will have a Title (usually song title), an Artist (only one), and a list of guestArtist (they are Artist�s but will not receive royalties) the number of the CD the recording is stored on (numbers are numerical and recordings are saved on CD-R), plus the recording start and finish times for the recording session (suggest you use Java Date class � refer to the API). An Address will contain, house number (integers only), a street name and a telephone number. There is no need to store city and country.
    To enter a set of data for testing your program � main() should call a method in the Start class that will fill in a set of values by creating objects and filling in values by calling methods in each class. This is the ONLY method allowed to be longer than 1 page long � normally we would read the data from a file but there are no O-O principles that can be learnt with simply filling in data values. It is suggested to create say at least 4 Artist�s and 6 Recordings (at least one with 1 guest Artist and one with 2 guestArtist�s)
    A menu for testing your program should be provided (it is suggested to put the Menu into a separate class as you need at least 3 menus). While other commands are possible, only the following ones will receive marks.
    Menu commands needed are
    List the Managers name, address and telephone number
    List all Artist Names
    List an Artist telephone number (a sub menu showing valid Artist�s is required)
    Show all details for one Recording ( sub menu of valid Recordings will be needed and remember there can be more than one guestArtist)
    Add a new Recording, user will need to be prompted for all details.
    List the recording costs for all Artists � show each Artist on a separate line with their name and total amount, charge for using the studio is $1000 per hour or part thereof, example for a 1 hour and 10 minute recording the Artist will be billed for 2 hours.
    List all the Recording�s one Artist has worked on (sub menu of Artists needed), the list should show whether they were the Artist or a guestArtist
    Exit program
    Use fixed sizes for arrays, suggest 20 is suitable for all arrays. Java can handle dynamic data structures (where the number of elements can grow or shrink), but that is beyond a first assignment.
    Do NOT make ANY methods static - this defeats the Object Oriented approach and will result in ZERO marks for the entire assignment.
    Data MUST be encapsulated, this means that all the data relating to an object are to be stored INSIDE an object. None of the data detail is to be globally available within your program - hence do not store Artist names in either Studio or Recordings � just store a reference instead. Do NOT create ID numbers for Artists, you should use References instead � for many students this will be the hardest part as you have to use Objects, not program in a C style to solve the problem. Note that if there are any non-private data in classes then zero will given for marks for encapsulation.
    Good programming style is expected (see web page or lecture notes). In particular, you must use javadoc to generate a set of html pages for your classes. Make sure you use the special javadoc style comments in your source code. Marks will be granted for both using javadoc and also for including sensible javadoc comments on each class and each public method.
    What to Hand In
    Read the turnin page, basically the .java files, a readme.txt to tell the marker which file the program starts from plus the javadoc (html) files. Do NOT send .class files (if you do send these we will delete them and recompile your program), do NOT compress with gtar, tar, zip or use any other tool on your files. Turnin automatically compresses all your files into a single archive for us to mark.
    The simplest way to turnin all your files is to place all files in one directory then just use the *.* wildcard to turn in all files within that one directory.
    You must turnin all files that are not part of Java 1.3. In particular, you are allowed (actually encouraged) to use EasyIn or SavitchIn but should include the one you use in the files you submit. It is STRONGLY suggested that you copy all the files into another directory, test it works there by compiling and executing then turnin files from that directory. A common problem is students adding comments at the last minute then not testing if it still compiles. The assignment will be marked as submitted � no asking later for leniency because you added comments at the last minute and failed to check if it still worked.
    If the tutors are unable to compile your submission, they will mark the source code but you will lose all the execution marks. Sorry, but it is your responsibility to test then hand in all files.
    Comments
    For CS807 students, this program should be fairly easy if it was to be programmed in C (you would use several struct). The real art here is to change over to programming objects. Data is contained in an object and is not global. This idea is essential to using Java effectively and is termed encapsulation. Instead of using function(data), you use objectName.method( ). Effectively you switch the data and functions around, the data has a method (function) attached to it, not the other way around as in C (where you have a function and send data to it).
    While there will be some marks for execution, the majority of the marks will be given for how well you write your code (including comments and documentation) and for how well you used O-O principles. Programs written in a C style with most of the code in one class or using static will receive ZERO marks regardless of how well they work.
    You are responsible for checking your turnin by reading the messages turnin responds with. Failure to read these messages will not be an acceptable excuse for submitting an incorrect assignment. About 2% of assignments sent to turnin are unreadable (usually empty) and obtain 0.
    Late submissions
    Late submissions will only be accepted with valid reasons for being late. All requests for assignment extensions must be made via email to the lecturer. Replies for acceptance or refusal will made by email. Instant replies are unrealistic (there is usually a flood of queries into my mail box around assignment due dates) and the best advice is to ask at least 4 days in advance so that you will have a reasonable chance of getting a timely reply and allow yourself enough time to submit something on time if the extension is not granted.
    ALL late submissions will be marked LAST and will NOT be sent to tutors for marking until all other assignments have been marked. As an example, if you submit late and your assignment is not yet marked by the time assignment 2 is due then it will be pushed to the end of the marking pile as the assignments that were submitted on time for assignment 2 will take priority.
    If you make a second submission after the submission date, only the first submission will be marked. We will not mark assignments twice! You can update your submission BEFORE the submission date if you need to - this will just overwrite the first submission. The latest time for a late submission is 5pm on the Wednesday after the due date. This is because, either a solution will be handed out at that lecture or details of the assignment will be discussed at the lecture. I cannot accept any assignment submissions after that time for any reason at all including medical or other valid reasons. For those who are given permission to be later than the maximum submission time � a different assignment will be handed out. Remember, if you decide to submit late you are VERY UNLIKELY to receive feedback on your assignments during semester.
    Assignments will be removed from turnin and archived elsewhere then forwarded to tutors for marking on the morning after the assignment is due. A different tutor will mark each of your assignments � do not expect the tutor you see at the tutorials to be your marker.
    Marks will be returned via email to your computer science yallara account � ideally within 2 weeks. I will send marks out when I receive them so do not send email asking where your marks are just because a friend has theirs. If you want your email forwarded to an external account, then place a valid .forward file into your yallara account. The Help Desk on level 10 can assist you in setting this up if you do not know how to do it.

    I have seen other people who have blatantly asked for
    other people to do their homework for them, but you
    are the first person I've seen to actually cut and
    paste the entire assignment as it was handed to you.
    Amazing.
    Well, unlike some of the people you're talking about, it seems like zyangfan did at least take a stab at it himself, and does have a question that is somewhat more sepcific that "please do this homework for me."
    Zyangfan,
    marendoj is right, though. Posting the entire assignment is kind of tacky. If you want to post some of it to show us what you're trying to do, please trim it down to the essential points. We don't need to see all the instructor's policies and such.
    Anyway, let me see if I understand what you're asking. You said that you know how to write the code, but only by putting it all in one class, is that right? What part about using separate classes do you not understand? Do you not know how to make code in one class aware that the other class exists? Do you not know how code in class A can call a method in class B?
    Please be a bit more specifice about what you don't understand. And at least try using multiple classes, then when you can't figure out why something doesn't work, explain what you did, and what you think should have happened, and what did happen instead.
    To get you started on the basics (and this should have been covered in your course), you write the code for two classes just like for one class. That is, for class A, you create a file A.java and compile it to A.class. For class B, you create a file B.java and compile it to B.class. Given how rudimentary you question is, we'll skip packages for now. Just put all your class files in the same directory, and don't declare packages in the .java files.
    To call a method in class B from code that's in class A, you'll need an object of class B. You instantiate a B, and then call its methods.
    public class B {
      int count;
      public B() { // constructor
      public void increment() {
        count++;
    public class A {
      public static void main(String args[]) {
        B b = new B();
        b.increment();
    }Is this what you were asking?

  • Writing a Vector to a Output File Line by Line.

    Can anyone tell me how to write each element of the Vector on a New Line to the Output file? Right now the Output is in a String across 1 line.
    Now - � t Bowser 5 years 105 lbs.t Bowser 5 years 106 lbs.t Daisy 1 year 30 lbs.t Dog 1 yr 66 lbs.t King 6 years 77 lbs.t Nikki 5 years 68 lbs.
    Here is what I need -
    Bowser 5 years 106 lbs.
    Bowser 5 years 105 lbs.
    Rover 7 years 88 lbs.
    Dog 1 yr 66 lbs.
    King 6 years 77 lbs.
    Nikki 5 years 68 lbs.
    Daisy 1 year 30 lbs.
    Do a find on // Writes Vector Object to a file
    Thank You in advance.
    import java.io.*;
    import java.awt.*;
    import java.util.*;
    public class VectorSort
    Vector v;
    private DataInputStream inputStream = null;
    private ObjectOutputStream outputStream = null; // <== this is for a Vector
    // private DataOutputStream outputStream = null; // <== This is for a Textfile
    (1) Read in Pet Records put them in a Vector, Sort them Print them.
    public static void main(String[] args) throws java.io.IOException
    VectorSort newVector = new VectorSort();
    newVector.connectToInputFile();
    newVector.connectToOutputFile();
    newVector.readInput();
    newVector.sortPrint();
    newVector.closeFiles();
    System.out.println(" ");
    System.out.println("Check A:/DataOut.txt Now");
    public void connectToInputFile()
    String inputFileName = getFileName("Enter input file name: A://DataIn.txt");
    try
    inputStream = new DataInputStream(new FileInputStream(inputFileName));
    catch(FileNotFoundException e)
    System.out.println("File " + inputFileName + " not found.");
    System.exit(0);
    public void connectToOutputFile()
    String outputFileName = getFileName("Enter output file name: A://DataOut.txt");
    try
    outputStream = new ObjectOutputStream( // <== this is for a Vector
    // outputStream = new DataOutputStream( // <== this is for a Textfile
    new FileOutputStream(outputFileName));
    catch(IOException e)
    System.out.println("Error opening output file "
    + outputFileName);
    System.out.println(e.getMessage());
    System.exit(0);
    private String getFileName(String prompt)
    String fileName = null;
    System.out.println(prompt);
    fileName = SavitchIn.readLineWord();
    return fileName;
    //===========================================================================
    public void readInput()
    v = new Vector ();
    try
    String result = "";
    boolean done = false;
    int ctr = 0;
    String next;
    next = inputStream.readLine();
    while ( next != null)
    v.addElement( next.trim() );
    next = inputStream.readLine();
    catch(EOFException e)
    //Do nothing. This just ends the loop.
    System.out.println("Do Nothing Here");
    catch(IOException e)
    System.out.println(
    "Error: reading or writing files.");
    System.out.println(e.getMessage());
    System.exit(0);
    public void sortPrint()
    Collections.sort(v);
    int vsize = v.size();
    for (int j = 0; j < vsize - 1 ; j++)
    try
    outputStream.writeObject(v.elementAt(j)); // Writes Vector Object to a file
    System.out.println(v.elementAt(j));
    catch(IOException e)
    System.out.println("Error Writing Output "
    + e.getMessage());
    System.exit(0);
    public void closeFiles()
    try
    outputStream.flush(); // <== force the buffer to write
    inputStream.close();
    outputStream.close();
    catch(IOException e)
    System.out.println("Error closing files "
    + e.getMessage());
    System.exit(0);

    // did you try with java.io.PrintWriter
    // here is simple method to write file from vector.
    // you need to change obtaining your string value at the vector loop
    private void writeDataLog(Vector vector, String filename)
    try
    PrintWriter pw = new PrintWriter(new FileWriter(filename, true));     
    if (vector.size()>0)
    for (int i=0; i<vector.size(); i++)
    { String str = ((your object)vector.get(i)).getYourString();
    pw.println( str );
    pw.close();
    catch(Exception e)
    { System.out.print(e.toString()); }
    }

  • Got another problem PLEASE HELP

    this is what i have....it reads test scores then prints the min max and average.....also categorizes the grades into a, b, c, d, f......and gives what percent of the test scores are these grades....so far it doesn't read the right amount of grades....percents remain at 0...and the max and min is wrong...any ideas?
    public class ReadGrades5
    public static double next;
    public static void main(String[] args)
    int numberOfA, numberOfB, numberOfC, numberOfD, numberOfF;
    int numberOfStudents;
    double sum, max, min;
    char answer;
    do
    System.out.println("Please enter the list of Exam Scores.");
    System.out.println("Enter a negative number to exit.");
    max = 0;
    min = 0;
    sum = 0;
    numberOfStudents = 0;
    numberOfA = 0;
    numberOfB = 0;
    numberOfC = 0;
    numberOfD = 0;
    numberOfF = 0;
    next = SavitchIn.readLineDouble();
    while (next>=0)
    if(next < min)
    min = next;
    if(next > max)
    max = next;
    if (min <= 0)
    min = 100;
    sum = sum + next;
    numberOfStudents++;
    next = SavitchIn.readLineDouble();
    if (next>=90)
    numberOfA++;
    numberOfStudents++;
    else if (next>=80)
    numberOfB++;
    numberOfStudents++;
    else if (next>=70)
    numberOfC++;
    numberOfStudents++;
    else if (next>=60)
    numberOfD++;
    numberOfStudents++;
    else if (next<60)
    numberOfF++;
    numberOfStudents++;
    next = SavitchIn.readLineDouble();
    if (next < 0)
    System.out.println("Total number of grades = " +numberOfStudents);
    System.out.println("Number of A's = " + numberOfA + " " +(numberOfA/(int)numberOfStudents)*100 + "%");
    System.out.println("Number of B's = " + numberOfB+ " " +(numberOfB/(int)numberOfStudents)*100 + "%");
    System.out.println("Number of C's = " + numberOfC+ " " +(numberOfC/(int)numberOfStudents)*100+ "%");
    System.out.println("Number of D's = " + numberOfD+ " " +(numberOfD/(int)numberOfStudents)*100+ "%");
    System.out.println("Number of F's = " + numberOfF+ " " +(numberOfF/(int)numberOfStudents)*100+ "%");
    System.out.println("The average score is " + (sum/numberOfStudents));
    System.out.println("The highest score is " + max);
    System.out.println("The lowest score is " + min);
    else
    System.out.println("Please enter the grades.");
    System.out.println("");
    System.out.println("Do you want to input more scores?");
    System.out.println("Enter y for yes or n for no.");
    answer = SavitchIn.readLineNonwhiteChar();
    }while ((answer == 'y') || (answer == 'Y'));
    }

    Upon request from someone besides ^^you^^ (don't mean to offend you by not following what you said)
    this is what i have
    public class ReadGrades5
    public static double next;
    public static void main(String[] args)
    int numberOfA, numberOfB, numberOfC, numberOfD, numberOfF;
    int numberOfStudents;
    int studentsForPercent;
    double sum, max, min;
    char answer;
    do
    System.out.println("Please enter the list of Exam Scores.");
    System.out.println("Enter a negative number to exit.");
    max = 0;
    min = 0;
    sum = 0;
    numberOfStudents = 0;
    studentsForPercent = 0;
    numberOfA = 0;
    numberOfB = 0;
    numberOfC = 0;
    numberOfD = 0;
    numberOfF = 0;
    next = SavitchIn.readLineDouble();
    while (next>=0)
    if(next < min)
    min = next;
    if(next > max)
    max = next;
    sum = sum + next;
    numberOfStudents++;
    next = SavitchIn.readLineDouble();
    while (next>=0)
    if(next !< 0)
    sum = sum + next;
    if (next>=90)
    numberOfA++;
    studentsForPercent++;
    else if (next>=80)
    numberOfB++;
    studentsForPercent++;
    else if (next>=70)
    numberOfC++;
    studentsForPercent++;
    else if (next>=60)
    numberOfD++;
    studentsForPercent++;
    else if (next<60)
    numberOfF++;
    studentsForPercent++;
    next = SavitchIn.readLineDouble();
    if (next < 0)
    System.out.println("Total number of grades = " +numberOfStudents);
    System.out.println("Number of A's = " + numberOfA + " " +(numberOfA/(double)studentsForPercent)*100 + "%");
    System.out.println("Number of B's = " + numberOfB+ " " +(numberOfB/(double)studentsForPercent)*100 + "%");
    System.out.println("Number of C's = " + numberOfC+ " " +(numberOfC/(double)studentsForPercent)*100+ "%");
    System.out.println("Number of D's = " + numberOfD+ " " +(numberOfD/(double)studentsForPercent)*100+ "%");
    System.out.println("Number of F's = " + numberOfF+ " " +(numberOfF/(double)studentsForPercent)*100+ "%");
    System.out.println("The average score is " + (sum/numberOfStudents));
    System.out.println("The highest score is " + max);
    System.out.println("The lowest score is " + min);
    else
    System.out.println("Please enter the grades.");
    System.out.println("");
    System.out.println("Do you want to input more scores?");
    System.out.println("Enter y for yes or n for no.");
    answer = SavitchIn.readLineNonwhiteChar();
    }while ((answer == 'y') || (answer == 'Y'));

  • Read txt file 1 char @ time cnvrt to uppercase problem

    I am trying to get the following 2 problems solved. My input file is below and my output is below along with the code.
    Can anyone fix this and explain what I am doing wrong? Thank You in advance!
    (1) Any string of two or more blanks symbols is replaced by a single blanks.
    (2) All sentences start with an upper case letter.
    Input A://DataIn.txt = How me? you good.
    Output A://DataOut.txt = H o w m e Y U G O . ��
    import java.io.*;
    public class NumberFormat
    private DataInputStream inputStream = null;
    private DataOutputStream outputStream = null;
    *(1) Any string of two or more blanks symbols is replaced by a single blanks.
    (2) All sentences start with an upper case letter.
    public static void main(String[] args) throws java.io.IOException
    NumberFormat twoTimer = new NumberFormat();
    twoTimer.connectToInputFile();
    twoTimer.connectToOutputFile();
    twoTimer.readInput();
    twoTimer.closeFiles();
    System.out.println("Check A:/DataOut.txt Now");
    public void connectToInputFile()
    String inputFileName = getFileName("Enter input file name: A://DataIn.txt");
    try
    inputStream =
    new DataInputStream(
    new FileInputStream(inputFileName));
    catch(FileNotFoundException e)
    System.out.println("File " + inputFileName
    + " not found.");
    System.exit(0);
    public void connectToOutputFile()
    String outputFileName = getFileName("Enter output file name: A://DataOut.txt");
    try
    outputStream = new DataOutputStream(
    new FileOutputStream(outputFileName));
    catch(FileNotFoundException e)
    System.out.println("Error opening output file "
    + outputFileName);
    System.out.println(e.getMessage());
    System.exit(0);
    private String getFileName(String prompt)
    String fileName = null;
    System.out.println(prompt);
    fileName = SavitchIn.readLineWord();
    return fileName;
    //===========================================================================
    public void readInput()
    char prevChar = ' ';
    try
    char nextChar;
    String result = "";
    boolean done1 = false;
    boolean done2 = false;
    char next;
    do
    next = (char) (inputStream.read()); // <== Read input 1 Character @ time
    if (next == '\n')
    done1 = true;
    if (next == ' ' && next == prevChar)
    prevChar = next;
    else
    if (next == '.' || next == '!' || next == '?')// <== Capitalize next input Character
    do
    next = ' ';
    outputStream.writeChar(next);
    next = (char) (inputStream.read());
    if (next == '\n')
    done2 = true;
    next = (char) (inputStream.read());
    // next = (char) (inputStream.readNonwhiteChar()); ?????????????
    if (next == '\n')// <== never gets to end of file
    done2 = true;
    outputStream.writeChar(Character.toUpperCase (next));
    prevChar = next;
    while (!done2);
    else
    outputStream.writeChar(next);
    prevChar = next;
    while (!done1);
    catch(EOFException e)
    //Do nothing. This just ends the loop.
    System.out.println("Do Nothing Here");
    catch(IOException e)
    System.out.println(
    "Error: reading or writing files.");
    System.out.println(e.getMessage());
    System.exit(0);
    public void closeFiles()
    try
    inputStream.close();
    outputStream.close();
    catch(IOException e)
    System.out.println("Error closing files "
    + e.getMessage());
    System.exit(0);

    This line looks fishy:
    if (next == ' ' && next == prevChar)
    prevChar = next;Try:
    if (next == ' ' && next == prevChar)
    next = "";That should take care of the extra blanks, though I didn't test it myself, and could very well be wrong.
    Not sure about the uppercase, though I imagine it must be reading the ToUpperCase every time after the first period.

  • How do I get the methods to respond to my main program?

    I have created 3 classes,where class Kunde is my base class and class PudsPrAreal and PudsPrTid are derived classes from class Kunde.
    All my classes went through my compiler without error, but my main program is not able to read the methods from my classes.How do I fix that??
    my base class:
    navn = nyNavn;
    adresse = nyAdresse;
    rabat = nyRabat;
    public void readInput()
    System.out.println("Indtast kundens navn:");
    navn = SavitchIn.readLine();
    System.out.println("Indtast kundens adresse:");
    adresse = SavitchIn.readLine();
    System.out.println("Modtager " + navn + " en form for rabat?");
    System.out.println("(j/n):");
    char answer = SavitchIn.readNonwhiteChar();
    if (answer == 'j'||answer == 'J')
    System.out.println("Indtast den procentsats som " + navn + " modtager:");
    rabat = SavitchIn.readLineDouble();
    public void writeOutput()
    System.out.println("Navn: " + navn);
    System.out.println("Adresse: " + adresse);
    if (rabat > 0)
    System.out.println("Rabat: " + rabat);
    public Kunde()
    navn = "no record";
    adresse = "no record";
    rabat = 0;
    public String getNavn()
    return navn;
    public String getAdresse()
    return adresse;
    public double getRabat()
    return rabat;
    derived class # 1:
    public class PudsPrAreal extends Kunde
    private double areal; //i kvadratmeter
    private String kunde;
    private String pudsningsdato;
    private double kvadratmeterPris;
    private double pris;
    public PudsPrAreal()
    super();
    kunde = "no record";
    pudsningsdato = "no record";
    kvadratmeterPris = 0;
    pris = 0;
    areal = 0;
    public PudsPrAreal(String initialKunde, String initialPudsningsdato, double initialAreal,
    String initialNavn, String initialAdresse, double initialRabat)
    super(initialNavn, initialAdresse, initialRabat);
    set(initialKunde, initialPudsningsdato, initialAreal);
    public void set(String nyKunde, String nyPudsningsdato, double nyAreal)
    kunde = nyKunde;
    pudsningsdato = nyPudsningsdato;
    areal = nyAreal;
    public void readInputPrAreal()
    System.out.println("Indtast datoen hvor vinduespudsningen er blevet foretaget:");
    pudsningsdato = SavitchIn.readLine();
    System.out.println("Hvor mange kvadratmeter skal der afregnes for:");
    areal = SavitchIn.readLineDouble();
    public double pris(double areal)
    double pris;
    double kvadratmeterPris;
    if (areal > 100)
    kvadratmeterPris = 7.0;
    else if (areal >= 500)
    kvadratmeterPris = 6.5;
    else
    kvadratmeterPris = 6.0;
    double prisEks = areal * kvadratmeterPris; //pris eksclusiv rabat
    pris = prisEks * ((100 - getRabat())/100); //pris inclusiv rabat
    return pris;
    public void writeOutputPrAreal()
    System.out.println("Dato for vinduespudsning: " + pudsningsdato);
    System.out.println("Navn: " + getNavn());
    System.out.println("Adresse: " + getAdresse());
    System.out.println("Prisberegningsgrundlag: pr kvadratmeter");
    System.out.println("Antal kvadratmeter: " + areal);
    System.out.println("Pris pr kvadratmeter: " + kvadratmeterPris + " kr.");
    if (getRabat() > 0)
    System.out.println("Rabat: " + getRabat());
    System.out.println("Pris for vinduespudsningen: " + pris + "kr.");
    else
    System.out.println("Pris for vinduespudsningen: " + pris + "kr.");
    public String getkunde()
    return kunde;
    public String getPudsningsdato()
    return pudsningsdato;
    public double getAreal()
    return areal;
    derived class # 2:
    public class PudsPrTime extends Kunde
    private int minuter; //tid for vinduespudsningen angives i minuter
    private double tid; //tid for vinduespudsningen i timer
    private String kunde;
    private String pudsningsdato;
    private double pris;
    public PudsPrTime(String initialKunde, String initialPudsningsdato, int initialMinuter,
    String initialNavn, String initialAdresse, double initialRabat)
    super(initialNavn, initialAdresse, initialRabat);
    set(initialKunde, initialPudsningsdato, initialMinuter);
    public void set(String nyKunde, String nyPudsningsdato, int nyMinuter)
    kunde = nyKunde;
    pudsningsdato = nyPudsningsdato;
    minuter = nyMinuter;
    public void readInputPrTime()
    System.out.println("Indtast datoen hvor vinduespudsningen er blevet foretaget:");
    pudsningsdato = SavitchIn.readLine();
    System.out.println("Hvor mange minuter skal der afregnes for:");
    minuter = SavitchIn.readLineInt();
    public double pris(int minuter)
    int kvarter;
    int minuterTilOvers;
    double pris;
    kvarter = minuter / 15;
    minuterTilOvers = minuter % 15;
    if (minuterTilOvers > 0)
    kvarter++;
    tid = kvarter * 0.25;
    double prisEks = tid * 375; //pris eksclusiv rabat
    pris = prisEks * ((100 - getRabat())/100);
    return pris;
    public void writeOutputPrTime()
    System.out.println("Dato for vinduespudsning: " + pudsningsdato);
    System.out.println("Navn: " + getNavn());
    System.out.println("Adresse: " + getAdresse());
    System.out.println("Prisberegningsgrundlag: pr time");
    System.out.println("Antal timer: " + tid);
    System.out.println("Pris pr time: 375 kr.");
    System.out.println("Der afregnes pr p�begyndt 15 minuter.");
    if (getRabat() > 0)
    System.out.println("Rabat: " + getRabat());
    System.out.println("Pris for vinduespudsningen: " + pris + "kr.");
    else
    System.out.println("Pris for vinduespudsningen: " + pris + "kr.");
    public String getKunde()
    return kunde;
    public String getPudsningsdato()
    return pudsningsdato;
    public int getMinuter()
    return minuter;
    my main program:
    public class Glasklart
    public static void main(String[] args)
    Glasklart kunde = new Glasklart();
    System.out.println("Indtast datoen for idag:");
    String dato = SavitchIn.readLine();
    kunde.readInput();
    System.out.println("Hvad er prisberegningsgrundlaget?");
    System.out.println("Skriv 'k' for pr kvadratmeter eller 't' for pr time:");
    char svar = SavitchIn.readNonwhiteChar();
    if (svar == 'k'||svar == 'K')
    kunde.readInputPrAreal();
    System.out.println("Afregningsdato: " + dato);
    kunde.writeOutputPrAreal();
    else if (svar == 't'||svar == 'T')
    kunde.readInputPrTime();
    System.out.println("Afregningsdato: " + dato);
    kunde.writeOutputPrTime();
    else
    System.out.println("Forkert svar. Pr�v igen.");
    System.out.println("Skriv 'k' for pr kvadratmeter eller 't' for pr time:");
    svar = SavitchIn.readNonwhiteChar();
    error message for my main program:
    "Glasklart.java": Error #: 300 : method readInput() not found in class Glasklart at line 10, column 9
    "Glasklart.java": Error #: 300 : method readInputPrAreal() not found in class Glasklart at line 16, column 13
    "Glasklart.java": Error #: 300 : method writeOutputPrAreal() not found in class Glasklart at line 18, column 13
    "Glasklart.java": Error #: 300 : method readInputPrTime() not found in class Glasklart at line 22, column 13
    "Glasklart.java": Error #: 300 : method writeOutputPrTime() not found in class Glasklart at line 24, column 13

    The problem is that your main class isn't even trying to read the methods in your other classes. In your main() method in Glasklart.java, you do this:
    Glasklart kunde = new Glasklart();
    System.out.println("Indtast datoen for idag:");
    String dato = SavitchIn.readLine();
    kunde.readInput();But you didn't define readInput() in Glasklart, you defined it in your "base class" which you didn't quote enough of us to know the name for sure, but I presume is called Kunde.java.
    But I also see that you named the variable "kunde". It looks like maybe you're confusing the names of classes with the names of variables that happen to hold objects instantiated from those classes.
    If I define classes:
    public class Dog {
    public class Cat {
    }and later do this:
      Cat dog = new Cat();The methods defined in Dog cannot be invoked from from "dog", because "dog" is really a Cat. Just because you called it "dog", it doesn't necesarily mean it's an instance of Dog.

  • Accessor methods

    Hello,
    I am working on a temp class that has 2 instance variables, double tempValue, and char tempScale ('C' or 'F').
    My constructor methods are working fine. My mutator (set) methods are working fine.
    I need to write two accessor methods, one that returns the temp in Fahrenheit, and one that returns the temp in Celsius.
    I am not sure how to return both the tempValue and the tempScale for both of these methods. Here is my starting point:
    //accessor method to return the degrees Fahrenheit.
    public double getF()
    return tempF;     //tempF = (9*(tempC)/5 + 32)
    //accessor method to return the degrees Celsius
    public double getC()
    return tempC;     //tempC = 5*(tempF - 32)/9
    }Thank you,
    Eric

    If possible, I would like to stick to the program I am working on. It is much easier for me to understand.
    Is there any way you can just use my program as the example?
    Here is what I have so far:
    public class TestTemp
    //Two parameters, a temperature value (a floating-point number)
    //and a character for the scale, either 'C' for Celsius or 'F'
    //for Fahrenheit.
    private double tempValue;     //in degrees
    private char tempScale;     //in either 'C' or 'F'     
    public void writeOutput()
    System.out.println("The temperature is " + (tempValue) + " degrees " + tempScale + ".");
    //Four constructor methods, one for each instance variable,
    //(assume zero degrees if no value isspecified and Celsius
    // if no scale is specified), one with two parameters for the
    //two instance variables, and a default constructor (set to
    //zero degreees Celsius.
    //constructor method for the instance variable tempValue
    public TestTemp(double initialTempValue)
    tempScale = 'C';
    if(initialTempValue < 0)
    System.out.println("Error:  Negative temperature value.");
    System.exit(0);
    else
    round(initialTempValue);
    tempValue = initialTempValue;
    //constructor method for the instance variable tempScale
    public TestTemp(char initialTempScale)
    tempValue = 0;
    initialTempScale = Character.toUpperCase(initialTempScale);
    if(initialTempScale == 'C' || initialTempScale == 'F')
    tempScale = initialTempScale;
    else
    System.out.println("Error:  Must be C or F.");
    System.exit(0);
    //constructor method for both instance variables tempValue and tempScale
    public TestTemp(double initialTempValue, char initialTempScale)
    if(initialTempValue < 0)
    System.out.println("Error:  Negative temperature value.");
    System.exit(0);
    else
    round(initialTempValue);
    tempValue = initialTempValue;
    initialTempScale = Character.toUpperCase(initialTempScale);
    if(initialTempScale == 'C' || initialTempScale == 'F')
    tempScale = initialTempScale;
    else
    System.out.println("Error:  Must be C or F.");
    System.exit(0);
    //default constructor method
    public TestTemp()
    tempValue = 0.0;
    tempScale = 'C';     
    //Two accessor (get) methods, one to return the degrees Celsius,
    //and one to return the degrees Fahrenheit.
    //Round to the nearest tenth of a degree.
    //accessor method to return the degrees Fahrenheit.
    public double getF()
    if(tempScale == 'F')
    System.out.println("Error:  The temp scale is already Fahrenheit.");
    return 0;
    else
    double tempF;
    tempF = ((9 * tempValue)/5 + 32);  //tempF = ((9*tempC)/5 + 32)
    tempValue = tempF;
    tempScale = 'F';
    round(tempValue);
    return tempF;          
    //accessor method to return the degrees Celsius
    public double getC()
    if(tempScale == 'C')
    System.out.println("Error:  The temp scale is already Celsius.");
    return 0;
    else
    double tempC;
    tempC = (5 * (tempValue - 32)/9);          //tempC = 5*(tempF - 32)/9
    tempValue = tempC;
    tempScale = 'C';
    round(tempValue);
    return tempC;     
    //round method returns the tempValue rounded to tenths
    public double round(double roundTempValue)
    tempValue = Math.round(tempValue * 10.0)/10.0;
    return tempValue;
    //Three reset methods, one to reset the value, one to reset the
    //scale ('F' or 'C'), and one to reset both the value and the scale.
    //reset method to reset tempValue
    public void set(double newTempValue)
    if(newTempValue < 0)
    System.out.println("Error:  Negative temperature value.");
    System.exit(0);
    else
    round(newTempValue);
    tempValue = newTempValue;
    //tempScale is unchanged
    //reset method to reset tempScale
    public void set(char newTempScale)
    newTempScale = Character.toUpperCase(newTempScale);
    if(newTempScale == 'C' || newTempScale == 'F')
    tempScale = newTempScale;
    else
    System.out.println("Error:  Must be C or F.");
    System.exit(0);
    //tempValue is unchanged
    //reset method to reset tempValue and tempScale
    public void set(double newTempValue, char newTempScale)
    if(newTempValue < 0)
    System.out.println("Error:  Negative temperature value.");
    System.exit(0);
    else
    round(newTempValue);
    tempValue = newTempValue;
    newTempScale = Character.toUpperCase(newTempScale);
    if(newTempScale == 'C' || newTempScale == 'F')
    tempScale = newTempScale;
    else
    System.out.println("Error:  Must be C or F.");
    System.exit(0);
    //tempValue and tempScale are reset
    //Driver program that tests all the methods.
    //Use each one of the constructors.
    //Include at least one true and one false
    //case for each of the comparison methods.
    //Test the following: 
    //          0.0 degrees C = 32 degrees F
    //          -40 degrees C = -40 degrees F
    //          100 degrees C = 212 degrees F     
    public class TestTempDriver
    public static void main(String[] args)
    //t1, t2, t3, and t4 test the four constructors
    TestTemp t1 = new TestTemp();
    t1.writeOutput();
    TestTemp t2 = new TestTemp(22.222);
    t2.writeOutput();
    TestTemp t3 = new TestTemp('f');
    t3.writeOutput();
    TestTemp t4 = new TestTemp(44.444, 'f');
    t4.writeOutput();
    //t5 tests the set method with both the double and char parameters
    TestTemp t5 = new TestTemp(55.555, 'f');
    System.out.println("The initial temp for t5 is:");
    t5.writeOutput();          
    System.out.println("Please enter the correct temp:");
    double correctTemp = SavitchIn.readLineDouble( );
    System.out.println("Please enter the correct temp scale:");
    char correctScale = SavitchIn.readLineNonwhiteChar( );
    t5.set(correctTemp, correctScale);
    System.out.println("The updated temp for t5 is:");
    t5.writeOutput();          
    //t6 tests the set method with the double parameter
    TestTemp t6 = new TestTemp(66.666, 'f');
    System.out.println("The initial temp for t6 is:");
    t6.writeOutput();
    System.out.println("Please enter the correct temp:");
    correctTemp = SavitchIn.readLineDouble( );
    t6.set(correctTemp);
    System.out.println("The updated temp for t6 is:");
    t6.writeOutput();
    //t7 tests the set method with the char parameter
    TestTemp t7 = new TestTemp(77.777, 'f');
    System.out.println("The initial temp for t7 is:");
    t7.writeOutput();
    System.out.println("Please enter the correct temp scale:");
    correctScale = SavitchIn.readLineNonwhiteChar( );
    t7.set(correctScale);
    System.out.println("The updated temp for t7 is:");
    t7.writeOutput();
    //t8 tests the getF accessor method
    TestTemp t8 = new TestTemp();     
    double convertTemp = 88.888;
    char convertScale = 'c';
    t8.set(convertTemp, convertScale);
    t8.getF();     
    t8.writeOutput();
    //t9 tests the getC accessor method
    TestTemp t9 = new TestTemp();
    convertTemp = 99.999;
    convertScale = 'f';
    t9.set(convertTemp, convertScale);
    t9.getC();     
    t9.writeOutput();
    }Thanks,
    Eric

  • Logical error 2nd Edition... :~(

    here is the 2nd edition of the program.
    it runs wired, i can't exactly tell how, but the way it does just like lost-control.
    copy it and give it a try see if you have any idea what's going on.
    p.s. all called methods are sticked after the main program.
    class DecodeDriver
         public static void main(String[] args)
              char keyin;
              do
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            M A I N   M E N U             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** M) Morse Code                            **");
                   sop("** C) Caesar Cipher                         **");
                   sop("** V) Vignere Cipher                        **");
                   sop("** P) Playfair Cipher                       **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Exit Program                          **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select an encoding scheme: ");
                   keyin = SavitchIn.readNonwhiteChar();
                   switch(keyin)
                   case'M':
                   case'm': Morse();
                        break;
                        case'C':
                   case'c': Caesar();
                        break;
                        case'V':
                   case'v': Vignere();
                        break;
                        case'P':
                   case'p': Playfair();
                        break;
                        case'X':
                        case'x': sop("Thanks for using! Bye!");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } //switch
              } // do
              while(keyin != 'X' && keyin != 'x');
              System.exit(0);
         } // main
              public static void Morse()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            Morse Code Menu               **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': MorseCode.encode();
                        break;
                        case'D':
                        case'd': MorseCode.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                                       break;
                   } // switch
              } //Morse
              private static void Caesar()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Caesar Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': CaesarCipher.encode();
                        case'D':
                        case'd': CaesarCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //CaesarCipher
              private static void Vignere()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Vignere Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': VignereCipher.encode();
                        case'D':
                        case'd': VignereCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //VignereCipher          
              private static void Playfair()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**          Playfair Cipher Menu            **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': PlayfairCipher.encode();
                        case'D':
                        case'd': PlayfairCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //PlayfairCipher     
              private static void sop(String newString)
                   System.out.println(newString);
              } // sop
    } //class
    (part of)the SavitchIn input stuff:
        public static char readNonwhiteChar( )
          char next;
          next = readChar( );
          while (Character.isWhitespace(next))
              next = readChar( );
          return next;
         The following methods are not used in the text, except
         for a brief reference in Chapter 2. No program code uses
         them. However, some programmers may want to use them.
         Precondition: The next input in the stream consists of
         an int value, possibly preceded by whitespace, but
         definitely followed by whitespace.
         Action: Reads the first string of nonwhitespace characters
         and returns the int value it represents. Discards the
         first whitespace character after the word. The next read
         takes place immediately after the discarded whitespace.
         In particular, if the word is at the end of a line, the
         next read will take place starting on the next line.
         If the next word does not represent an int value,
         a NumberFormatException is thrown.
    MorseCode.java - for debugin' propose.
    class MorseCode
       public MorseCode()
          sop("unfinished - const.");
         }//const.
         public static void encode()
              sop("unfinished - encode");
              char newchar;
              newchar = SavitchIn.readChar();
              System.out.println(newchar);
         public static void decode()
              sop("unfinished - decode");
         private static void sop(String newString)
              System.out.println(newString);
         } // sop
    }//class

    aside from the missing breaks?
    encode OR decode
    case'E':
    case'e': CaesarCipher.encode();
    break;
    case'D':
    case'd': CaesarCipher.decode();
    break;looks better this time?
    class DecodeDriver
         public static void main(String[] args)
              char keyin;
              do
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            M A I N   M E N U             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** M) Morse Code                            **");
                   sop("** C) Caesar Cipher                         **");
                   sop("** V) Vignere Cipher                        **");
                   sop("** P) Playfair Cipher                       **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Exit Program                          **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select an encoding scheme: ");
                   keyin = SavitchIn.readNonwhiteChar();
                   switch(keyin)
                   case'M':
                   case'm': Morse();
                        break;
                   case'C':
                   case'c': Caesar();
                        break;
                   case'V':
                   case'v': Vignere();
                        break;
                   case'P':
                   case'p': Playfair();
                        break;
                   case'X':
                   case'x': sop("Thanks for using! Bye!");
                        break;
                   default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } //switch
              } // do
              while(keyin != 'X' && keyin != 'x');
              System.exit(0);
         } // main
              public static void Morse()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            Morse Code Menu               **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': MorseCode.encode();
                        break;
                        case'D':
                        case'd': MorseCode.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //Morse
              private static void Caesar()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Caesar Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin =  SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': CaesarCipher.encode();
                        break;
                        case'D':
                        case'd': CaesarCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                                       break;
                   } // switch
              } //CaesarCipher
              private static void Vignere()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Vignere Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin  = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': VignereCipher.encode();
                        break;
                        case'D':
                        case'd': VignereCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //VignereCipher          
              private static void Playfair()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**          Playfair Cipher Menu            **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin  = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': PlayfairCipher.encode();
                        break;
                        case'D':
                        case'd': PlayfairCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //PlayfairCipher     
              private static void sop(String newString)
                   System.out.println(newString);
              } // sop
    } //class

  • Fraction program problem.

    Hi, ive done a program to compute two fractions, but im getting wierd results, and I know its because I stuffed up the logic in equals(), add(), and isZero(). Its saying some fractions are equal to 0 when they are not, and when it does add two fractions they turn out to be fairly large.
    Any help to tell me what parts I did wrong would be great.
    Thankyou.
    //Accessor class
    public class Fraction {
         private int num1, den1, num2, den2, resultNum, resultDen;
         public void readIn() {
              System.out.println("\nTime to enter the first fraction.");
              System.out.print("\nEnter the numerator: ");
              num1 = SavitchIn.readLineInt();
              System.out.print("Enter the denominator: ");
              den1 = SavitchIn.readLineInt();
              System.out.println("\nTime to enter the second fraction");
              System.out.print("\nEnter the numerator: ");
              num2 = SavitchIn.readLineInt();
              System.out.print("Enter the denominator: ");
              den2 = SavitchIn.readLineInt();
         public boolean errorCheck() {
             if ((den1 == 0)||(den2 == 0)) {
                  System.out.println("\nError: The fraction is invalid is its denominator is 0, Halting!");
                  return false;
             else
                  return true;
         public boolean isZero() {
              int result = num1 / den1;
              if (result == 0) {
                  System.out.println("The first fraction equals 0, Halting Program!");
                  return false;
              else
                  return true;
         public boolean equals() {
              if (num1*den2 == den1*num2)
                   return true;
              else
                   return false;
         public void add() {
              int tempNum = (num1*den2) + (den1*num2);
              int tempDen = den1*den2;
              int d = simplify(tempNum, tempDen);
              resultNum = tempNum/d;
              resultDen = tempDen/d;
         public static int simplify(int a, int b) {
              if(a%b > 0)
                   return simplify(b, a%b);
              else
                   return b;
         public void writeOutTrue(boolean check) {
              System.out.println("The fractions entered were: "+num1+"/"+den1+" and "+num2+"/"+den2+".");
              System.out.println("The sum of the fractions entered is: "+resultNum+"/"+resultDen+".");
              if (check == true)
                   System.out.println("The fractions are equal!");
    }//Main class
    public class FractionDemo {
         public static void main(String[] args) {
              boolean truthCheck = true;
              int firstNume=0, firstDenom=0, secNume=0, secDenom=0;
              System.out.println("\nThis program gathers a faction from the user and displays it to the screen.");
              System.out.println("If the first fraction entered equals to '0' to the program will exit.");
              Fraction fracData = new Fraction();
              while(true) {
                   fracData.readIn();
                   truthCheck = fracData.errorCheck();
                   if (truthCheck == true)
                        truthCheck = fracData.isZero();
                   if (truthCheck == false)
                        break;
                   truthCheck = fracData.equals();
                   fracData.add();
                   fracData.writeOutTrue(truthCheck);
    }

    Well, first off, I really don't like your simplify method. If I were you, I'd return an array of two ints, one for the numerator and one for the denominator. Or a Point object, but that could get confusing. :P
    I think your modulo method of simplifying may not work for all situations, but I'm not completely sure; I'm having trouble following it in my head. Personally, I think I'd do simplifying like this:
    public int[] simplify(int n, ind d)
         int nFactors[] = getFactors(n);
         int dFactors[] = getFactors(d);
         // take out factors that are the same here, and the multiply the remaining ones in nFactors for the new numerator and the remaining ones in the dFactor for the denominator.
    publicn int[] getFactors(int n)
        int size=1;
        int twos;
        int threes;
        int fives;
        int sevens;
        boolean canFactor = true;
        while(canFactor))
             if(n%2 == 0)
                 size++;
                 twos ++;
                 n = n/2;
             if(n%3 == 0)
                 size++;
                 threes++;
                 n = n/3;
             if(n%5 == 0)
                 size++;
                 fives++;
                 n = n/5;
             if(n%7 == 0)
                 size++;
                 sevens++;
                 n = n/7;
             else
                 size++;
                 canFactor = false;
        int factors[] = new int[size];
        for(int i = 0; i<factors.size; i++)
            if(twos != 0)
                factors[i] = 2;
                twos --;
            else if(threes != 0)
                factors[i] = 3;
                threes --;
            else if(fives != 0)
                factors[i] = 5;
                fives --;
            if(sevens != 0)
                factors[i] = 2;
                sevens--;
            else
                factors[i] = n; //  this takes care of some of the other prime numbers, like 17 I think
    }I think that code would work for simplifying; but there are probably some exceptions that would get through it; I'm not a mathematician.
    Then, to compare equality, simplify both fractions and if the equal, then the fractions are equal.
    I think your problem with your add method lies in your simplify method, but I'm not sure. If you gave us numbers your program messed up on it would help. I don't have my IDE up here, so I can't test your code.
    As for your isZero method, why divide it out? A fraction will only be 0 if the numerator is 0.
    I hope I was some help. shrug Use my code at your own risk, it's totally untested. I don't know if it will work, but I think it'd work for most cases. I tried a few numbers; I haven't found one where it won't work (yet).

  • Rookie needs help with program!!

    Hi everyone,
    I am new to JAVA programming and am trying to figure out my first progam. Any suggestions? Here's what I have to come up with...
    This program will test your ability to code a loop function and some work with the strings methods.
    INPUT
    A SENTENCE OF UNKNOWN LENGTH.
    OUTPUT
    THE NUMBER OF WORDS IN THE SENTENCE AND EACH WORD ON A SEPARATE LINE. Two spaces are not a word; "a" is a word.
    HINT
    Use a loop until the end of the sentence and count each word that is removed from the front of the sentence (one at a time). Each time the sentence should be shortened.
    I know I need to use a string method...Here's what I have so far...
    public class jmstr
    public static void main (String[ ] args)
    System.out.println ("Please enter a sentence starting with some spaces ");
    inputline = SavitchIn.readLine ( ) ;
    System.out.println (inputline);
    I'm not really sure what to do next....?
    Any help would be appreciated!
    materman

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html
    look at the example on the page, then scroll down to the Methods section and click on
    countTokens()

  • Is there better way?

    Hi! To check which input for the population is lower I used double min and double max. But while loop for counting years is not working. What is better way to do it?
    I'd appreciate any help you can give.
    Thanks.
    Program asks for data on two species and has to respond by telling how many years it will
    take for the species with lower
    population outnumber the species that starts with higher population.
    class SpeciesTry
    private String name1;
    private String name2;
    private int population1;
    private int population2;
    private double growthRate1;
    private double growthRate2;
    public void readInput( )
    System.out.println("What is the first species' name?");
    name1 = SavitchIn.readLine( );
    System.out.println("What is the population of the species?");
    population1 = SavitchIn.readLineInt( );
    while (population1 < 0)
    System.out.println("Population cannot be negative.");
    System.out.println("Reenter population:");
    population1 = SavitchIn.readLineInt( );
    System.out.println("Enter growth rate (percent increase per year):");
    growthRate1 = SavitchIn.readLineDouble( );
    System.out.println("What is the second species' name?");
         name2 = SavitchIn.readLine( );
         System.out.println("What is the population of the species?");
         population2 = SavitchIn.readLineInt( );
         while (population2 < 0)
         System.out.println("Population cannot be negative.");
         System.out.println("Reenter population:");
         population2 = SavitchIn.readLineInt( );
         System.out.println("Enter growth rate (percent increase per year):");
    growthRate2 = SavitchIn.readLineDouble( );
    public void writeOutput( )
    System.out.println("Name of the species' = " + name1);
              System.out.println("Population = " + population1);
              System.out.println("Growth rate = " + growthRate1 + "%");
              System.out.println("Name of the species' = " + name2);
              System.out.println("Population = " + population2);
    System.out.println("Growth rate = " + growthRate2 + "%");
    public void outnumbersPopulation()
    double max=0; double min=0; double minGrowthRate=0; double maxGrowthRate=0;
    String maxName=null; String minName=null;
    int years=0;
    if ((population1<=population2)&(growthRate1<=growthRate2))
    System.out.println("The species " + name1 + " will never outnumber the species " + name2 );
    System.exit(0);
    else if ((population2<=population1)&(growthRate2<=growthRate1))
    System.out.println("The species " + name2 + " will never outnumber the species " + name1 );
    System.exit(0);
    if((population1>population2)&(growthRate1<growthRate2))// this is to determine which population is smaller
    max=population1;
    maxName=name1;
    maxGrowthRate=growthRate2;
    min=population2;
    minGrowthRate=growthRate1;
    minName=name2;
    if ((population2>population1) &(growthRate2<growthRate1))
    max=population2;
    maxName=name2;
    maxGrowthRate=growthRate1;
    min=population1;
    minName=name1;
    minGrowthRate=growthRate2;
    while ( (min <=max) & (years > 0) )
    min= (min +((minGrowthRate/100) * min));
    max=(max + ((maxGrowthRate/100) * max));
    years ++;
    System.out.println("The species " + minName + " will outnumber the species " + maxName +
    " in " + (years+1) + " years");
    public class Species
         public static void main(String[] args)
         SpeciesTry s1= new SpeciesTry();
         s1.readInput();
         s1.writeOutput();
         s1.outnumbersPopulation();
    }

    I'm new to Java and posting. So, here's my program again with outnumberPopulation() method formated. Is there any hope for this program?
    class SpeciesTry
    private String name1;
    private String name2;
    private int population1;
    private int population2;
    private double growthRate1;
    private double growthRate2;
    public void readInput( )
    System.out.println("What is the first species' name?");
    name1 = SavitchIn.readLine( );
    System.out.println("What is the population of the species?");
    population1 = SavitchIn.readLineInt( );
    while (population1 < 0)
    System.out.println("Population cannot be negative.");
    System.out.println("Reenter population:");
    population1 = SavitchIn.readLineInt( );
    System.out.println("Enter growth rate (percent increase per year):");
    growthRate1 = SavitchIn.readLineDouble( );
    System.out.println("What is the second species' name?");
         name2 = SavitchIn.readLine( );
         System.out.println("What is the population of the species?");
         population2 = SavitchIn.readLineInt( );
         while (population2 < 0)
         System.out.println("Population cannot be negative.");
         System.out.println("Reenter population:");
         population2 = SavitchIn.readLineInt( );
         System.out.println("Enter growth rate (percent increase per year):");
    growthRate2 = SavitchIn.readLineDouble( );
    public void writeOutput( )
    System.out.println("Name of the species' = " + name1);
              System.out.println("Population = " + population1);
              System.out.println("Growth rate = " + growthRate1 + "%");
              System.out.println("Name of the species' = " + name2);
              System.out.println("Population = " + population2);
    System.out.println("Growth rate = " + growthRate2 + "%");
       public void outnumbersPopulation()
            double max=0;  double min=0; double minGrowthRate=0; double maxGrowthRate=0;
            String maxName=null; String minName=null;
                    int years=0;
            if( population1>population2)// this is to determine which population is smaller
            {    max=population1;
                maxName=name1;
                maxGrowthRate=growthRate2;
                min=population2;
                minGrowthRate=growthRate1;
                minName=name2;
             else
                    max=population2;
                    maxName=name2;
                    maxGrowthRate=growthRate1;
                    min=population1;
                    minName=name1;
                    minGrowthRate=growthRate2;
           if (minGrowthRate<=maxGrowthRate)
              System.out.println(minName+" will never grow larger than "+maxName);
              return;
             while ( (min <=max) & (years > 0) )
                 min= (min +((minGrowthRate/100) * min));
                   max=(max + ((maxGrowthRate/100) * max));
                               System.out.println("Check" + max + min);
                               years ++;
            System.out.println("The species " + minName + " will outnumber the species " + maxName +
            " in " + (years+1) + " years");
    public class Species
         public static void main(String[] args)
         SpeciesTry s1= new SpeciesTry();
         s1.readInput();
         s1.writeOutput();
         s1.outnumbersPopulation();
    }

  • Using mutator and accessor methods in main.

    Would somebody explain to me exactly how mutator and accessor methods make a class and it's driver program work together. I understand the principle of encapsulation, but I'm obviously missing something. I get the syntax, but what actually happens? I'm hoping a fresh perspective on it will help me understand better.
    I guess another way to ask the question could be: how do you use accessor and mutator methods in the main program that calls them?

    >
    the assignment says to have a
    "reasonable set of accessor and mutator methods
    whether or not you use them". So in my case I have
    them written in the class but do not call them inthe
    driver program. And like I said, the program does
    what it's supposed to do.This class you're in worries me. I'm sure what
    polytropos said is true: they're trying to make you
    think about reuse. But adding to an API without cause
    is widely considered to be a mistake, and there are
    those who are strongly opposed to accessors/mutators
    (or worse, direct field access) on OOP design grounds.The class is based on the book Java: Introduction to Computer Science and Progamming, by Walter Savitch. Until now I've been pretty happy with it. Another problem, to me anyway, is that so far we've done a few, cumulative programming projects per chapter. This time, there was one assignment for the whole chapter that is suppsoed to incorporate everything. But that's just me complaining.
    Here is the code I have and that it looks like I'll be turning in... criticisms welcome.
    Here is the class:
    public class GradeProgram//open class
         private double quiz1;
         private double quiz2;
         private double mid;
         private double fin;
         private double finalGrade;
         private char letterGrade;
         public void readInput()//open readInput object
              do
                   System.out.println("Enter the total points for quiz one.");
                   quiz1 = SavitchIn.readLineInt();
                   System.out.println("Enter the total points for quiz two.");
                   quiz2 = SavitchIn.readLineInt();
                   System.out.println("Enter the mid term score.");
                   mid = SavitchIn.readLineInt();
                   System.out.println("Enter final exam score.");
                   fin = SavitchIn.readLineInt();
                   if ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0))
                   System.out.println("Quiz scores are between one and ten.  Re-enter scores");
                   if ((mid>100)||(fin>100)||(mid<0)||(fin<0))
                   System.out.println("Exam scores are between zero and one hundred.  Re-enter scores.");
              while ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0)||(mid>100)||(fin>100)||(mid<0)||(fin<0));
         }//end readInput object
         public void output()//open output object
              System.out.println();
              System.out.println("You entered:");
              System.out.println("Quiz 1: " + (int)quiz1);
              System.out.println("Quiz 2: " + (int)quiz2);
              System.out.println("Mid term: " + (int)mid);
              System.out.println("Final exam: " + (int)fin);
              System.out.println();
              System.out.println("Final grade: " + (int)percent() + "%");
              System.out.println("Letter grade: " + letterGrade());
         }//end output object
         public void set(double newQuiz1, double newQuiz2, double newMid, double newFin, double newFinalGrade, char newLetterGrade)
              if ((newQuiz1 >= 0)&&(newQuiz1 <= 10))
              quiz1 = newQuiz1;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newQuiz2 >= 0)&&(newQuiz2 <= 10))
              quiz2 = newQuiz2;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newMid >= 0)&&(newMid <= 100))
              mid = newMid;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              if ((newFin >= 0)&&(newFin <= 100))
              fin = newFin;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              letterGrade = newLetterGrade;
         public double getQuiz1()
              return quiz1;
         public double getQuiz2()
              return quiz2;
         public double getMid()
              return mid;
         public double getFin()
              return fin;
         public char getLetterGrade()
              return letterGrade;
         private double finalPercent()//open finalPercent object
              double quizPercent = (((quiz1 + quiz2) /2) * 10) / 4;
              if (((((quiz1 + quiz2) /2) * 10) % 4) >= 5)
                   quizPercent++;
              double midPercent = mid / 4;
              if ((mid % 4) >= 5)
                   midPercent++;
              double finPercent = fin / 2;
              if ((fin % 2) >= 5)
                   finPercent++;
              finalGrade = (quizPercent + midPercent + finPercent);
              return (finalGrade);
         }//end final percent object
         private double percent()//open percent object - helping object
              double percentGrade = finalPercent();
              return (percentGrade);
         }//end percent object
         private char letterGrade()//open letterGrade object
              double letter = percent();
              if (letter >= 90)
                   return ('A');
              else if (letter >= 80)
                   return ('B');
              else if (letter >= 70)
                   return ('C');
              else if (letter >= 60)
                   return ('D');
              else
                   return ('F');
         }//end letterGrade object
         private double quizScore()//open quizScore object
              double quizes = ((quiz1 + quiz2) /2) * 10;
              return (quizes);
         }// close quizScore object
    }//end classAnd here is the driver program:
    public class GradeProgramDemo
         public static void main(String[] args)
              String cont;
              do
                   GradeProgram firstStudent = new GradeProgram();
                   firstStudent.readInput();
                   firstStudent.output();
                   System.out.println();
                   System.out.println("Enter more student grades?  Enter Y to continue");
                   System.out.println("or press enter to quit.");
                   cont = SavitchIn.readLine();
                   System.out.println();
              while (cont.equalsIgnoreCase("y"));

  • Out OF Bounds Exception need help

    I am trying to learn how to catch exceptions. I can not see what I am doing wrong. Can someone show me and explain what I am doing wrong. I am taking in Military Time and will convert it to a 12 hour clock. I am testing it as I go so I have not finished adding code. The bad code is marked with // <== StringIndexOutOfBoundsException. Thank You in advance for the help.
    public class TimeFormat
    public TimeFormat()
    public static void main(String[] args)
    double amtt;
    char ans = 'n';
    String time1 = "00:00";
    String min1 = " ";
    int hh = 0;
    int mm = 0;
    String dd = " ";
    System.out.println("This program will convert 24 hour time into 12 hour time");
    do
    try
    System.out.println("Enter a time in military format: (ex. 14:00)");
    time1 = SavitchIn.readLine();
    hh = Integer.parseInt(time1.substring( 0, 2));
    String amPm = "PM";
    if (hh <= 12)
    amPm = "AM";
    dd = time1.substring( 2, 1); // <== StringIndexOutOfBoundsException
    mm = Integer.parseInt(time1.substring( 3, 2));
    int t1 = Integer.parseInt(time1);
    min1 = time1.substring(3, 3);
    if (t1 < 0 || t1 > 2459)
    throw new Exception ("Exception: Bad Input, must be between 0 and 2459");
    catch(Exception e)
    System.out.println("e.getMessage()");
    System.out.println("Time must be between 0 and 2499");
    System.out.println("\n\nWould you like to do it again? (y/n) : ");
    ans= SavitchIn.readLineNonwhiteChar();
    }while ((ans == 'y') || (ans == 'y'));

    import java.awt.*;
    import java.io.*;
    import java.text.*;
    public class texas {
      int hours, minutes;
      String AM_PM = " am";
      public texas() {
        try {
          BufferedReader br = new BufferedReader(
                              new InputStreamReader( System.in ));
          System.out.print("\nEnter a 24-hour time (\"##:##\"): ");
          System.out.flush();
          String s = br.readLine();
          if(s.indexOf(":") == -1) {
            System.out.println("Invalid entry - separate hours " +
                               "and minutes with \":\"");
            return;
          String[] sarray = s.split(":");
          hours   = Integer.parseInt(sarray[0]);
          minutes = Integer.parseInt(sarray[1]);
        } catch(IOException ioe) {
          System.out.println(ioe.toString());
          return;
        } catch(NumberFormatException nfe) {
          System.out.println(nfe.toString());
          return;
        } catch(ArrayIndexOutOfBoundsException aioobe) {
          System.out.println(aioobe.toString());
          return;
        if(hours < 0 || hours > 24) {
          System.out.println("Invalid input - hours must be between 0 and 24");
          return;
        if(minutes < 0 || minutes > 59) {
          System.out.println("Invalid input - minutes must be between 0 and 59");
          return;
        if(hours > 12) {
          hours -= 12;
          AM_PM = " pm";
        if(hours == 12 && minutes >= 0)
          AM_PM = " pm";
        String minutes12 = String.valueOf(minutes);
        if(minutes12.length() < 2)
          minutes12 = "0" + minutes12;
        String time = String.valueOf(hours) + ":" + minutes12 + AM_PM;
        System.out.println("12-hour time is: " + time);
      public static void main(String[] args) {
        new texas();
    }

  • A problem with infinite loop

    Hi there! My program has to get data on two species in any order and respond by telling how many years it will take for the species with lower population outnumber the species that starts with higher population. If the species with the smaller population never outnumbers the species with the higher population I'll get an infinite loop. What is the right approach here?
    Thanks.
    public class Species
    private String name1;name2
    private int population1, population2;
    private double growthRate1, growthRate2;
    public void readInput( )
    System.out.println("What is the first species' name?");
    name1 = SavitchIn.readLine( );
    System.out.println("What is the population of the species?");
    population1 = SavitchIn.readLineInt( );
    while (population1 < 0)
    System.out.println("Population cannot be negative.");
    System.out.println("Reenter population:");
    population1 = SavitchIn.readLineInt( );
    System.out.println(
    "Enter growth rate (percent increase per year):");
    growthRate1 = SavitchIn.readLineDouble( );
    ystem.out.println("What is the second species' name?");
    name2 = SavitchIn.readLine( );
    System.out.println("What is the population of
    the species?");
    population2 = SavitchIn.readLineInt( );
    while (population2 < 0)
    System.out.println("Population cannot be negative.");
    System.out.println("Reenter population:");
    population2 = SavitchIn.readLineInt( );
    System.out.println(
    "Enter growth rate (percent increase per year):");
    growthRate2 = SavitchIn.readLineDouble( );
    public void writeOutput( )
    System.out.println("Name of the species' = " + name1);
    System.out.println("Population = " + population1);
    System.out.println("Growth rate = " + growthRate1 + "%");
    System.out.println("Name of the species' = " + name2);
    System.out.println("Population = " + population2);
    System.out.println("Growth rate = " + growthRate2 + "%");
    public void OutnumbersPopulation()
    double max, min;
    int years=0
    if(population1>population2)// this is to determine which population is smaller
    max=population1;
    min=population2;
    else if (population2>population1)
    max=population2;
    min=population1;
    while ((years > 0) && (min <=max))//This could be an infinite loop if min never outnumbers max
    min= (min +
    (growthRate/100) * min);
    max=(max + (growthRate/100) * max);
    years ++;
    System.out.println("The species with the lower population will outnumber the species with higher population
    in" + (years+1) + "years");

    Cross post. original is in "New to Java Technology".

Maybe you are looking for

  • I can't sync my iPad to iTunes after I trust my Sony Vaio Laptop Windows 8. Please help.

    Hi I tried to sync my iPad on my laptop and I plug into my laptop and touch the trust this computer but it doesn't show up on iTunes. Please help me to solve this problem

  • How to find out the file name

    Hi, In selection screen (parameter) user will give input TXT file from presentation server to upload to SAP. I need to capture the file name only but not the path and need to concatenate with date stamp and need to download error log in XLS file to p

  • Adobe Flash player for Asus Transformer Pad

    We're Sorry This content requires Adobe Flash Player, which is not supported by your device. This content can be viewed on a desktop computer or on mobile devices that support Flash Player. Why adobe.com doesn't have opportunity download adobe flash

  • Pl/sql Fuction Output

    Hi, The given below function used in a formula column of report 6i and its return value used to display iterm_code description in a quotation. But for corresponding to some values(V_segment6) the o/p is giving wrong answer. i cant find where the prob

  • Unable to get the print option in network for Services

    Hi Experts I am unable to get the print for services in CN21/CN22 but the print option is in Disable Mode .How should I get it as to Enable Mode to get print .Pl find the attached screenshot for reference Thanks in Advance Ambarish