javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Type cast Object to Integer:

Integer integ = (Integer)objectValue;
integ.intValue();

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You can first check if the input is 'Q' or 'q' and then try to convert it into a double

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If you want to call methods you can only do it inside other methods (a Constructor maybe).
Where you wrote the code that gives you the error you can only put variable declarations.
So you must declare a method (preferably a Constructor) and put the code that gives you the error there

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Well,

1. That's already been said.
2. The OP has declared the problem solved.
3. You didn't notice that today was declared today=new date() rather than today=new Date() .

And

4. This thread is 15 days old. Try to solve more current threads

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
while(option!=9) {

Name nameBox[]= new Name[500];

}

You create a new nameBox every time you repeat the loop, so the first time you are in the loop you give values to the local nameBox, but when the loop executes again, you create again a new nameBox (new Name[500]) that naturally hasn't anything inside.
Put the declaration of nameBox outside the while-loop

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I have search the java.awt package and didn't find the class Picture:
java.awt

I don't believe that it is a class that the JDK has. Try search it in the internet and you will find plenty Picture classes implemented by others

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If my sleepy mind does play tricks on me, you should do it as

(File)vector.elementAt(i).getAbsolutePath()

I think, although it needs to be checked that you should do this: ((File)vector.elementAt(i)).getAbsolutePath() Just a suggestion, I don't know if it will work, just try it, because resizing the array is bad idea.
Every time you change the vector you will have to create a new array AND store again the data, so try first the above before using the array solution

PoovenM commented: I totally agree :) +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

This: File stuff = new File(stuff.txt); Should be: File stuff = new File([B]"[/B]stuff.txt[B]"[/B]); This: Scanner scan = Scanner(stuff); Should be: Scanner scan = [B]new[/B] Scanner(stuff); This: place = scan.NextDouble(); I think should be: place = scan.[B]n[/B]extDouble(); Look at this: Scanner

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

first of all this:
sides = mSides;
should be like this:
mSides = sides;

And the error you get is because the method:
mRandom.nextInt(mSides)
doesn't take as argument a negative or zero number; as the error message says it must be positive.

The reason you get the error is because when you do:
sides = mSides
the sides is the argument and you simply change its value. The mSides which is the class variable doesn't change and remains to 0 and you get error.

If you had:
mSides = sides
the argument sides will give value to the mSides of the class, and it will take the value you give it, so the call:
mRandom.nextInt(mSides)
will have what you give as argument

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I assume that the other program (GUI) has a list of classes. Do you know the elements of those classes as well as their methods. If the main GUI page has a constructor you call it with the appropriate data that you get from your program.
If the elements of the GUI are public you can 'set' their values, after you have called the constructor of the program in your main:

In general how you set values:

JTextField field = new JTextField();
field.setText("New Text");

In your main:

OtherProgramGUI gui = new OtherProgramGUI();
gui.field.setText("New Text");

gui.setVisible(true);

If all of the elements and the methods are private then you have a problem

PoovenM commented: Thank you for the awesome suggestion :) +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The concept of stack is not unique in java. It applies not only in the programming world but everywhere, so I will explain the basic concept.

When you put items in a stack you place each one of them after the other. But when you try to take these items from the stack you can only take the last one you entered not the first. If you have a stack of plates you put one on top of the other, but you cannot take the one at the bottom (the one you put first), you must take the one at the top, which was the one you placed last.

In java, you can store objects in a stack the same way. Assume you call push several times:

push("AAA")
push("BBB")
push("CCC")

when you call the pop command you will get the value: "CCC". If you call pop again you will get the "BBB". You will be getting the items in the opposite order you put them


Now if you use an ArrayList and do this:

add("AAA")
add("BBB")
add("CCC")

And then try to get the values with method get(int i) , you will have the values in the order placed in them:
"AAA"
"BBB"
"CCC"

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The problem is in the evaluatePostfix method, as the error says.
Probably because the program goes to else if { ... } and you try to do a
int op1 = stack.pop()
If the stack is empty how can you pop something from it?
First check if the stack has values before calling pop. I am not very familiar with the Stack class but here is the API:
Stack
There is an empty() method that checks if the stack is empty or not

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

