Broken else statement within a while loop - java

I am currently been working on a program to parse CSV's and then check an inputted email adress against the CSV and if it is valid display their personnel information. The problem I am coming across is the else statement to say that your email is invalid. My current code;
import java.io.*;
import java.util.*;
public class CSVReader123{
public static void main(String[] arg) throws Exception {
BufferedReader CSVFile = new BufferedReader(new FileReader("testa453.csv"));
String dataRow = CSVFile.readLine();
//String email = "ojones#coldmail.net";
//String password = "ocrabc";
Scanner input = new Scanner(System.in);
System.out.println("Please input an email adress");
String email = input.nextLine();
System.out.println("Please input you password");
String password = input.nextLine();
while (dataRow != null){
String[] dataArray = dataRow.split(",");
if ((dataArray[0].equals(email)) && (dataArray[1].equals(password))) {
System.out.println("Your email is valid");
System.out.println("Do you want to display you personel data?(Y or N)");
String personeldata = input.nextLine();
if ((personeldata.equals("yes")) || (personeldata.equals("Yes")) || (personeldata.equals("Y"))){
System.out.println("You email is " +dataArray[0]+".");
System.out.println("You password is " +dataArray[1]+".");
System.out.println("You first name is " +dataArray[2]+".");
System.out.println("You second name is " +dataArray[3]+".");
System.out.println("You street name is " +dataArray[4]+".");
System.out.println("You city name is " +dataArray[5]+".");
System.out.println("You postcode is " +dataArray[6]+".");
}
else if ((personeldata.equals("no")) || (personeldata.equals("No")) || (personeldata.equals("N"))) {
System.out.println("Shutting down.");
break;
}
}
else {
System.out.println("BROKEN");
break;
}
System.out.println();
dataRow = CSVFile.readLine();
}
CSVFile.close();
System.out.println();
}
}
The problem which I am having is that if I try to enter a valid or invalid email it will always print out broken and stop. Although if I remove said if statement the program runs perfectly and the rest of it works correctly. Have I somehow declared it in the incorrect place since the first else statement works perfectly? Any help would be appreciated.

You shouldn't break from the loop. You must use continue, because there can be other rows which will pass the email check. I mean, because the first row does not pass the check, it doesn't mean that the second row won't pass it. You must check all rows.
Make it like this:
else {
System.out.println("BROKEN");
dataRow = CSVFile.readLine();
continue;
}
Or just remove the whole else section like this:
}
//here was the else section
System.out.println();
dataRow = CSVFile.readLine();

Related

Simple Password Check

Just beginning to learn java and I am trying to code a simple password check that gives you tries if you type the incorrect password. The problem is when I type the incorrect password and followed by the correct password it still says its the wrong password.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
while(true) {
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
}
else {
for (int i =6; i>0;i--) {
System.out.println("Incorrect password ");
System.out.println(+ i + " Trys left");
password= scanner.nextLine();
}
}
System.out.println("No more tries");
System.out.println("Program exits");
break;
}
}
I want the program to check if the password is correct or incorrect.
Once you entered the wrong password, code flow stuck in the for loop and remain there for available iterations, no comparison with entered password is going on there so you need to modify the flow. One way to do so as per your initial code posted is
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
int tryCountForFailure = 6;
while (true) {
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
} else {
System.out.println("Incorrect password ");
System.out.println(tryCountForFailure + " Trys left");
tryCountForFailure--;
if (tryCountForFailure == 0) {
System.out.println("No more trys");
System.out.println("Program exits");
break;
}
}
}
scanner.close();
}
In your code, the loop gets stuck in the Else statement. Let's run through the logic.
The program asks for the password and stores it in a password String.
The program check's if that password is right, if it is the program stops and if not it continues to the else statement.
The program uses a for statement to run this block of code 6 times:
System.out.println("Incorrect password ");
System.out.println(+ i + " Trys left");
password = scanner.nextLine();
The problem is even if you enter a correct String for the password field, it never checks if that value is correct. You would be better of refactoring your code so the logic is sound. Let's run through what should happen.
Program defines a variable named count and set's it to 0.
The program uses a while loop to ask if count is less than 6.
The program takes in a password String with a scanner.
The program checks if that password String is equal to the correct password, if yes, it breaks and,
If it does not equal the correct password it adds one to count
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
} else {
count++
}
}

JAVA how to write an exception if the user entered a number instead of a string?

