How to well adjust a loop in Java? - java

I am currently writing a little program to ask a PinCode to a user and return ":)" if the Pin is good or ":(" if the Pin is wrong.
My code is made of one java file and one text file.
This is the code :
import java.io.*;
import java.util.*;
public class Main {
static public boolean readPinsData(File dataFile, ArrayList<Integer> data) {
boolean err = false;
try {
Scanner scanner = new Scanner(dataFile);
String line;
while (scanner.hasNext()) {
line = scanner.nextLine();
try {
data.add(Integer.parseInt(line));
} catch (NumberFormatException e) {
e.printStackTrace();
err = true;
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
err = true;
}
return err;
}
public static void main(String[] args) {
System.out.println("-----------------------");
System.out.println("MY APP");
System.out.println("-----------------------");
Console console = System.console();
int pinSize = 0;
int nbTry = 0;
do{
do{
char passwordArray[] = console.readPassword("Enter pin: ");
pinSize = passwordArray.length;
if(pinSize != 4){
System.out.println("Pin must be 4 digits");
} else {
System.out.println("Checking...");
}
ArrayList<Integer> pins = new ArrayList<Integer>();
readPinsData(new File("bdd.txt"), pins);
//System.out.println(pins);
//System.out.println(passwordArray);
String[] thePins = new String[pins.size()];
for (int i = 0; i < thePins.length; i++) {
thePins[i] = pins.get(i).toString();
}
String passEntered = String.valueOf(passwordArray);
for(int i = 0 ; i < thePins.length ; i++){
if(passEntered.equals(thePins[i]) && pinSize == 4){
System.out.println(":)");
} else if(!passEntered.equals(thePins[i]) && pinSize == 4){
nbTry++;
}
}
}while(nbTry < 3);
}while(pinSize != 4);
}
}
This is bdd.txt where all the good Pins are stored :
1111
2222
3333
4444
5555
6666
7777
8888
9999
Actually my problem is to limit the number of try to 3 tries. I need to explain:
--> the user has to enter a pin
--> either he enters a good 4 digits pin and it prints ":)" (and the app is done)
--> either he enters a wrong 4 digits pin and it prints ":(" and the nbTry must be ++.
In this case he has only 2 tries left
--> he also can enter a 1-digit pin or 2-digits pin or 3-digits pin ... and in this case nbTry is not affected, he just have to re-enter a 4 digits pin.
I can not find out how to do with the nbTry left part.. Any ideas ?

Do you want him to be able to enter a 4 digit pin only or do you want him to be able to enter any length of pin?
Edit:
Reading your main I saw that you have two 'do...while`. If you change the order of them It should work. I can't test it atm because I'm on mobile bit try it like this:
do {
do {
....
} while (pinSize != 4);
} while (nbTry < 3);
Edit2:
boolean loginCorrdect = false;
for (int i = 0; i < thePins.length; i++) {
if (passEntered.equals(thePins[i]) && pinSize == 4) {
System.out.println(":)");
booleanCorrect = true;
break;
} else if (!passEntered.equals(thePins[i]) && pinSize == 4) {
System.out.println(":(");
}
}
if(!booleanCorrect && pinSize == 4){
nbTry++;
}
Hope you got it as its hard to type on mobile.
The full main code:
public static void main(String[] args) {
System.out.println("-----------------------");
System.out.println("MY APP");
System.out.println("-----------------------");
Console console = System.console();
int pinSize = 0;
int nbTry = 0;
boolean authenticated = false;
do {
do {
char passwordArray[] = console.readPassword("Enter pin: ");
pinSize = passwordArray.length();
if (pinSize != 4) {
System.out.println("Pin must be 4 digits");
} else {
System.out.println("Checking...");
}
ArrayList<Integer> pins = new ArrayList<Integer>();
readPinsData(new File("bdd.txt"), pins);
// System.out.println(pins);
// System.out.println(passwordArray);
String[] thePins = new String[pins.size()];
for (int i = 0; i < thePins.length; i++) {
thePins[i] = pins.get(i).toString();
}
String passEntered = String.valueOf(passwordArray);
for (int i = 0; i < thePins.length; i++) {
if (passEntered.equals(thePins[i]) && pinSize == 4) {
System.out.println(":)");
authenticated = true;
break;
}
}
} while (pinSize != 4);
if (!authenticated && pinSize == 4) {
System.out.println(":(");
nbTry++;
}
} while (nbTry < 3 && !authenticated);
}

If I understand your question, you can do it like so (and you should close() your Scanner when done) -
static public boolean readPinsData(File dataFile, ArrayList<Integer> data) {
boolean err = false;
Scanner scanner = null; // so we can close the Scanner.
try {
scanner = new Scanner(dataFile);
String line;
while (scanner.hasNext()) {
line = scanner.nextLine();
try {
data.add(Integer.parseInt(line));
} catch (NumberFormatException e) {
e.printStackTrace();
err = true;
}
// Limit it to 3 attempts. Set err on 3rd.
if (data.size() >= 3) {
err = true;
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
err = true;
} finally {
if (scanner != null) { // Close the Scanner.
scanner.close();
}
}
return err;
}

What helps is to have a top-down refinement of your control flow / logic.
As this reeks a bit of home work, just an idea:
Set<String> pins = readPINs();
boolean authenticated = false;
for (int attempt = 0; attempt < 3; ++attempt) {
String pin = askForPIN();
if (!isSyntacticalValidPIN(pin)) {
giveError();
break;
} else if (pins.contains{pin)) {
authenticated = true;
break;
}
}
if (authenticated) {
offerMenu();
}

Related

The password validation sends out the wrong output?

The program that I've written is giving me the wrong output. It verifies whether the input password is 6 characters long with letters and numbers, if one of the requirement is not met, then it should say "Invalid Password." Otherwise, then it should output "Password Accepted." But when I enter more than 6 character long password, though the password is all letters, it still say password accepted.
import java.util.*;
public class passwd {
public static void main(String[] args)
{
String in_pass;
int i = 0, x = 0, l = 0, d = 0;
boolean valid_len;
Scanner in = new Scanner(System.in);
System.out.print("Enter Password: ");
in_pass = in.next();
int len = in_pass.length();
valid_len = (len >= 6) ? true : false;
char passwd_l;
char passwd_d;
if (valid_len == false)
{
System.out.println("Invalid Password");
}
else if (valid_len == true)
{
for (i = 0, x = 0; i < len; i++, x++)
{
passwd_l = in_pass.charAt(i);
if (Character.isLetter(passwd_l))
{
l += i;
}
passwd_d = in_pass.charAt(x);
if (Character.isDigit(passwd_d))
{
d += x;
}
}
}
if (i > 0 && x > 0)
{
System.out.println("Password Accepted");
}
}
}
Check out this one!
else if (valid_len == true){
for (i = 0; i < len; i++){
passwd_l = in_pass.charAt(i);
if (Character.isLetter(passwd_l))
{
l ++;
}
if (Character.isDigit(passwd_l))
{
d ++;
}
}
}
if (l > 0 && d > 0){
System.out.println("Password Accepted");
}

Retrieving the two smallest inputs from an array in java

I'm taking an Intro to CS and one of the assignments asks for the 2 smallest numbers based off of user input. I've tried for about 3 days and just can't figure out why my code isn't working, and the more I work at it the more frustrated I get.
public class TwoSmallest {
public static void main(String[] args){
System.out.print("How many numbers will you be inputing? ");
int howManyNums = IO.readInt();
int[] arrayScores = new int[howManyNums];
for(int j = 0;j < howManyNums;j++){
System.out.print("Inuput number "+(j+1)+": ");
arrayScores[j]=IO.readInt();
int tinyNum1 = arrayScores[0];
int tinyNum2 = arrayScores[1];
for(int m = 0;tinyNum1 < arrayScores[m];m++){
//if (tinyNum1 < m) {
tinyNum1 = arrayScores[m];
}
for (int n = 1;tinyNum2 < arrayScores[n];n++){
//if (tinyNum2 < n) {
tinyNum2 = arrayScores[n];
}
if (tinyNum2 < tinyNum1){
int swapTinyNum1 = tinyNum1;
tinyNum2 = swapTinyNum1;
}
System.out.println("Smallest number: "+tinyNum1);
System.out.println("Followed by: "+tinyNum2);
}
We use the IO.readInt() for user input which I use to define the size of the array. I use it again at arrayScores[j]=IO.readInt(); to load the array. It kind of works when the user inputs the lower numbers first, but not when the higher numbers are input first. I think I'm having problems with retrieving the value at the designated index. It's probably a mess, but if anyone can help me out, it would definitely be appreciated. And here is the IO module we use, if this helps. I'm going to continue my endless battle at making this thing work..
import java.io.*;
public class IO
{
private static BufferedReader kb =
new BufferedReader(new InputStreamReader(System.in));
private static BufferedReader fio = null;
public static boolean openFile(String filename){
try{
fio = new BufferedReader(new FileReader(filename));
return true;
}catch (IOException e){ return false;}
}
public static String readLine(){
if (fio == null)
return null;
try{
return fio.readLine();
}catch(IOException e){ return null;}
}
public static String readString()
{
while (true) {
try {
return kb.readLine();
} catch (IOException e) {
// should never happen
}
}
}
public static int readInt()
{
while (true) {
try {
String s = kb.readLine();
return Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.print("That is not an integer. Enter again: ");
} catch (IOException e) {
// should never happen
}
}
}
public static double readDouble()
{
while (true) {
try {
String s = kb.readLine();
return Double.parseDouble(s);
} catch (NumberFormatException e) {
System.out.print("That is not a number. Enter again: ");
} catch (IOException e) {
// should never happen
}
}
}
public static char readChar()
{
String s = null;
try {
s = kb.readLine();
} catch (IOException e) {
// should never happen
}
while (s.length() != 1) {
System.out.print("That is not a single character. Enter again: ");
try {
s = kb.readLine();
} catch (IOException e) {
// should never happen
}
}
return s.charAt(0);
}
public static boolean readBoolean()
{
String s = null;
while (true) {
try {
s = kb.readLine();
} catch (IOException e) {
// should never happen
}
if (s.equalsIgnoreCase("yes") ||
s.equalsIgnoreCase("y") ||
s.equalsIgnoreCase("true") ||
s.equalsIgnoreCase("t")) {
return true;
} else if (s.equalsIgnoreCase("no") ||
s.equalsIgnoreCase("n") ||
s.equalsIgnoreCase("false") ||
s.equalsIgnoreCase("f")) {
return false;
} else {
System.out.print("Enter \"yes\" or \"no\": ");
}
}
}
public static void outputStringAnswer(String s)
{
if (s != null) {
System.out.println("RESULT: \"" + s + "\"");
} else {
System.out.println("RESULT: null");
}
}
public static void outputIntAnswer(int i)
{
System.out.println("RESULT: " + i);
}
public static void outputDoubleAnswer(double d)
{
System.out.println("RESULT: " + d);
}
public static void outputCharAnswer(char c)
{
System.out.println("RESULT: '" + c + "'");
}
public static void outputBooleanAnswer(boolean b)
{
System.out.println("RESULT: " + b);
}
public static void reportBadInput()
{
System.out.println("User entered bad input.");
}
}
To find the two smallest number:
int[] numbers = {}; // whatever.
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] < min1) {
min2 = min1;
min1 = numbers[i];
} else if (numbers[i] < min2) {
min2 = numbers[i];
}
}

not getting correct numbers in for loop

Hy there. Below you can see sagment of my code. So lets go to the problem.
int i is not returning correct values and i cannot figure it out why.
LIST: [AGRFT, AGRFT, ARNES, ASCII, ASEAN, Aaron, Abdul, Abdul]
So for example. User inputs AS***, the program should return i is at 2. However i am getting i is at 0.
If i remember right it should go like this:
User_input= AS***
User_input.lenght() should be 5
first it should be user_input.charAt(0)=='*' NO
second it should be user_input.charAt(1)=='*' NO
third it should be user_input.charAt(2)=='*' YES
BREAK
i is at 2.
SO what am i missing?
I am getting 0.
Oh and also at
for(i=0; i < user_input.length();i++){
i am getting warning that i++ is Dead code?
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i is at "+ i);
this is my full code for refrence. What it does it reads from txt file add wor
public class proba {
public static void main(String[] args) {
String izbira;
int dolzina=0;
int i=0;
Scanner in = new Scanner(System.in);
String user_input;
Scanner input = new Scanner(System.in);
String regex;
List<String> list5 = new ArrayList<String>();
int beseda;
String prefix = null;
try {
File file = new File("sort.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
if (vrstica.length() == 5) {
list5.add(vrstica);
}
}
System.out.println(list5);
do{
do {
System.out.println("Enter lenght of word:");
if (in.hasNextInt()) {
dolzina = in.nextInt();
} else if (in.hasNextLine()) {
System.out.printf("Wrong entry!%n ",
in.nextLine());
}
} while (dolzina <= 0);
Collections.sort(list5);
System.out.println("Enter a word for unknown character enter * :");
user_input = input.nextLine();
System.out.println("Sorted list: [length: " + list5.size() + "]");
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i je"+ i);
prefix=user_input.substring(0,i);
System.out.println(prefix);
int start=binarySearchfirst(list5,prefix);
int end=binarySearchlast(list5,prefix);
System.out.println(start);
System.out.println(end);
for (int b=start;b<=end;b++)
{
user_input = user_input.replace("*", ".");
String s = (String) list5.get(b);
if (s.matches(user_input))
System.out.println(s);
}
}
dolzina=-1;
System.out.println("Ponovni vnos (da/ne):");
Scanner inn= new Scanner (System.in);
izbira = inn.next();
}while (izbira.equalsIgnoreCase("da"));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}}
public static int binarySearchfirst(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == 0 || !integerList.get(mid - 1).startsWith(prefix)) {
return mid;
} else {
high = mid - 1;
}
} else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
public static int binarySearchlast(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size()-1;
while (low <= high) {
int mid = (low+high)/2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == integerList.size()-1 || !integerList.get(mid+1).startsWith(prefix)) {
return mid;
}
else {
low = mid+1;
}
}
else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid+1;
}
else {
high = mid-1;
}
}
return high;
}
}
You have an extra semi-colon after your if statement:
for(i=0; i < user_input.length();i++)
{ if (user_input.charAt(i)=='*');
break;
}
So the break is executed the first time through the loop no matter what. This is also why i++ is being reported as dead code...it's never being executed.

