I have added an array containing string values in my programme where I want to add an else statement so that if someone enters a value that is not contained in the array, in would print out a message invalid entry.
I have written this in the programme but if a correct value is entered the invalid entry still appears when I run the code.
Enter your name
barry
you are verified you may use the lift
Invalid entry
Invalid entry
Invalid entry
This is what I get
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
// array containing usernames
String [] name = {"barry", "matty", "olly","joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
for (int i = 0; i < name.length; i++) {
if(name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
}else{System.out.println ("Invalid entry");
}
}
Instead of looping over the array, you could just convert the array to a list in use contains:
System.out.println("Enter your name");
String name1 = kb.nextLine();
if (Arrays.asList(name).contains(name1)) {
System.out.println("you are verified you may use the lift");
} else {
System.out.println ("Invalid entry");
}
You can add a boolean variable and keep there information if user has been found.
Try this code:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = { "barry", "matty", "olly", "joey" }; // elements in
// array
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
b = false;
break;
}
}
if (b) {
System.out.println("Invalid entry");
}
}
I think it's because of how you iterate and compare. You compare the value entered to all the names with a for loop. Barry doesn't equal "matty", "olly" or "joey", but your for loop still compares all of them.
Your problem is that if outputs on all comparisons.
I would recommend setting a boolean before the loop, and if it finds a match - set that boolean to true.
Then when the loop has ended, simply check if the boolean is true or false, and output the desired code.
Example:
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
// array containing usernames
String [] name = {"barry", "matty", "olly","joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
Boolean foundMatch = false;
for (int i = 0; i < name.length; i++) {
if(name[i].equals(name1))
foundMatch = true;
}
if(foundMatch)
System.out.println("you are verified you may use the lift");
else
System.out.println ("Invalid entry")
}
You can specify a boolean value to save your status.
boolean contais = false;
for (int i = 0; i < name.length; i++) {
if(name[i].equals(name1)) {
contais = true;
break;// to stop looping
}else{contais = false;}
}
if(contais) {
System.out.println("you are verified you may use the lift");
else {
System.out.println ("Invalid entry");
}
Your code :
if(name[i].equals(name1))
Try This :
if(name[i].equalsIgnoreCase(name1))
Related
The following takes in 10 names and then prints them using System.out.println later. I have an if statement below when I enter a number it warns me "do no enter numbers".
The problem is that after the warning prompt I enter 10 names but the number prints off as the first item in the Array? Then the names print afterwards?
import java.io.*;
public class Input {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] myarray = new String[10];
System.out.println("Enter a 10 names");
for (int i = 0; i < 10; i++) {
myarray[i] = br.readLine();
if (!myarray[i].matches("[a-zA-Z_]+")) {
System.out.println("Invalid name,please do not enter numbers");
}
}
System.out.println("Here are your names");
for (int i = 0; i < 10; i++) {
System.out.println(myarray[i]);
}
}
}
The problem is that when you're rejecting a value you're incrementing the loop counter as if you'd accepted it.
Instead of writing the input to the array, check whether it is valid first:
int i = 0;
while (i < 10) {
String line = br.readLine();
if (line.matches("[a-zA-Z_]+") {
myarray[i++] = line;
} else {
System.out.println("Invalid name");
}
}
Note that i is only incremented when a value is written to the array, and while is used in preference to for since the number of iterations is unknown.
i have written this code that is a hangman game
however the code keeps running when the user enters all the letters unless i write the word so it congrats the user.
i want it to stop when the user inputs all correct letters
import java.util.Scanner;
public class question6 {
public static void main(String[] args) {
String str = "testing";
boolean[] strBoolean = new boolean[str.length()];
Scanner input = new Scanner(System.in);
String test = "";
int counter = 1;
System.out.println("Java word guessing testing");
// main for loop for guessing the letters
while(true){
System.out.println("Key in one word character or your guessed word:");
test = input.nextLine();
if(test.equals(str)){
System.out.println("Congratulation!");
break;
}else{
// for loop for checking the boolean array
for(int b=0; b<strBoolean.length; b++){
if(str.charAt(b) == test.charAt(0)){
strBoolean[b] = true;
}
}
// for loop for printing the correct letters
System.out.print("Trail "+counter+": ");
for(int j=0; j<str.length(); j++){
if(strBoolean[j] == true){
System.out.print(str.charAt(j));
}else{
System.out.print("_");
}
}
System.out.println();
counter++;
}
}
}
}
First off, you are using attempting to compare your String test to the String str, but since you accept new user input for test before the you make that comparison, that conditional will only ever be true if the user types in "testing". So make sure you keep track of the ordering in your instructions in the program for future cases.
You are keeping track of the user's progress by using an array of boolean values. Thus, you could create a method that checks if all the values in said array are true, and return true if so. See example:
import java.util.Scanner;
public class question6 {
public static void main(String[] args) {
String str = "testing";
boolean[] strBoolean = new boolean[str.length()];
Scanner input = new Scanner(System.in);
String test = "";
int counter = 1;
System.out.println("Java word guessing testing");
// main for loop for guessing the letters
while(true){
if(allTrue(strBoolean)){
System.out.println("Congratulation!");
break;
}else{
System.out.println("Key in one word character or your guessed word:");
test = input.nextLine();
// for loop for checking the boolean array
//and the rest of your code
}
}
}
public static boolean allTrue (boolean[] values) {
for (int index = 0; index < values.length; index++) {
if (!values[index]){
return false;
}
}
return true;
}
}
I am new to Java and am creating a project for class that basically asks the user to input a string, and then tests the string and prints whether or not it is a palindrome (the same forwards as backwards... i.e. mom or dad or racecar)
I have gotten the code to work, however i have a loop setup to rerun the program or quit at the end. My problem is that when you rerun the program and enter another String input then it's adding it to the original string.
How can I reset or delete the String input each time so that it starts fresh?
Thank you for any help! Also please note, there may be better or faster ways to accomplish what I have done here but my knowledge of java is limited and I am just getting started, so I have used the knowledge that I have thus far learned. Thanks!!
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class
Ok, figured it out thanks to your guys' help... also rewrote the code so that you can just keep entering new strings or type q to quit instead of the redo question at the end. Hopefully this is cleaner!
import java.util.Scanner;
public class Palindrome_Test {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
int length; //length of word entered by user
boolean redo = true; // boolean to rerun program
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please enter a string, or type Q to quit: ");
input = scan.nextLine();
if (input.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
redo = false;
} else {
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
reverse = "";
}
} while (redo);
} //end main
} //end class
At the end of your while loop add reverse = "";
You'll notice that I moved the following -
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
Inside of the first loop. Although you could simply reset both variables at the end of the loop...
input = "";
reverse = "";
There is no need to (Although, they both work!). By dealing with the scope of the variable inside of the loop, it will essentially "refresh" each time the loop executes.
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// String input = ""; // Word entered by user
// String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class
Alrighty, I'm currently trying to make a program that takes input, in the form of a email address, from the user and checks to see if it has a '#' in it. I want to use a loop to steps through the whole string that the user entered, and checks each character for the '#'. I'm a little lost as to how to get started.
What I did, was use a for loop to iterate through the whole string that the user entered. Then I used a do/while loop to execute a certain line of code until the user entered a valid email. However, it seems to always be valid no matter if it has a '#' or not. I also want to check if it only contains 1 '#' in it. I'm a little lost as you can see, but any help would be appreciated!
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
System.out.print("Enter an email address ");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
valid c = new valid(input);
}
}
class valid
{
String scan2;
char amper = '#';
int i;
valid(String scan1)
{
scan2 = scan1;
for (i = scan2.length() - 1 ; i <= 0; i--)
do
{
System.out.print("That input is invalid");
} while(scan2.indexOf(i) != amper);
System.out.println("That input is valid");
}
}
Since you have to use a loop, I would recommend charAt. It gives you the character at a given index in a string:
boolean found = false;
//where string is the input that you are scanning to find an email address
for (int i = 0; i < string.length; i++){
if (string.charAt(i) == '#'){
found = true;
break;
}
}
if (found){
System.out.println("Found the # character!");
}
Hope it helps you
Loop the each character in the loop.
Check for '#' character
String email = "test#gmal.com";
boolean valid = false;
for (int i=0;i<=email.length();i++) {
if (email.charAt(i)== '#') {
valid = true;
break;
}
}
if (valid) {
System.out.println("This is valid email Id");
} else {
System.out.println("This is an Invalid email Id");
}
Others have already made some helpful comments, but here a few other things I have noticed:
Did you mean to have no "{} after the for statement? Not having that { } can change the program.
In the for statement, did you want it to be i <= 0 or i >= 0? If i starts out being the length of the input string and the test in the for statement is i <= 0, it will never be true unless the input is zero length.
Why do you have a scan1 and a scan2 String?
You may want to consider removing your search logic from the constructor.
I recommend using charAt() method in this case. Here is my code.
import java.util.Scanner;
public class EmailAddr {
private String emailAddress;
public EmailAddr(String emailAddress){
this.emailAddress = emailAddress;
}
public boolean isValid(){
boolean isValid = false;
int nAtSign = 0;
for (int i = 0; i < emailAddress.length(); i++){
if(emailAddress.charAt(i) == '#')
nAtSign++;
}
if(nAtSign == 1)
isValid = true;
return isValid;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your email address: ");
EmailAddr emailTest = new EmailAddr(sc.nextLine());
sc.close();
if(emailTest.isValid()){
System.out.println("The email address is VALID!");
} else {
System.out.println("The email address is INVALID!");
}
}
}
Javadoc concerning indexOf:
the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your E-Mail:");
String line;
do {
line = sc.nextLine();
}
while(line.indexOf('#') == -1);
Why dont you try with regular expressions ??
public class EmailValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean flag;
do{
String pattern="[a-zA-Z]*#[a-zA-Z.]*";
//if u need to think of much better email validation..
//String pattern="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
System.out.println("Enter your Email here :");
flag=scanner.next().matches(pattern);
if(!flag){
System.out.println("Not a valid Email.");
}else{
System.out.println("Valid Email.");
}
}while(!flag);
}
You can use this code as class valid.
class valid {
String scan2;
char amper = '#';
boolean isFound = false;
valid(String scan1) {
scan2 = scan1;
for (int i = 0; i < scan2.length(); i++) {
if (scan2.charAt(i) == amper) {
isFound = true;
}
}
if(isFound) {
System.out.println("Seems like valid email.");
}
}
}
This code based on your class valid and continue some critical errors. As example : "What happen if user input contains more # characters.
I have an array of 8 strings
(Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi")
all referenced by "county"
I'd prompt the user to input a number of 1-8 (iVal), 1 being Carter, 2 being Cocke, etc...
Is there a way I could do this other than using a switch statement?
Also, how would I go about this if the user were to input Washington I'd display "Washington is in the array" and the opposite if the string isn't in the array?
Thanks in advance.
Here is my array.
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
for (int i = 0; i< county.length; i++)
{
System.out.print (county [i]+ "\n");
}
To prompt the user to enter a county, and then display it (without a switch) is simple enough. You could use something like,
String[] county = { "Carter", "Cocke", "Washington", "Greene",
"Hawkins", "Johnson", "Sullivan", "Unicoi" };
Scanner scan = new Scanner(System.in);
for (int i = 0; i < county.length; i++) {
System.out.printf("%d %s%n", i + 1, county[i]);
}
System.out.println("Please select a county from above: ");
int choice = scan.nextInt();
if (choice > 0 && choice <= county.length) {
System.out.println("You selected: " + county[choice - 1]);
} else {
System.out.println("Not a valid choice: " + choice);
}
As for testing if a String array contains a particular String you could write a utility function using the for-each loop like
public static boolean contains(String[] arr, String val) {
if (arr != null) {
for (String str : arr) {
if (str.equals(val)) {
return true;
}
}
}
return false;
}
i was working on the same thing, use ArrayList. this was my code
import java.util.*;
public class Practice{
public static void main(String[] args){
ArrayList<String> mylist = new ArrayList<>();
mylist.add("Maisam Bokhari");
mylist.add("Fawwad Ahmed");
mylist.add("Ali Asim");
mylist.add("Maheen Hanif");
mylist.add("Rimsha Imtiaz");
mylist.add("Mugheer Mughal");
mylist.add("Maaz Hussain");
mylist.add("Asad Shahzada");
mylist.add("Junaid Khan");
System.out.println("Name of the student: "+mylist);
}
}
now if u want a specific name from the list put this in system.out.println
System.out.println("Name of the student: "+mylist.get(1));
now the trick is to let the user enter the number in get( )
for this i made this program, here is the code
first make a scanner
Scanner myScan = new Scanner(System.in);
int a = myScan.nextInt();
System.out.println("Name of the student: "+mylist.get(a));
now it will only print that name depending on what number user have entered !!
I didn't understand well your questions, but I am going to answer on what I have understand.
In case you want to print the value of a given index by the user here is the solution:
Try an i with correct (existing) index and another one which does not exist e.g i=9
public class app
{
public static void main(String[] args)
{
String [] county ={"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
int i = 10; //i is the user input, you should do that using a BufferedReader or Scanner.
try
{
System.out.println(county[i-1]);
}
catch(IndexOutOfBoundsException e)
{
System.out.println("This index doesn't exist");
}
}
}
In case you want to check if a given word exist you can do it that way:
Again try a string which exist and one which does not exist.
public class app
{
public static void main(String[] args)
{
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
String word = "Cocke"; //word is the user input, you should do that using a BufferedReader or Scanner.
boolean found = false;
for(int i=0; i<=7; ++i)
{
if(word == county[i])
{
found = true;
break;
}
}
if(found == true)
{
System.out.println(word + " is in the array.");
}
else
{
System.out.println(word + " is not in the array.");
}
}
}