Please explain I'm a little confused with do while .
If I enter the name of the city the first time, everything works correctly.But if I enter a number, I get a corresponding message, and when I try to enter the name of the city for the second time, it gives the same message.(about invalid data)
String town=scanner.nextLine();
boolean tryagain = false;
do {
if (town.charAt(0) >= '0' && town.charAt(0) <= '9'){
System.out.println("You probably entered an invalid data format");
scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
}while (tryagain);
I also tried the try and catch option, but I couldn't write an exception if the user entered numbers instead of a string.It doesn't work. Help please.
try {
System.out.println("enter the name of the city");
town = scanner.nextLine();
} catch (InputMismatchException e) {
System.out.println ("You probably entered an invalid data format ");
scanner.nextLine();
}
Note the difference between this line of code:
town = scanner.nextLine();
and this line of code:
scanner.nextLine();
They both accept input from the console, but only one of them stores that input in the town variable. To update the town variable with the newly entered value, store that value in that variable:
town = scanner.nextLine();
Try this. Inside if block save scanner.nextLine() to town variable in order to check in the next iteration if it consists only from numbers or it is empty:
Scanner scanner = new Scanner(System.in);
String town=scanner.nextLine();
boolean tryagain;
do {
if (town.matches("[0-9]*")){
System.out.println("You probably entered an invalid data format");
town = scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
} while (tryagain);
put it inside try block and try parsing it as Integer
try{
Integer.parseInt(town)
}catch(NumberFormatException nfe){
//this is a string otherwise it would be number
}

Restart while loop if parameters are not fulfilled

So, this program works, it runs, but I want it to be idiot proof! And to do that I need some help..
I don´t want it to go to the next line if the user entered a number or nothing at all!
If I press enter without writing anything at all, it still goes to the next line, and the variable navn comes out completely empty at the end.
It does the same thing if I write a number. How do I make it go back and try the same while loop again if for the answer doesn't fulfil the prompts.
Thank you very much:)
import java.util.Scanner;
class Metoder {
public static void main(String[] args) {
String bosted; //Variable
String navn; //Variable
Scanner in = new Scanner(System.in);
System.out.println("Skriv inn navn: "); //What shows up when you first start the program
while (!in.hasNext("[A-Za-z]+")) { //Only allow letters A-Z
in.next();
System.out.println("Tall horer ikke hjemme i navn, prøv igjen!"); //Prints, "numbers dont belong in names, try again" if what the user entered is a number
}
System.out.println("Takk!"); //Says thank you if the user has entered letters
navn = in.nextLine(); //Proceeds to next line
System.out.println("Skriv inn bosted: "); //Next line, where the user is supposed to enter where he/she lives
while (!in.hasNext("[A-Za-z]+")) { //Excactly the same loop as above
in.next();
System.out.println("Tall hører ikke hjemme i stedsnavn, prøv igjen!");
}
System.out.println("Takk!");
bosted = in.nextLine();
System.out.println("Hei, " + navn + "! Du er fra " + bosted + "."); //Prints out what the user has entered previously in a full sentence.
}
}
Please use this code :
public static void main(String[] args) {
String bosted=""; //Variable
String navn=""; //Variable
Scanner in = new Scanner(System.in);
System.out.println("Skriv inn navn: "); //What shows up when you first start the program
while(in.hasNext()) { //Only allow letters A-Z
navn = in.nextLine();
if(!navn.isEmpty() && navn.matches("[A-Za-z]+")){
System.out.println("Takk!"); //Says thank you if the user has entered letters
in.next();
break;
}
else{
System.out.println("Tall horer ikke hjemme i navn, prøv igjen!"); //Prints, "numbers dont belong in names, try again" if what the user entered is a number
in.next();
System.out.println("Skriv inn navn: ");
continue;
}
}
System.out.println("Skriv inn bosted: ");
while(in.hasNext()) { //Only allow letters A-Z
bosted = in.nextLine();
if(!bosted.isEmpty() && bosted.matches("[A-Za-z]+")){
System.out.println("Takk!"); //Says thank you if the user has entered letters
break;
}
else{
System.out.println("Tall horer ikke hjemme i navn, prøv igjen!"); //Prints, "numbers dont belong in names, try again" if what the user entered is a number
in.next();
System.out.println("Skriv inn bosted: ");
continue;
}
}
System.out.println("Hei, " + navn + "! Du er fra " + bosted + "."); //Prints out what the user has entered previously in a full sentence.
}
You can use the continue keyword to restart a loop essentially.
while(!in.hasNext("[A-Za-z]+")) {
try {
String s = in.nextLine();
if(s.isEmpty() || s.matches("^-?\\d+$")){
throw new Exception("empty string or number detected");
}
} catch (Exception e){
continue;
}
}
In that if condition we are checking if the entered string is empty or is an integer, and we can throw an exception which will cause the while loop to continue asking for input until the condition fails (i.e. passes our test).

How would I split this inputted string? (Java)

I have been working on a program that prompts the user to enter strings, and they are assumed to only enter strings "f name" or "m name." It then lists the names of the males and females entered in separate lists. However, instead of the program listing just the names, it also lists the "f"s and "m"s in front of each name. I tried placing a split method after the user inputs the gender and name, but it doesn't work. I'm sure I'm missing something, but I can't seem to place it. Any help would be appreciated. :)
package labs.lab5;
import java.util.Scanner;
public class NameProcessor {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
UnboundedQueueInterface<String> males;
males = new ArrayUnbndQueue<>(10);
UnboundedQueueInterface<String> females;
females = new ArrayUnbndQueue<>(10);
String input;
do{
System.out.print("Input a gender and name (x done to quit)>");
input = s.nextLine();
input.split(" ");
if(input.startsWith("m"))
{
males.enqueue(input);
}
else if(input.startsWith("f"))
{
females.enqueue(input);
}
else if(input.startsWith("x done"))
{
break;
}
}
while(!input.startsWith("x done"));
System.out.print("males: ");
while(!males.isEmpty())
{
input = males.dequeue();
System.out.println(input + " ");
}
System.out.print("females: ");
while(!females.isEmpty())
{
input = females.dequeue();
System.out.println(input + " ");
}
}
}
Replace males.enqueue(input); with males.enqueue(input.substring(2));
Actually you need to skip first 2 symbols: 'm' (or 'f') and ' '.
You should check for null values and trim the string, but otherwise a simple modification to your code, as follows, works.
do{
System.out.print("Input a gender and name (x done to quit)>");
input = s.nextLine();
String[] tokens = input.split(" ");
if(input.startsWith("m"))
{
males.enqueue(tokens[1]);
}
else if(input.startsWith("f"))
{
females.enqueue(tokens[1]);
}
else if(input.startsWith("x done"))
{
break;
}
}

