I've been spending the last 42 mnins trying to figure the error out on why it states
Resource leaked: 'myFirstname' and many other decleared variables
including myObj when its ran.
You only need one Scanner. That warning is because you never close the Scanner. Normally that is a valuable warning, but when the Scanner wraps System.in closing it will also close System.in so normally you don't close such a Scanner. However, you can do so before the program ends; and the easiest way is a try-with-Resources. Also, you compare the scanner myUsername with the String newUsername and close an if body with an unfortunately placed ;. Fixing all of that, it should look something like
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter your First Name");
String firstName = scan.nextLine();
System.out.println("Enter your Last Name");
String lastName = scan.nextLine();
System.out.println("Enter your Year of Employment");
String yearVar = scan.nextLine();
String newUsername = firstName.substring(0, 1) + lastName;
System.out.println("Username: " + newUsername);
String newPassword = firstName.substring(0, 3) + yearVar + lastName.substring(0, 3);
System.out.println("Password: " + newPassword);
System.out.println("Enter your Username");
String userName = scan.nextLine();
System.out.println("Enter your Password");
String passWord = scan.nextLine();
if (userName.equals(newUsername)) {
System.out.println("Would you like to change your password?");
}
}
You are creating a lot of Scanner object, and closing none of them. This cause the resources to be leaked. To close them and stop the leaks, add: myScanner.close() once you are finished with it.
Besides it could be better to use less scanner objects and reuse one in order to optimize your code.
EDIT: As pointed out by Elliott Frisch answer, closing a scanner wrapping System.in will close it as well, which is usually not wanted.
Related
I've tried different uses for Scanners (I want it to read in Files but I also tried just Strings), and it just skips over the code as if it doesn't exist. No error messages are shown.
public static void main(String[] args)
throws FileNotFoundException {
Scanner test = new Scanner(System.in);
String testLine = test.next();
Scanner input = new Scanner(new File("data.txt"));
while(input.hasNextLine){
String name = input.nextLine();
String letters = input.nextLine();
System.out.println(name + ": " + letters);
}
}
Your code doesn't compile, because hasNextLine() is a function, not a class member.
You are actually reading from System.in at test.next(); - you have to enter some text, then your code will continue to run. It's just waiting for a user input - thus no exception is thrown.
At this line of code:
String testLine = test.next();
your program is waiting for your input. It cannot proceed to next line till you provide an input.
EDIT:
Taking cue from Charlie's comment below, here is a quote about System.in from docs.
The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
More here..
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I'm not sure how dumb I am or if I am missing something quite simple; anyhow, I am trying to get a basic username and password input from the user using the scanner utility.
I have made sure scanner was initialised correctly (Scanner sc = new Scanner(System.in)
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
The issue I am having is when I run this part of the code (above), the output I get looks like this (below) where I start inputting into the password section. Its as though it is just skipping over the first call to the scanner.
Username or Email:
Password: (this is where my input goes)
My only guess is that the scanner is taking the second printing as its input but I am not sure so any help is greatly appreciated.
p.s I will leave the entire method at the bottom incase it helps.
Thanks.
public static void loginPage() throws SQLException{
int requestCounter = 0;
do {
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
boolean validLoginRequest = accountLoginCheck(username, password);
if (validLoginRequest) {
break;
} else {
requestCounter++;
}
} while (requestCounter < 3);
if (requestCounter == 3) {
System.out.println("Too many attempts");
return;
}
System.out.print("TO MAIN MENU");
Remove \n from System.out.print("\nPassword: ");
Username or Email: myemail
Password: pass
I know this might seem like a simple/silly question, but I am trying to keep my code as organized and simple as possible. The problem that I am having is with a while loop for validation. I am validating a string input. I am using the validation simply to make sure that something is entered. The only time I would like the while loop to run is when no information is entered at all, so I would like to include every character and symbol. The question that I have, is that I am wondering if there is a shorter way to include every character possible except for simply hitting enter of course. Here is the simple code snippet.
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");
System.out.print("Please enter your name: ");
String email = input.nextLine();
while(!email.matches("[a-zA-Z]+"));
{
System.out.println("\nPlease enter a valid E-Mail.");
email = input.nextLine();
}
out.println("E-Mail: " + email);
What about restructuring it as a do-while and only having one print/scan?
Scanner input = new Scanner(System.in);
PrintWriter out = new PrintWriter("contactRequest.txt");
String email;
String prompt = "Please enter your name: ";
do {
System.out.print(prompt);
email = input.nextLine();
prompt = "\nPlease enter a valid E-Mail.\n"
} while (!email.matches("[a-zA-Z]+"));
out.println("E-Mail: " + email);
File RaptorsFile = new File("raptors.txt");
File tempFile = new File("raptorstemp.txt");
BufferedWriter output = new BufferedWriter (new FileWriter ("raptorstemp.txt"));
System.out.println("Please enter the following infomation");
System.out.println("Please enter the Player's Name");
String PlayerName=sc.nextLine();
System.out.println("Please enter the Player's FG%");
String FieldGoal=sc.nextLine();
System.out.println("Please enter the Player's 3P%");
String ThreePointer=sc.nextLine();
System.out.println("Please enter the Player's FT%");
String FreeThrow=sc.nextLine();
System.out.println("Please enter the Player's REB");
String Rebounds=sc.nextLine();
System.out.println("Please enter the Player's AST");
String Assists=sc.nextLine();
System.out.println("Please enter the Player's Points");
String Points=sc.nextLine();
String currentLine;
while((currentLine = Raptors.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(PlayerName+"," +FieldGoal+"," +ThreePointer+"," +FreeThrow+"," +Rebounds+"," +Assists+"," +Points)) continue;
output.write(currentLine + System.getProperty("line.separator"));
}
boolean successful = tempFile.renameTo(RaptorsFile);
output.close();
System.out.println("The CarsTemp file will have the new list");
options(Raptors,s);
I am having a problem i just want the user to input only player's name, for example if he inputs Kyle Lowry i want it to delete all of Kyle Lowry's stats. Below is sample of text field.
Lou Williams,41.1,36.3,87.6,60,53,508
Kyle Lowry,44.9,35.1,81.3,160,260,702
Patrick Patterson,48.8,46.0,75.0,177,61,286
Terrence Ross,42.9,38.7,87.9,119,30,411
Jonas Valanciunas,54.2,0.0,79.2,283,16,414
So basically you loop through the file and check the beginning of each line of text to see if it starts with the user input. You can use the String method startsWith() to determine if the line starts with the user input, if it returns false, write the line to a temporary file, if it returns true, skip to the next line in the input file. When you've scanned the entire input file, close them both, rename the original to a backup file and rename the temporary file to the original file. Not a very complicated problem.
You can either use the String.startsWith() method or match to a regular expression.
Solution 1
while ((currentLine = Raptors.readLine()) != null) {
if (!currentLine.startsWith(PlayerName + ",")) { // you could use continue as well, but imho it is more readable to put the output.write inside the condition
output.write(currentLine);
output.newLine();
}
}
This solution has better performance but can result in false positives
Solution 2
while ((currentLine = Raptors.readLine()) != null) {
if (!currentLine.matches(PlayerName + ",\\d[\\d.+],\\d[\\d.+],\\d[\\d.+]),\\d+\\d+,\\d+\\s*") {
output.write(currentLine);
output.newLine();
}
}
This solution exactly matches your criteria but has worse performance and looks uglier.
I think Solution 1 should work well.
Please note, that I have not tested the above pieces of code.
PS: it is always a good idea to adhere to the official coding conventions, such as variable names should start with lowercase characters and so on.
PS2: You could use a PrintWriter instead of BufferedWriter, which gives you additional methods, such as println, which combines write(…) and newLine().
this is the code i use when opening the txt file but it overwrites the data everytime i want to put in more data.
private Formatter X;
private File Y = new File("C:\\Users\\user\\workspace\\Property Charge Management System\\users.txt");
private Scanner Z;
public String[][] PCMSarray;
public boolean OpenFile() {
try{
if(Y.exists()==false){
X = new Formatter("users.txt");
}
return true;
}
catch(Exception e){
System.out.println("File has not yet been created.");
return false;
}
}
This is the code i use to write to the file but this works.
public void WriteToFilecmd(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter your First name");
String Fname = input.next();
System.out.println("Please enter your Last name");
String Lname = input.next();
System.out.println("Please enter your Password");
String Password = input.next();
System.out.println("Please enter your user ID");
String ID = input.next();
System.out.println("Please enter the first address line of your Property");
String addressln1 = input.next();
System.out.println("Please enter the second address line of your Property");
String addressln2 = input.next();
System.out.println("Please enter the third address line of your Property");
String addressln3 = input.next();
System.out.println("Please enter the properties estimated market value");
String EstimatedPropertyValue = input.next();
System.out.println("Please enter your tax owed");
String Taxowed = input.next();
input.close();
X.format("%1$20s %2$20s %3$20s %4$20s %5$20s %6$20s %7$20s %8$20s %9$20s \n",Fname,Lname,Password,ID,addressln1,addressln2,addressln3,EstimatedPropertyValue,Taxowed);
}
Use a different constructor for the Formatter, one that takes a FileWriter (which is Appendable), and construct the FileWriter so that it appends to the end of the file:
// the second boolean parameter, true, marks the file for appending
FileWriter fileWriter = new FileWriter(fileName, true);
Formatter formatter = new Formatter(fileWriter);
As an aside, please learn and follow Java naming rules, else your code will not be easily understood by others (namely us!). Variable and method names should begin with lower-case letters.
Your code is a bit of a mess in a number of respects, but I think that the problem is that you are testing:
C:\\Users\\user\\workspace\\Property Charge Management System\\users.txt
but then you are opening
users.txt
... which happens to be a different file because your "current directory" is not what you think it should be.
Even if that is not what is causing your problem, you should fix it. The way the code is currently written it will break if your current directory is not "C:\Users\user\workspace\Property Charge Management System" when the code is executed.
If you really want to append to the file instead of overwriting it, then you need to use a Formatter constructor that takes an opened output stream or writer ... and supply it with a stream that has been opened in append mode.
I should also not that you've made a serious style mistake in your code. The universal rule for Java code is that variable names and method names must start with a lower-case letter. People assume that anything that starts with an upper-case letter is a class ... unless the name is ALL_CAPITALS, which is reserved for manifest constants.