What puneetkay is trying to say is that you must first read the input from the console and then do the calculations, not the other way around

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

wont let me do anything like that, first methode has to be
public static void main(String [] args);
it wont allow me to have anything but variables above it, no methods nothing.
wont even allow me to have a methode without a 'type' such as
public static unnamed();

/

That is because i wrote this:

public printMyName() {

}

When I should have written this:

public void printMyName() {

}

It was a simple mistake and you should have been able to correct it and not say that it cannot be done


Add a System.out.println("") at the begining of the mainmenu() method and see if it is called:

public static void mainmenu(String playername) {
   Sytem.out.println("mainmenu method called with: "+playername);
}

Does the playername printed? :

System.out.println("hello " + playername)

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Here is an example for your problem followed by a link from this forum:

Static:

class Test {
public static printMyName() {
  System.out.println("My name IS  NEO");
}

public static void main(String [] args) {
   printMyName();

   //or

   Test.printMyName();

   //both will work
}
}

Non Static:

class Test {
public printMyName() {
  System.out.println("My name IS  NEO");
}

public static void main(String [] args) {
   Test test = new Test();
   test.printMyName();
}
}

http://www.daniweb.com/forums/thread143361.html

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
<form action="">

...
<input type="text" name="text1" ......>
...

<input type="submit" value="Submit">
</form>

If you don't understand the above, you are doing something wrong.
After you submit the form you will use:
request.getParameter() to take the values into String:

String text1 = request.getParameter("text1");

Then call the method that takes the above values and stores them into the database.

As for the database the is plenty of code to look for in this forum or look for tutorials

This is just an example:
http://www.daniweb.com/forums/post653467.html#post653467

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Since you created it dynamically using java, then you can the values that you displayed and write a method that take these values and store them in the database.

If the values, are user inputs then use the <form> tag and submit the form to another jsp, take the values (request.getParameter()) and use the above procedure

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You forgot the parenthesis at the end:
total=first.getPages()+ second.getPages()+ third.getPages;
total=first.getPages()+ second.getPages()+ third.getPages();

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Probably because the file does not exist.
And you could use BufferedReader for reading from file.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

am getting the error ") expected" at line 68..Is there a way I can call the method printInfo from the class mainPrg? maybe something like calling the class Chapter from mainPrg which can call the method printInfo..

Don't tell me that you couldn't also figure out that out?

Create an instance of the class whose method you want to call.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

And the getPages(), getTitle(), methods are not declared in the Book class. That is why you get error. They are defined in the Chapter class so you should do:

public void printContents()
	{
		System.out.println("Contents:");
		System.out.println("1." +first.getTitle()"........." +first.getPages());
		System.out.println("");
		System.out.println("2." +second.getTitle()"...........:" +second.getPages()"\n");
		System.out.println("");		
		System.out.println("3."+third.getTitle()"...........:" +third.getPages()"\n");
		System.out.println("");
	}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Please post the errors you get and at which line you get them

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
for (int i=0;i<personList.size();i++) {
  String s = personList.get(i);
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The Person class is abstract. So the classes that extend Person must implement all the abstract methods of Person.

The classes: Students and Lecturers must implement the method getRegisterNo() .
You have forgotten to implement this method when you did:

Students extends Person

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

It looks OK. What is your problem?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

There is a null personList of type List, but you declare that the null personList List will have ONLY elements of type Person.
The personList maybe null, it is type List but you put "things" in the List. And you declare that when you are going to put things in the List the elements will be of type Person.

List<Person> personList= null;

Then somewhere else in the code:

personList = new ArrayList<Person>();
personList.add(new Person());

//the following is wrong:
personList.add(new String("Aaaaa"));
//you can put only Person objects in the List

But this would be correct:

List list = new ArrayList();

personList.add(new Person());
personList.add(new String("Aaaaa"));

But not recommended

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If you want to give only once input the use the args of the main. This happens when you run the program

Use BufferedReader when you don't know how many inputs the user will give.
If you have a menu where the user selects options you don't know when the user will decide to stop selecting. So you will use BufferedReader. In that way you read input while the program is running

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Now pay REAL attention to this:

package testpackage;

/**
 *
 * @author stamatios.bardanis
 */
public class Main3 {
    public static void main(String [] args) {
        Person a = new Person("John");
        Person b = new Athlete("John", 178); 
        
        System.out.println(a.toString());
        System.out.println(b.toString());
    }
}

Both a and b are Persons:
Person a = ...
Person b = ...
And I call the same method:
a.toString()
b.toString()

BUT for object a, the Person toString() will be called.
For object b, the Athlete toString() will be called.
Check what the toString() methods of those objects do and what is called.

An Athlete object is a Person. Meaning it can do whatever a Person can do. The Athlete object has access to all the public methods of Person

But this would be wrong:

Athlete c = new Person ("John");

Because a Person is not an Athlete. The Person cannot call the Athlete's methods. How could it?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

And for inheritance:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testpackage;

/**
 *
 * @author stamatios.bardanis
 */
public class Athlete extends Person {
    private int height=0;
    
    public Athlete() {
        super();
        height=0;
    }
    
    public Athlete(int he) {
        super();
        height=he;
    }
    
    public Athlete(String na) {
        super(na);
        height=0;
    }
    
    public Athlete(String na, int he) {
        super(na);
        height=he;
    }

    public void setHeight(int he) {
        height = he;
    }

    public int getHeight() {
        return height;
    }

    @Override
    public String toString() {
        return "The athlete: "+getName()+" has height: "+height+" cm";
    }
    
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testpackage;

/**
 *
 * @author stamatios.bardanis
 */
public class Main2 {
    public static void main(String [] args) {
        Athlete a1 = new Athlete();
        a1.setName("Andersson");
        a1.setHeight(180);
        System.out.println("Name: "+a1.getName());
        System.out.println("Height: "+a1.getHeight());
        
        System.out.println();
        
        Athlete a2 = new Athlete("Superman",200);
        System.out.println(a2.toString());
    }
}

Check what I call. Then check the code of what I call and what it returns
Any questions?
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
package testpackage;

/**
 *
 * @author stamatios.bardanis
 */
public class Person {
    private String name=null;
    
    public Person() {
        name="";
    }
    
    public Person(String na) {
        name = na;
    }

    public String getName() {
        return name;
    }

    public void setName(String na) {
        name = na;
    }

    public String toString() {
        return "My name is: "+name;
    }
    
}
package testpackage;

/**
 *
 * @author stamatios.bardanis
 */
public class Main {
    public static void main(String [] args) {
        Person p1 = new Person();
        p1.setName("Andersson");
        System.out.println("Mr "+ p1.getName()+" welcome back. We missed you");
        
        System.out.println();
        
        Person p2 = new Person("Neo");
        System.out.println(p2.toString());
    }
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I think your professor simply wants you to catch what may potentially generate the indexOutOfBounds exception and handle it by making the number accessing the indice set to some value (for example, if the number is constantly incrementing, in the catch block set the number to zero, if decrementing set it to the array length - 1 ).

Either way, this is a poor way of doing it though it may please your unreasonable professor.

That is no way to teach someone exceptions or proper java and I think that we both agree on that.
If you want to teach someone how to use exception, you use the NombarFormatException, not ArrayIndexOutOfBounds. What's the difference. One happens at runtime and cannot be avoided, so that is why you catch it and the other is not suppose to happen. If it happens then the code is wrong.

Suppose that you have a program that accepts 2 inputs and it must add them. The main has Strings as arguments: main (String [] args) . So since you don't what the user might enter you use the NombarFormatException.
But with ArrayIndexOutOfBounds you are supposed to check the index of the array. It will be the programmer's mistake to have such an exception thrown. I doubt that there is any case where using ArrayIndexOutOfBounds is better than doing something else. And NO ONE will ever write something like this:

try {
  for (int i=0;i<10;i++) {
    System.out.println(array[i]);
  }
} catch (ArrayIndexOutOfBounds e) …
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

This:

FileReader inputStream = null;
			 PrintWriter outfile = null;
			 
			 try
			 {
			 
          FileReader inputStream = new FileReader("text.txt");
          PrintWriter outfile =
                  new PrintWriter(new FileWriter("textCh.out"));
..
..
}

Should be:

FileReader inputStream = null;
PrintWriter outfile = null;
			 try
			 {
          inputStream = new FileReader("text.txt");
          outfile = new PrintWriter(new FileWriter("textCh.out"));
..
..
}

The 3 methods writeTotal, chCount, copyText should be declared outside the main method. Meaning that you have a small problem with the parenthesis. You forgot to put one:
Add it there:


System.out.println(e.getMessage()) ;
}

} this one closes main

static void copyText(FileReader infile, PrintWriter outfile,


Also I don't know what the IntClass does? But try to fix the above first and see what happens. I think that it will work. Sometimes one misplaced '}' can give many errors

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

post you final code

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I have to create a program that reads the text, outputs the text as is and prints the number of lines and the number of times each letter appears in the text. I have to include an exception, so that if the array index goes out of bounds when the program accesses the array letterCount, it throws and handles the ArrayIndexOutOfBoundsException. I have the program completed and working , but I'm having trouble adding the exception to the program. Here is my code:

Hi it's me again. Sorry for not checking what you wrote, I was only looking at the code you gave. It seems that I suggested not to use ArrayIndexOutOfBoundsException even though that is what you wanted.
Who told you to use this exception handling? Because what I suggested was generally correct: you don't want to catch such exception, but instead make sure it doesn't happen by checking the length of the array.
Anyway if you want ArrayIndexOutOfBoundsException here it is.:

static void chCount(char ch, int[] letterC) throws ArrayIndexOutOfBoundsException {
          int index;
          int i;

          ch = Character.toUpperCase(ch);   //Step a
          index = (int) ch - 65;            //Step b
          if (index >= 0 && index < 26)      //Step c
            letterC[index]++;
    }

    static void writeTotal(PrintWriter outfile, int lines,
                           int[] letters)
    throws ArrayIndexOutOfBoundsException  {
          int i;

          outfile.println();
          outfile.println("The number of lines = " + lines);

          for (i = 0; i < 26; i++)
              outfile.println((char)(i + 65) + " count = "
                             + letters[i]);
    }

static void copyText(FileReader infile, PrintWriter …
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

And something that I forgot:
NEVER, NEVER "hard code" the length of an array when you access it :

This:

for (i = 0; i < 26; i++)
              outfile.println((char)(i + 65) + " count = "
                             + letters[i]);

Should become this:

for (i = 0; i < letters.length ; i++)
              outfile.println((char)(i + 65) + " count = "
                             + letters[i]);

And this:

if (index >= 0 && index < 26)      //Step c
            letterC[index]++;

To this:

if (index >= 0 && index < letters.length)      //Step c
            letterC[index]++;
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
IntClass next = new IntClass();

          FileReader inputStream = new FileReader("text.txt");
          PrintWriter outfile =
                  new PrintWriter(new FileWriter("textCh.out"));

          next.setNum(inputStream.read());

          while (next.getNum() != -1)
          {
              copyText(inputStream, outfile, next, letterCount);
              lineCount++;
              next.setNum(inputStream.read());
          }  //end while loop

          writeTotal(outfile, lineCount, letterCount);

          outfile.close();

The above code needs to be altered like this:

IntClass next = new IntClass();
FileReader inputStream = null;
PrintWriter outfile = null;

try {
           inputStream = new FileReader("text.txt");
           outfile = new PrintWriter(new FileWriter("textCh.out"));

          next.setNum(inputStream.read());

          while (next.getNum() != -1)
          {
              copyText(inputStream, outfile, next, letterCount);
              lineCount++;
              next.setNum(inputStream.read());
          }  //end while loop

          writeTotal(outfile, lineCount, letterCount);

          outfile.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all, this:
int[] letterCount = new int[26] ;
does not throw an exception.
Second: Let me guess your program does not compile. This is why:

try
			 {
          int[] letterCount = new int[26];
			 }
			 catch (ArrayIndexOutOfBoundsException e)
			 {
			 System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage());
			 e.printStackTrace();
			 }

You declare letterCount inside the try { ... }. Meaning that outside try{...} no one can "see" it. So when you try to use it at the while loop you will get an error. If you have to give value to a variable inside the try{...} but you will have to use it outside as well then:

int[] letterCount = null;
try
			 {
          letterCount = new int[26];
			 }
			 catch (ArrayIndexOutOfBoundsException e)
			 {
			 System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage());
			 e.printStackTrace();
			 }

You declare letterCount outside try{} so anyone can see it.
By the way the above is not necessary, since the declaration does not throw an ArrayIndexOutOfBoundsException, unless you use negative value. And it is not very correct to catch such exceptions. It is up to the programmer to check in the code and make sure that you will never try to access an element of an array with an index greater than the length.

//try {
          int[] letterCount = new int[26];
/*
			 } catch (ArrayIndexOutOfBoundsException e) {
			 System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage());
			 e.printStackTrace();
			 }
*/

Try it without the try-catch.

As for you question, remove the throws Exception, from the main. You use these at method declarations in order to …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The
int numberValue = Integer.parseInt(number) ;
does not throw a IOException. You are right to use it in the catch since readLine() does throw the IOException, but the parseInt() throws a NumberFormatException:

/**
 * @(#)GetUserInput.java
 *
 *
 * @author 
 * @version 1.00 2008/8/2
 */
import java.io.*;

public class GetUserInput 
{
         private static BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );

        
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException
    {

     
            System.out.print( "Type some data for the program: " );


            // Read a line of text from the user.
            String input = stdin.readLine();
		


            // Display the input back to the user.
            System.out.println( "input = " + input );
            
            System.out.print( "Type a number for the program: " );

	
            // Read a line of text from the user.
            // then convert it to int but print error message if it goes wrong
             try
	    {
		String number = stdin.readLine();
	    int numberValue = Integer.parseInt(number);	    
            
            // Display the input back to the user.
            System.out.println( "Number Inputted = " + numberValue );
	
	    }
            // i want it to print the error message if if cant convert the string to an int
		catch ( IOException e )
	   {
	System.out.println(e);
      		System.out.println("Error while reading input: " + e.getMessage());
           }
catch ( NumberFormatException e )
	   {
	System.out.println(e);
      		System.out.println("Given input not a number: "+e.getMessage());
           }
   
    }
}
Alex Edwards commented: Helpful individual +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Put all the averages in a new array. Then write two methods that accept an array as input and return the greater and the lower value.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Once you have the necessary information for a specific student:

double avg = (student[i][0] + student[i][1] + student[i][2])/3.0
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Instead of getting the last two values, take the first two. And don't forget that sorting the priceArray, doesn't sort the itemArray. And if you sort the itemArray, it will be sorted based on the values itemArray has, and the mapping between names and prices will be mixed up.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

i tried using

import java.util.Arrays;

so as to use the method Arrays.sort(); but it only shows the highest instead, i would like the 2 lowest value plaease.

What do you mean the highest?
The Arrays.sort(int[] a) sorts the array. It's up to you to take the values you want

Edit: I would suggest to read my previous post

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Arrays class with its sort() methods is all you need

But if he sorts priceArray then the itemArray will also have to be sorted the same way.
It would be better to use the old fashion way to sort priceArray and do equivalent swapping to itemArray.
Or
Create an object with two attributes:
price, foodName:

class Food {
private String foodName;
private double price;

//add get, set methods OR make the above variables public
}

Then use the interface: Comparable:

class Food implements Comparable{
// code

public int compareTo(Food f) {

}
}

Comparable

Objects that implement Comparable can be used as arguments at the Arrays.sort() method

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Do you know that the array will already have the values sorted? From what I see:
double[] priceArray = { 21.00, 17.00, 12.00, 10.00, 4.90, 4.90, 1.80, 1.80 } ;
The array is already sorted, so you just need to take the 2 last values.