Java CSV read file validation doesnt work

Background : The code is supposed to go through a csv file (second link), find the username and password and either confirm and display all the info or write error. But now it only says error. Cheers in advance.
http://pastebin.com/YBpKRKe2
http://pastebin.com/9K3nwYG3
import java.io.*;
import java.util.*;
public class CSVRead
{
public static void main(String[] args)
throws Exception
{
BufferedReader CSVFile =
new BufferedReader(new FileReader("test123.csv"));
int invalidvar = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter your email");
String email =input.nextLine();
System.out.println("Enter your password");
String password =input.nextLine();
String dataRow = CSVFile.readLine(); // Read first line.
// The while checks to see if the data is null. If
// it is, we've hit the end of the file. If not,
// process the data.
while (dataRow != null)
{
String[] dataArray = dataRow.split("\\t");
if ((dataArray[0].equals(email))
&&(dataArray[1].equals(password)))
{
System.out.println("You email is " +dataArray[0]+".");
System.out.println("You password is " +dataArray[1]+".");
System.out.println("You first name is " +dataArray[2]+".");
System.out.println("You second name is " +dataArray[3]+".");
System.out.println("You street name is " +dataArray[4]+".");
System.out.println("You city name is " +dataArray[5]+".");
System.out.println("You postcode is " +dataArray[6]+".");
}
else
{
System.out.println("Error");
break;
}
dataRow = CSVFile.readLine();
}
// Close the file once all data has been read.
CSVFile.close();
// End the printout with a blank line.
System.out.println();
} //main()
} // CSVRead
You are only checking the first record after the CSV header. You need to continue checking the records until the EOF is reached:
boolean found = false;
while (!found && dataRow != null) {
String[] dataArray = dataRow.split("\\t");
if ((dataArray[0].equals(email)) && (dataArray[1].equals(password))) {
System.out.println("You email is " + dataArray[0] + ".");
...
found = true;
}
dataRow = csvFile.readLine();
}
System.out.println("Result of CSV search: " + found);
Some side notes:
IO Streams should be closed in a finally block.
Java Naming Conventions indicate variables should start with a lowercase letter.

Categories

Resources