Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Possible Loop Error...

  1. #1
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Possible Loop Error...

    Hi guys, I have a problem: either a loop isn't working, or possibly something else, though I suspect it's the loop. Basically, I have a text file which the string usernamefile reads. The int LINENUM is set to the number of lines in the file. The string username is set to what the user inputs. This is the code:

    while(LINENUM > 0)
                      {
                        usernamefile = dis.readLine();
                        System.out.println("Username:"+username);
                        System.out.println("Check:"+usernamefile);
                        if(username.equals(usernamefile))
                        {
                        	LINENUM=0;
                        }
                        else
                        {
                        	if(LINENUM==0)
                        	{
                        		JOptionPane.showMessageDialog(null, "Incorrect Username.","Error",JOptionPane.ERROR_MESSAGE);
                    			System.exit(0);
                        	}
                        }
                        LINENUM--;
                      }

    So basically, what I'm hoping the loop says is: While there are still lines to check in the file, read the line and compare it with the user input. If it matchs, then leave the loop, if not, then check the lines until you find a match or you run out of lines, in which case exit the program after a JOptionPane message first shows up.

    The problem is that no matter what you input for the username value, it will always say that you have the correct username.

    Here is the output (the println statements) for 4 lines in the textfile, with the usernames in the file being: 1,2,3,4 and the user input being "5":

    Username: 5
    Check: 1
    Username: 5
    Check: 2
    Username: 5
    Check: 3
    Username: 5
    Check: 4

    Then it accepts the username for some reason. So what I'm wondering, is if this is a problem with the loop, or something else?
    Last edited by The_Mexican; November 29th, 2010 at 07:08 PM. Reason: Grammer


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Possible Loop Error...

    Scanner reader = new Scanner("File Name. extension");

    while (reader.hasNext())
    {

    }

    Try that

    It should keep reading till it runs out of lines.

    You probably don't even need to know how many lines there are in the file.

    Unless, there is a space like this

    1
    2

    3
    4

    Then it'd stop after the 2.

    But if it's like
    1
    2
    3
    4

    You shouldn't have a problem.

  3. #3
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Possible Loop Error...

    Can you post all of your code please so I can compile it?
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  4. #4
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Possible Loop Error...

    Quote Originally Posted by javapenguin View Post
    Scanner reader = new Scanner("File Name. extension");

    while (reader.hasNext())
    {

    }

    Try that

    It should keep reading till it runs out of lines.

    You probably don't even need to know how many lines there are in the file.

    Unless, there is a space like this

    1
    2

    3
    4

    Then it'd stop after the 2.

    But if it's like
    1
    2
    3
    4

    You shouldn't have a problem.
    Javapenguin, reading the file is not the problem, I need to know if this is the correct way to state the loop I want.

  5. #5
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Possible Loop Error...

    Quote Originally Posted by JavaPF View Post
    Can you post all of your code please so I can compile it?
    It's a bit long, but okay:

    package layout;
    import javax.swing.AbstractButton;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.SpringLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.io.BufferedInputStream;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
     
    public class testing2 extends JPanel implements ActionListener {
     
    	static String usernamefile;
    	static String passwordfile;
    	static String emailfile;
    	//static String Path = System.getenv("USERPROFILE");
    	static File file = new File("temp");
    	static String dir = file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 4 );//remove the temp - this gives you the directory
    	static File rfile = new File(dir + "username.txt" );
    	File rfile1 = new File(dir + "password.txt" );
    	File rfile2 = new File(dir + "email.txt" );
    	File rfile3 = new File(dir + "linenum.txt");
    	static int linenum = 0;
    	public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
     
    	static int y = 0;
    	static JTextField textField = new JTextField("", 15);
    	static JPasswordField textField2 = new JPasswordField("", 15);
    	static JPasswordField textField3 = new JPasswordField("", 15);
    	static JTextField textField4 = new JTextField("", 15);
    	static JLabel label3 = new JLabel("Re-enter Password: ");
    	static JLabel label4 = new JLabel("Email Address: ");
    	protected static JButton b1;
    	protected static JButton b4;
    	protected JButton b2, b3;
    	public static String username;
    	public static String password;
    	public static String password2;
    	public static String email;
    	static int x = 0;
    	 static JFrame frame = new JFrame("Account Creation");
        private static void createAndShowGUI() {
     
     
     
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Set up the content pane.
            Container contentPane = frame.getContentPane();
            SpringLayout layout = new SpringLayout();
            contentPane.setLayout(layout);
     
            //Create and add the components.
            JLabel label = new JLabel("Username: ");
      //      JTextField textField = new JTextField("", 15);
            JLabel label2 = new JLabel("Password: ");
      //      JPasswordField textField2 = new JPasswordField("", 15);
           // JLabel label3 = new JLabel("Re-enter Password: ");
         //   JPasswordField textField3 = new JPasswordField("", 15);
            //JLabel label4 = new JLabel("Email Address: ");
           // JTextField textField4 = new JTextField("", 15);
            b1 = new JButton("Finish");
            b1.setVerticalTextPosition(AbstractButton.CENTER);
            b1.setHorizontalTextPosition(AbstractButton.LEADING);
            b1.setMnemonic(KeyEvent.VK_F);
            b1.addActionListener(new testing2());
            b1.setActionCommand("Finish");
            b4 = new JButton("Login With Current Account");
            b4.setVerticalTextPosition(AbstractButton.CENTER);
            b4.setHorizontalTextPosition(AbstractButton.LEADING);
            b4.setMnemonic(KeyEvent.VK_L);
            b4.addActionListener(new testing2());
            b4.setActionCommand("Finish");
            contentPane.add(label);
            contentPane.add(textField);
            contentPane.add(label2);
            contentPane.add(textField2);
            contentPane.add(label3);
            contentPane.add(textField3);
            contentPane.add(label4);
            contentPane.add(textField4);
            contentPane.add(b1);
            contentPane.add(b4);
     
            //SET HEIGHT/WIDTH
            layout.putConstraint(SpringLayout.WEST, label,
                                 5,
                                 SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, label,
                                 5,
                                 SpringLayout.NORTH, contentPane);
     
     
            layout.putConstraint(SpringLayout.WEST, textField,
                                 56,
                                 SpringLayout.EAST, label);
            layout.putConstraint(SpringLayout.NORTH, textField,
                                 5,
                                 SpringLayout.NORTH, contentPane);
            //END SET HEIGHT/WIDTH
     
           //SET HEIGHT/WIDTH
     
            layout.putConstraint(SpringLayout.WEST, label2,
                                 5,
                                 SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, label2,
                                 33,
                                 SpringLayout.NORTH, contentPane);
     
     
     
            layout.putConstraint(SpringLayout.WEST, textField2,
                                 57,
                                 SpringLayout.EAST, label2);
            layout.putConstraint(SpringLayout.NORTH, textField2,
                                 33,
                                 SpringLayout.NORTH, contentPane);
     
            //END SET HEIGHT/WIDTH
     
          //SET HEIGHT/WIDTH
     
              layout.putConstraint(SpringLayout.WEST, label3,
                                   5,
                                   SpringLayout.WEST, contentPane);
              layout.putConstraint(SpringLayout.NORTH, label3,
                                   61,
                                   SpringLayout.NORTH, contentPane);
     
     
              layout.putConstraint(SpringLayout.WEST, textField3,
                                   5,
                                   SpringLayout.EAST, label3);
              layout.putConstraint(SpringLayout.NORTH, textField3,
                                   61,
                                   SpringLayout.NORTH, contentPane);
     
              //END SET HEIGHT/WIDTH
     
            //SET HEIGHT/WIDTH
     
                layout.putConstraint(SpringLayout.WEST, label4,
                                     5,
                                     SpringLayout.WEST, contentPane);
                layout.putConstraint(SpringLayout.NORTH, label4,
                                     89,
                                     SpringLayout.NORTH, contentPane);
     
     
     
                layout.putConstraint(SpringLayout.WEST, textField4,
                                     32,
                                     SpringLayout.EAST, label4);
                layout.putConstraint(SpringLayout.NORTH, textField4,
                                     89,
                                     SpringLayout.NORTH, contentPane);
     
                //END SET HEIGHT/WIDTH
     
              //SET HEIGHT/WIDTH
     
                  layout.putConstraint(SpringLayout.WEST, b1,
                                       25,
                                       SpringLayout.WEST, contentPane);
                  layout.putConstraint(SpringLayout.NORTH, b1,
                                       120,
                                       SpringLayout.NORTH, contentPane);
     
                  //END SET HEIGHT/WIDTH
     
                  //SET HEIGHT/WIDTH
     
                  layout.putConstraint(SpringLayout.WEST, b4,
                                       100,
                                       SpringLayout.WEST, contentPane);
                  layout.putConstraint(SpringLayout.NORTH, b4,
                                       120,
                                       SpringLayout.NORTH, contentPane);
     
                  //END SET HEIGHT/WIDTH
     
            //Display the window.
            frame.pack();
            frame.setSize(325, 200);
            frame.setVisible(true);
        }
    	public void actionPerformed(ActionEvent e) {
        	if (e.getSource()==b1) {
        		username = textField.getText();
        		////System.out.println(username);
    			password = textField2.getText();
        		//System.out.println(password);
        		password2 = textField3.getText();
        		//System.out.println(password2);
        		email = textField4.getText();
        		//System.out.println(email);
        		if(password.equals(password2)&&email.contains("@"))
        		{
        			JOptionPane.showMessageDialog(null, "Thank you.","Complete",JOptionPane.INFORMATION_MESSAGE);
        	       // System.out.println(x+"\\Downloads");
        			 try { 
        				 	FileWriter writer = new FileWriter(dir+"username.txt",true);
        				 	FileWriter writer1 = new FileWriter(dir+"password.txt",true);
        				 	FileWriter writer2 = new FileWriter(dir+"email.txt",true);
        				 	FileWriter writer3 = new FileWriter(dir+"writing.txt",true);
        			    	BufferedWriter out = new BufferedWriter(writer); 
        			    	out.newLine();
        			    	out.write(username); 
        			    	out.close(); 
        			    	BufferedWriter out1 = new BufferedWriter(writer1); 
        			    	out1.newLine();
        			    	out1.write(password);
        			    	out1.close(); 
        			    	BufferedWriter out2 = new BufferedWriter(writer2); 
        			    	out2.newLine();
        			    	out2.write(email); 
        			    	out2.close(); 
        			    	BufferedWriter out3 = new BufferedWriter(writer3); 
        			    	out3.write(""); 
        			    	out3.close();
        			    	FileInputStream fis3 = null;
        	                BufferedInputStream bis3 = null;
        	                DataInputStream dis3 = null;
        	                fis3 = new FileInputStream(rfile3);
        	                  bis3 = new BufferedInputStream(fis3);
        	                  dis3 = new DataInputStream(bis3);
        	                  String linenumRead = dis3.readLine();
     
        	                  if(linenumRead==(null))
        	                  {
        	               	linenumRead=("0");
        	                  }
     
     
        	                  int linenumInt = Integer.parseInt(linenumRead);
        			    	linenumInt = linenumInt + 1;
        			    	String rlinenumS = Integer.toString(linenumInt);
        			    	System.out.println(rlinenumS);
        			    	BufferedWriter out4 = new BufferedWriter(new FileWriter(dir + "linenum.txt")); 
        			    	out4.write(rlinenumS); 
        			    	out4.close();
        			    	} catch (IOException e1) { } 
        			System.exit(0);
        		}
        		else
        		{
        			JOptionPane.showMessageDialog(null, "Error.","Error",JOptionPane.ERROR_MESSAGE);
        			textField.setText("");
        			textField2.setText("");
        			textField3.setText("");
        			textField4.setText("");
        		}
        	}
        	if(e.getSource ()==b4)
        	{
        		y=y+1;
        		//System.out.println(y);
        		if(y==1)
        		{
        		frame.setTitle("Login");
        		b1.setVisible(false);
        		b4.setText("Login");
        		textField3.setVisible(false);
        		label3.setVisible(false);
        		textField4.setVisible(false);
        		label4.setVisible(false);
        		textField.setText("");
    			textField2.setText("");
        		y=y+1;
        		}
        		if(y == 3)
        		{
        			username = textField.getText();
            		//System.out.println(username);
        			password = textField2.getText();
            		//System.out.println(password);
     
     
     
     
     
     
     
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    DataInputStream dis = null;
     
                    FileInputStream fis1 = null;
                    BufferedInputStream bis1 = null;
                    DataInputStream dis1 = null;
     
                    FileInputStream fis2 = null;
                    BufferedInputStream bis2 = null;
                    DataInputStream dis2 = null;
     
                    try {
                      fis = new FileInputStream(rfile);
                      bis = new BufferedInputStream(fis);
                      dis = new DataInputStream(bis);
     
                      fis1 = new FileInputStream(rfile1);
                      bis1 = new BufferedInputStream(fis1);
                      dis1 = new DataInputStream(bis1);
     
                      fis2 = new FileInputStream(rfile2);
                      bis2 = new BufferedInputStream(fis2);
                      dis2 = new DataInputStream(bis2);
     
                      // dis.available() returns 0 if the file does not have more lines.
     
                      FileInputStream fis4 = null;
    	                BufferedInputStream bis4 = null;
    	                DataInputStream dis4 = null;
    	                fis4 = new FileInputStream(rfile3);
    	                  bis4 = new BufferedInputStream(fis4);
    	                  dis4 = new DataInputStream(bis4);
    	                  String rlinenumRead = dis4.readLine();
    	                  System.out.println("After read:"+rlinenumRead);
    	                  if(rlinenumRead == null)
    	                  {
    	                	  rlinenumRead=("0");
    	                  }
    	                  System.out.println("After checked for null:"+rlinenumRead);
    	                  int rlinenumInt = Integer.parseInt(rlinenumRead);
                      int LINENUM = rlinenumInt;
                      System.out.println("After converted to int:"+rlinenumInt);
                      while(LINENUM > 0)
                      {
                        usernamefile = dis.readLine();
                        System.out.println("Username:"+username);
                        System.out.println("Check:"+usernamefile);
                        if(username.equals(usernamefile))
                        {
                        	LINENUM=0;
                        }
                        else
                        {
                        	if(LINENUM==0)
                        	{
                        		JOptionPane.showMessageDialog(null, "Incorrect Username.","Error",JOptionPane.ERROR_MESSAGE);
                    			System.exit(0);
                        	}
                        }
                        LINENUM--;
                      }
                      int LINENUM2 = rlinenumInt;
                      while(LINENUM2 > 0)
                      {
                        passwordfile = dis.readLine();
                        System.out.println("Password:"+password);
                        System.out.println("Check:"+passwordfile);
                        if(password.equals(passwordfile))
                        {
                        	LINENUM2=0;
                        }
                        else
                        {
                        	if(LINENUM2==0)
                        	{
                        		JOptionPane.showMessageDialog(null, "Incorrect Password.","Error",JOptionPane.ERROR_MESSAGE);
                    			System.exit(0);
                        	}
                        }
                        LINENUM2--;
                      }
                        emailfile = dis2.readLine();
     
                      // dispose all the resources after using them.
                      fis.close();
                      bis.close();
                      dis.close();
                      fis1.close();
                      bis1.close();
                      dis1.close();
                      fis2.close();
                      bis2.close();
                      dis2.close();
     
                    } catch (FileNotFoundException e1) {
                      e1.printStackTrace();
                    } catch (IOException e1) {
                      e1.printStackTrace();
                    }
     
     
     
                    //System.out.println(usernamefile);
            		//System.out.println(passwordfile);
     
                    JOptionPane.showMessageDialog(null, "Welcome back, "+username+"!","Welcome",JOptionPane.INFORMATION_MESSAGE);
        			javax.swing.SwingUtilities.invokeLater(new Runnable() {
        	            public void run() {
        	                game1.createAndShowGame();
        	            }
        	        });
        			frame.setVisible(false);
     
     
        		}
        	}
    	}
     
     
     
    }

    If you find any other mistakes, let me know I'm sure there are tons xD

    EDIT: Oh, also, for some reason some of the files may occasionally not create themselves if you're not running windows.
    Last edited by The_Mexican; November 30th, 2010 at 04:12 PM.

  6. #6
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: Possible Loop Error...

    Astrix's are your friend.

    //Before
    import javax.swing.AbstractButton;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.SpringLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.io.BufferedInputStream;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;


    //After
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;

  7. #7
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Possible Loop Error...

    Quote Originally Posted by Brt93yoda View Post
    Astrix's are your friend.

    //Before
    import javax.swing.AbstractButton;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.SpringLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.io.BufferedInputStream;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;


    //After
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    Meh, I would've gotten around to it before I turned it in, but really, I don't need them while I'm writing it.

  8. #8
    Member DavidFongs's Avatar
    Join Date
    Oct 2010
    Location
    Minneapolis, MN
    Posts
    107
    Thanks
    1
    Thanked 45 Times in 41 Posts

    Default Re: Possible Loop Error...

    Actually its proper style to write it the way he originally has it. If you are using any IDE that isn't a piece of junk, it should organize the imports for you. (Ctrl-Shift-O in eclipse).

  9. #9
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Possible Loop Error...

    No one knows the problem with my loop?

  10. #10
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Possible Loop Error...

    An alternate way...just iterate over the read lines until the end of file is reached (eg null is returned from readLine())
    String line = null;
    while ( ( line = dis.readLine()) != null ){
       if ( user entry in line ){
            break;
       }
    }

  11. #11
    Member
    Join Date
    Feb 2010
    Posts
    81
    Thanks
    18
    Thanked 1 Time in 1 Post

    Default Re: Possible Loop Error...

    My problem wasn't about how to read the files, it was about the loop. However, I did manage to figure out the problem myself.

Similar Threads

  1. help using for while loop
    By robertsbd in forum What's Wrong With My Code?
    Replies: 8
    Last Post: October 30th, 2010, 02:36 PM
  2. Error when loop used
    By anandkokatnur in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 24th, 2010, 11:17 AM
  3. [SOLVED] logic error: cpu assigning incorrect values in for loop
    By Perd1t1on in forum What's Wrong With My Code?
    Replies: 5
    Last Post: July 25th, 2010, 08:13 PM
  4. for loop and while loop problems
    By Pulse_Irl in forum Loops & Control Statements
    Replies: 4
    Last Post: May 3rd, 2010, 02:09 AM
  5. hi. i want to rewrite this do loop into a while loop.
    By etidd in forum Loops & Control Statements
    Replies: 3
    Last Post: January 26th, 2010, 05:27 PM