Finding a word with the most consecutive vowels in a text file, using Java

I have a problem in Java that must be solved without anything but the most basic code. It cannot include arrays, and I can't really import anything other than what's showing in my code. The question is this:
The file words.txt on the book’s website contains 87,314 words from the English language.
Write a program that reads through this file and finds the word that has the most consecutive vowels.
I'm brand new to programming, so I've got some ideas of what to do but not precisely how to put it all together. I'm really stuck on this question. Any help would be much appreciated.
Here's what I've come up with, but it's clearly incorrect, and I've already spent many hours on it, including researching here and other places, and trying the code I found. I'm not expecting anyone to do the homework for me, but if you could give me some guidance, it would be very much appreciated. Here's what I have so far:
package vowels;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Vowels
{
public static void main(String[] args)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("words.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
System.exit(0);
}
String eachWord = fileIn.next();
String mostConsecutiveVowels = "";
int w = 0;
int z;
int consecutiveVowels = 0;
int mostConsecutiveVowelsInWord = 0;
int wordWithMostConsecutiveVowels = 0;
boolean vowel;
boolean previousVowel;
boolean mostVowels;
while (fileIn.hasNext())
{
while(consecutiveVowels >= mostConsecutiveVowelsInWord)
{
mostVowels = true;
}
char a = eachWord.charAt(w);
if (a=='a'||a=='e'||a=='i'||a=='o'||a=='u')
{
consecutiveVowels++;
consecutiveVowels = mostConsecutiveVowelsInWord;
}
for(z = 1; z <= eachWord.length(); z++)
{
char b = eachWord.charAt(z);
char c = eachWord.charAt(z-1);
while (b=='a'||b=='e'||b=='i'||b=='o'||b=='u')
{
vowel = true;
}
while (c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
{
previousVowel = true;
}
if (vowel = false && previousVowel = true && mostVowels = false;)
{
consecutiveVowels = 0;
}
else if (vowel = false && previousVowel = true && mostVowels = true;)
{
consecutiveVowels = mostConsecutiveVowelsInWord;
}
else if (vowel = true && previousVowel = false)
{
consecutiveVowels = 1;
}
else if (vowel = true && previousVowel = true && mostVowels = true;)
{
consecutiveVowels++;
consecutiveVowels = mostConsecutiveVowelsInWord;
}
else if (vowel = true && previousVowel = true && mostVowels = false;)
{
consecutiveVowels++;
}
}
}
if (mostVowels)
{
if(eachWord.length()>mostConsecutiveVowels.length())
{
mostConsecutiveVowels = eachWord;
}
}
System.out.println("The word in words.txt with the most consecutive vowels is " + mostConsecutiveVowels);
fileIn.close();
}
}
This is my solution. However, you should try coming up with your own as well for practice, and if you want to use the comments in my code as suggestions.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Vowels {
public static final String WORD_FILE = "words.txt";
public static void main(String[] args) {
try (Scanner fileScanner = new Scanner(new FileInputStream(WORD_FILE))) {
String targetWord = null; // word with most consecutive vowels
int maxConsecutiveVowels = 0;
while (fileScanner.hasNext()) {
// for each word in the file
String word = fileScanner.next().toLowerCase();
int consecutiveVowels = 0;
for (int i = 0; i < word.length() && i < word.length() - maxConsecutiveVowels + consecutiveVowels; i++) {
// for each character in the word, and exit early if the word is not long enough to beat maxConsecutiveVowels
if (isVowel(word.charAt(i))) {
// consonants reset this to 0
consecutiveVowels++;
} else {
// reached the end of the vowels so check if we beat maxConsecutiveVowels
if (consecutiveVowels > maxConsecutiveVowels) {
maxConsecutiveVowels = consecutiveVowels;
targetWord = word;
}
consecutiveVowels = 0;
}
}
// reached the end of the vowels at the end of the word so check if we beat maxConsecutiveVowels
if (consecutiveVowels > maxConsecutiveVowels) {
maxConsecutiveVowels = consecutiveVowels;
targetWord = word;
}
}
if (targetWord == null) {
System.out.println("there are no words with vowels in " + WORD_FILE);
} else {
System.out.println("the word in " + WORD_FILE + " with the most consecutive vowels is '" + targetWord + "'");
System.out.println("it has " + maxConsecutiveVowels + " consecutive vowels");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static boolean isVowel(char c) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
}
return false;
}
}

Java won't stop reading from input

Java won't stop reading from input.
I understand that maybe this while loop might have something to do with it:
while(input.hasMoreTokens());
{
array1[counter] = input.nextToken();
counter++;
}
But I don't see why the loop should be a problem because I am already calling .nextToken() which should advance the token.
Here's the full source code:
import java.io.*;
import java.util.*;
class HelloWorld
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
HelloWorld myWork = new HelloWorld(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String idata;
StringTokenizer input;
while ((idata = HelloWorld.ReadLn (255)) != null)
{
input = new StringTokenizer (idata);
String[] array1 = {};
int counter = 0;
while(input.hasMoreTokens());
{
array1[counter] = input.nextToken();
counter++;
}
int[] array2 = {};
for(int a = 0; a < array1.length; a++)
{
array2[a] = Integer.parseInt(array1[a]);
}
int[] array3 = {};
for(int b = 0; b < array2.length; b++)
{
if ( array2[b] != 42)
{
array3[b] = array2[b];
}
else
{
break;
}
}
String string = "";
for( int c = 0; c < array3.length; c++)
{
if( c < array3.length - 1)
{
string += array3[c] + "\n";
}
else
{
string += array3[c];
}
}
System.out.println(string);
}
}
}
You have a stray semicolon at the end of the while:
while(input.hasMoreTokens());
^ REMOVE THIS

Categories

Resources