2015-06-30 2 views
1

Я создал прототип системы входа в систему для себя, грустно, что это не работает! Я не знаю почему, но вот мой код:Java: система входа в систему не работает

Это код для моего основного класса: `

package darkbyte.tests; 

import java.util.Scanner; 

public class Main { 

    private static FileCreator creator = new FileCreator(); 
    private static FileReader reader = new FileReader(); 

    private static void login() { 
     Scanner input = new Scanner(System.in); 

     boolean passwordExists; 

     System.out.println(); 
     System.out.println("Please enter your username: "); 
     String username = input.nextLine(); 
     System.out.println("Please enter your password: "); 
     String password = input.nextLine(); 

     reader.openFile(username + ".user"); 
     if(reader.doesStringExist(password)) { 
      passwordExists = true; 
     } else { 
      passwordExists = false; 
     } 

     reader.closeFile(); 

     if(passwordExists) { 
      System.out.println("Welcome back to Darkbyte " + username + "!"); 
     } else { 
      System.out.println("The password you entered is incorrect!"); 
      login(); 
     } 
    } 

    private static void register() { 
     Scanner input = new Scanner(System.in); 

     System.out.println(); 
     System.out.println("Please enter the username you desire: "); 
     String username = input.nextLine(); 
     System.out.println("Please enter the password you desire: "); 
     String password = input.nextLine(); 

     creator.openFile(username + ".user"); 
     creator.writeString(username); 
     creator.writeString(password); 
     creator.closeFile(); 
    } 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     System.out.println("Welcome to Darkbyte!"); 
     System.out.println("Would you like to login or register an account?"); 
     System.out.println("Enter 0 to login and any other number to register: "); 
     int choice = input.nextInt(); 

     if(choice == 0) { 
      login(); 
     } else { 
      register(); 
     } 
    } 
} 

Это код для моего класса FileCreator:

package darkbyte.tests; 

import java.io.*; 

import java.util.*; 

public class FileCreator { 

    private Formatter format; 

    public void openFile(String file) { 
     try { 
      format = new Formatter(file); 
     } catch(Exception e) { 
      System.err.println("Darkbyte: There was an error in opening the file!"); 
     } 
    } 

    public void closeFile() { 
     format.close(); 
    } 

    public void writeInteger(int i) { 
     format.format("%i%n", i); 
    } 

    public void writeFloat(float f) { 
     format.format("%f%n", f); 
    } 

    public void writeString(String s) { 
     format.format("%s%n", s); 
    } 

    public void appendInt(String file, int i) { 
     try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) { 
      out.println(i); 
     }catch (IOException e) { 
      System.err.println("Darkbyte: Couldn't find file!"); 
     } 
    } 

    public void appendFloat(String file, float f) { 
     try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) { 
      out.println(f); 
     }catch (IOException e) { 
      System.err.println("Darkbyte: Couldn't find file!"); 
     } 
    } 

    public void appendString(String file, String s) { 
     try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) { 
      out.println(s); 
     }catch (IOException e) { 
      System.err.println("Darkbyte: Couldn't find file!"); 
     } 
    } 
} 

Это код для моего класса FileReader:

package darkbyte.tests; 

import java.io.*; 

import java.util.*; 

public class FileReader { 

    private Scanner scanner; 

    public void openFile(String file) { 
     try { 
      scanner = new Scanner(new File(file)); 
     } catch(Exception e) { 
      System.err.println("Darkbyte: Couldn't find file!"); 
     } 
    } 

    public void closeFile() { 
     scanner.close(); 
    } 

    public void readInt(int i, int lookingFor) { 
     while(i != lookingFor) { 
      if(scanner.hasNext()) { 
       i = Integer.parseInt(scanner.next()); 
      } 
     } 
    } 

    public void readFloat(float f, float lookingFor) { 
     while(f != lookingFor) { 
      if(scanner.hasNext()) { 
       f = Float.parseFloat(scanner.next()); 
      } 
     } 
    } 

    public void readString(String s, String lookingFor) { 
     while(s != lookingFor) { 
      if(scanner.hasNext()) { 
       s = scanner.next(); 
      } 
     } 
    } 

    public boolean doesIntExist(int i) { 
     boolean intIsFound = false; 
     int tempInt; 

     while(scanner.hasNext()) { 
      if(!intIsFound) { 
       tempInt = Integer.parseInt(scanner.next()); 
       if(tempInt == i) { 
        intIsFound = true; 
       } else { 
        intIsFound = false; 
       } 
      } 
     } 

     return intIsFound; 
    } 

    public boolean doesFloatExist(float f) { 
     boolean floatIsFound = false; 
     float tempFloat; 

     while(scanner.hasNext()) { 
      if(!floatIsFound) { 
       tempFloat = Float.parseFloat(scanner.next()); 
       if(tempFloat == f) { 
        floatIsFound = true; 
       } else { 
        floatIsFound = false; 
       } 
      } 
     } 

     return floatIsFound; 
    } 

    public boolean doesStringExist(String s) { 
     boolean stringIsFound = false; 
     String tempString; 

     while(scanner.hasNext()) { 
      if(!stringIsFound) { 
       tempString = scanner.next(); 
       if(tempString == s) { 
        stringIsFound = true; 
       } else { 
        stringIsFound = false; 
       } 
      } 
     } 

     return stringIsFound; 
    } 
} 

вопрос в том, когда я пытаюсь войти в систему, даже если мое имя пользователя и пароль, ар Правильно, он все еще говорит, что мои данные неверны!

Я не уверен, почему, но вы можете помочь мне!

+1

если (tempString == s). Это не то, как вы сравниваете строки в java. – OldProgrammer

+0

Ошибка в том, как я сравниваю строки? –

+0

Да, это так. См. Ответы других. – OldProgrammer

ответ

1

Я думаю, что ошибка находится в

if(tempString == s) { 
    stringIsFound = true; 
} else { 
    stringIsFound = false; 
} 

Изменить его:

if(tempString.equals(s)) { 
    stringIsFound = true; 
} else { 
    stringIsFound = false; 
} 

Всегда используйте equals при сравнении строк, иначе вы сравниваете их ссылку, а не их значение.

+0

Спасибо! –

0

Вы не можете сравнивать строки, как это:

if(tempString == s) { 

Вы должны использовать равно ... Так что вместо == сравнить с equals() и заполнить ваш булево так:

stringIsFound = tempString.equals(s); 
+1

Спасибо, много чувак! –

+0

Собственно, вы можете сравнить такие строки. Единственная проблема: вы можете подумать, что вы сравниваете значения, пока вы сравниваете ссылки. – Stultuske

+1

, тогда вы не сравниваете строки, вы сравниваете «объекты», или в этом случае объекты «String» ... не путайте OP .... –

-1

Ваш код довольно нелогичен. сравнивая пароль, введенный в командной строке, в другой, который вы вводите через командную строку?

Как уже указывал OldProgrammer: вам нужно использовать метод .equals для сравнения равенства строк на значении. == будет проверять их только для ссылочного равенства.

Кроме того, небольшое примечание. Код, как это:

if(reader.doesStringExist(password)) { 
      passwordExists = true; 
     } else { 
      passwordExists = false; 
     } 

может быть легко переработан в несколько эффективнее и легче читать фрагмент кода:

passwordExists = reader.doesStringExist(password); 
+0

Я не думал о том, что это было логическое, спасибо за это! –

Смежные вопросы