If this is not the case then writing:

System.out.println("Most Economical Food:\t" + (loworderNo-1) +"\t\t"+ item[[B]loworderNo-1[/B]] + "\t" + lowest);
System.out.println("Most Economical Food:\t" + loworderNo +"\t\t"+ item[loworderNo] + "\t" + lowest);
is not quite correct, because since the array will not be sorted you don't know if the lowest prices will be next to each other.
Plus if the array doesn't have 2 lowest prices but 1 you will have an ArrayIndexOutOfBoundsException.
Check before you access an array if the values is in bounds. You are sure for variable: loworderNo but you don't know 100% that ( loworderNo - 1 ) will be OK.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Another version using YOUR do while loop is this:

for (int i=0;i<10;i++) {

do{
 prelim=JOptionPane.showInputDialog("Student Prelim["+i+"]");
 midterm=JOptionPane.showInputDialog("Student Midterm["+i+"]");
 finals=JOptionPane.showInputDialog("Student Finals["+i+"]");

  boolean bPrelim =(prelim<50) || (prelim>100) ;
  boolean bMidterm =(midterm<50) || (midterm>100) ; 
  boolean bFinals =(finals<50) || (finals>100) ;

  if (bPrelim ) {
    //print the appropriate error message
  }
  if (bMidterm) {
    //print the appropriate error message
  }
  if (bMidterm) {
    //print the appropriate error message
  }

  student[i][0]=Integer.parseInt(prelim);
  student[i][1]=Integer.parseInt(midterm);
  student[i][2]=Integer.parseInt(finals);  

}  while( bPrelim || bMidterm || bMidterm);

}

If any of the boolean variables are true, that means that the values are wrong. So the while will repeat and ask for the values again. The <i> will not chang since you are inside the same for loop. If all the boolean values are false, means that all the values are correct and the while will be false, so you will continue with the next for loop.

You could also try this:

for (int i=0;i<10;i++) {

do{
 prelim=JOptionPane.showInputDialog("Student Prelim["+i+"]");
 midterm=JOptionPane.showInputDialog("Student Midterm["+i+"]");
 finals=JOptionPane.showInputDialog("Student Finals["+i+"]");

  boolean bPrelim =(prelim<50) || (prelim>100) ;
  boolean bMidterm =(midterm<50) || (midterm>100) ; 
  boolean bFinals =(finals<50) || (finals>100) ;

  if (bPrelim ) {
    //print the appropriate error message
  }
  if (bMidterm) {
    //print the appropriate error message
  }
  if (bMidterm) {
    //print the appropriate error message
  }
}  while( bPrelim || bMidterm || bMidterm);

  student[i][0]=Integer.parseInt(prelim);
  student[i][1]=Integer.parseInt(midterm);
  student[i][2]=Integer.parseInt(finals);  
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
for(int rw=0; rw<10; rw++){
for(int col=0; col<3; col++){
do{
grad=JOptionPane.showInputDialog("Student Prelim["+mj+"]");
student[rw][col]=Integer.parseInt(grad);
if(student[rw][col]<50||student[rw][col]>100){
JOptionPane.showMessageDialog(null,"Inputed Grade of student is not allowed!!!");
}
grad=JOptionPane.showInputDialog("Student Midterm["+mj+"]");
student[rw][col]=Integer.parseInt(grad);
if(student[rw][col]<50||student[rw][col]>100){
JOptionPane.showMessageDialog(null,"Inputed Grade of student is not allowed!!!");
}
grad=JOptionPane.showInputDialog("Student Finals["+mj+"]");
student[rw][col]=Integer.parseInt(grad);
if(student[rw][col]<50||student[rw][col]>100){
JOptionPane.showMessageDialog(null,"Inputed Grade of student is not allowed!!!");
}
}while(student[rw][col]<50||student[rw][col]>100);
mj++;

Let's talk about your code:

You don't need 2 for loops. This is what you wrote:

grad=JOptionPane.showInputDialog("Student Prelim["+mj+"]");
student[rw][col]=Integer.parseInt(grad);
grad=JOptionPane.showInputDialog("Student Midterm["+mj+"]");
student[rw][col]=Integer.parseInt(grad);
grad=JOptionPane.showInputDialog("Student Finals["+mj+"]");
student[rw][col]=Integer.parseInt(grad);

You will put 3 different values:
1) JOptionPane.showInputDialog("Student Prelim["+mj+"]") ;
2) JOptionPane.showInputDialog("Student Midterm["+mj+"]")
3) grad=JOptionPane.showInputDialog("Student Finals["+mj+"]")
At the same location: student[rw][col]

You might want to try this:

for (int i=0;i<10;i++) {

grad=JOptionPane.showInputDialog("Student Prelim["+i+"]");
student[i][0]=Integer.parseInt(grad);

grad=JOptionPane.showInputDialog("Student Midterm["+i+"]");
student[i][1]=Integer.parseInt(grad);

grad=JOptionPane.showInputDialog("Student Finals["+i+"]");
student[i][2]=Integer.parseInt(grad);
}

Assuming that at the location:
[0] there will be the Preilim
[1] there will be the Midterm
[2] there will be the Finals

As for the check I would suggest first to take all the values, check them all and then put them in the array:


for (int i=0;i<10;i++) {

boolean ok = false;
while (!ok) {
 prelim=JOptionPane.showInputDialog("Student Prelim["+i+"]");
 midterm=JOptionPane.showInputDialog("Student Midterm["+i+"]");
 finals=JOptionPane.showInputDialog("Student Finals["+i+"]");

 if (/* check the above values. if they are ok*/) {
  ok=true;

  //put them in the array as showed above
  }

 }

}

The first time the check will be made, ok will be false and you will go in the while. If the values are valid, ok will be turned into true. So the while statement (!ok) will be …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Do you know which part of the code needs to be replaced with JOptionPane? If you don't that probably means that you didn't write it. Tell us what you don't understand and we will help, but no one is going to email you the solution

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Instead of "Student.txt" you could have a String given from input. If you try a String that is not a file then you will get that error.

Even if you don't get that error, you don't know what might happen. I mean since there is a chance that: new PrintWriter( ... ) would throw an Exception, you should make that check in the finally.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If you have never done java then why should you get that position?
And if you are looking for the entire code we are not going to help you. Besides we don't know if it swing or jsp, or if you want to use javascript to do the validation at the client.
All we can tell you is that when the user submits the input,
take it,
put it in String,
convert it into a number,
check if the number is negative or not

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

here this worked for me

import java.io.*;
import java.util.*;

public class Streams {

	public static void main(String[] args) {
		String studentFirstName = "Bob ";
		String studentLastName = " Smith ";
		String finalGrade = "A";
		PrintWriter out = null;
		try {
			out = new PrintWriter(new FileOutputStream("Student.txt"));
			out.print(studentFirstName);
			out.println(studentLastName);
			out.print(finalGrade);
							
		}
		catch (IOException e) 	{
			System.out.println(e);
		}
		finally {
			out.close();
		}
	}
}

EDIT:
javaAddict just beat me to it :(

I would suggest you put this in finally:

if (out!=null) out.close();

If the student.txt file does not exist then an exception will be thrown without PrintWriter taking value. So in the finally you will have a NullPointerException.