String [] V = {"a","e","i","o","u"};
Scanner input = new Scanner(System.in);
String A;
System.out.println("Enter any letters");
A=input.next();
if(A.contains(V)) {
System.out.println("success");
}
bottom line. if any of the letters in "V" string are in "A" i want it to continue to "success"
Try to use a foreach loop like this:
for (String string : V) {
if(A.contains(string)) {
System.out.println("success");
}
}
Because the method contains(CharSequence) in the type String is not applicable for the arguments (String[]).
It Works Making some changes to your code
String [] V = {"a","e","i","o","u"};
boolean flag = false;
Scanner input = new Scanner(System.in);
String A;
System.out.println("Enter any letters");
A=input.next();
for(String temp:V)
{
if (A.contains(temp)) {
flag = true;
break;
}
}
if(flag)
System.out.println("Success");
else
System.out.println("Not Success");
Related
I am having a problem trying to understand how I can loop through a keyboard input line of text the user will give ex:
Anika 14 Dan 16
I want to read each token and assign to String name, Int, age, String name, int age. in that order.
This is easy however, if the user enters
Anika Anika Anika Anika 13 13 13 Dan 16
Then I want the program to:
Anika,
Integer needed got String,
Integer needed got String,
Integer needed got String,
13,
String needed got Integer,
String needed got Integer,
Dan,
16
So first one will always be a string which is a word EDIT: "word", second an int and thrid string which is a "word" and fourth int.
However, I can not simulate this.
Scanner scan = new Scanner(System.in);
String name = null;
int age = 0;
String name2= null;
int age2= 0;
if(scan.hasNext() == true)
name = scan.next();
age = scan.nextInt();
name2= scan.next();
age2= scan.nextInt();
I know if I do the top I get the right order, but it is the extra inputs that I would like to ignore but write a statement expression why it's wrong and then continue to search for the next int, or third string and so on.
boolean isstring = false;
boolean isnumber = false;
do {
if (scan.hasNext())
{
name = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age = scan.nextInt();
isnumber=true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
do {
if (scan.hasNext())
{
name2 = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age2 = scan.nextInt();
isnumber = true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
}
I tried to use do while with ifs and It didnt work. My logic is wrong somewhere, and I think it might be the has.next() method.
Any help will be appreciated!!
If the input is a word while waiting for an Integer, it will throw InputMismatchException. nextInt() first read the value as a String an then parse it as a Integer, so if you ignore the value using nextInt, if the value is a word, it will trow the aforementioned Exception.
Using the same logic of your program
The changes should be:
Ignore the input with scan.next()
Check if a String can be or not an Integer (using scan.hasNextInt()), not if is a String, because any Integer can be expressed as a String.
boolean isstring = false;
boolean isnumber = false;
do {
if (!scan.hasNextInt()) {
isstring = true;
name = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
do {
if (!scan.hasNextInt()) {
isstring = true;
name2 = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age2 = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
Using try/catch and one loop
A naive solution using try/catch can be the following
public static void main (String[]args)
{
String name = null;
String name2 = null;
Integer age = null;
Integer age2 = null;
Scanner scan = new Scanner(System.in);
while (scan.hasNext())
{
try
{
if (name == null)
{
System.out.println("Please provide name: ");
name = getNameOrFail(scan);
System.out.println("Name set: " + name);
}
if (age == null)
{
System.out.println("Please provide age: ");
age = getAgeOrFail(scan);
System.out.println("Age set: " + age);
}
if (name2 == null)
{
System.out.println("Please provide name2: ");
name2 = getNameOrFail(scan);
System.out.println("Name2 set: " + name2);
}
if (age2 == null)
{
System.out.println ("Please provide age2: ");
age2 = getAgeOrFail (scan);
System.out.println ("Age2 set: " + age2);
}
}
catch (Exception e)
{
System.out.println(e.getMessage ()); // Print the message put int Exception(message) constructor
scan.nextLine(); // Flush the Scanner cache
}
}
}
public static String getNameOrFail(Scanner scan) throws Exception
{
if (scan.hasNextInt())
throw new Exception("Need String got Integer");
return scan.next();
}
public static Integer getAgeOrFail(Scanner scan) throws Exception
{
if (!scan.hasNextInt())
throw new Exception("Need Integer got String");
return scan.nextInt();
}
Pay attention to the scan.newLine() in the catch clause, this is needed because the Scanner use a cache with the last input, so if is not re-read you enter in a infinite loop condition.
Good luck!
I am taking input from user and it should be string only, but code is not working as I expected. Here is my code `
while(true){
try{
System.out.print("Enter test string");
str=sc.nextLine();
break;
}
catch(InputMismatchException e) {
System.out.println("Please enter String value");
continue;
}
}
System.out.println(str);
`
If I am giving integer value than it should ask again but here it is printing integer value.Also no Special character
If you tried to parse the integer directly, then you'd get a more meaningful exception to catch.
String str = "";
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter test string");
str = sc.nextLine();
Integer.parseInt(str);
System.out.println("Please enter String value");
} catch (NumberFormatException e) {
// You *didn't* get a number; you actually have a String now.
// You can terminate the loop here.
break;
}
}
System.out.println(str);
check if string not number like this:
while(true){
try{
System.out.print("Enter test string");
str=sc.nextLine();
if(isNumeric(str)) {
continue;
}
break;
}
catch(InputMismatchException e) {
System.out.println("Please enter String value");
continue;
}
}
System.out.println(str);
}
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}
If you are only trying to check if the string is NOT a number, you can try
String str = sc.nextLine();
if (StringUtils.isNumeric(str))
System.out.println(str);
but this method will not work if your number has a decimal or something.
check How to check if a String is numeric in Java
for a similar answer
str=sc.nextLine();
takes everything as a string hence there is no exception. Try using statement like this
int num;
&
num=sc.nextInt();
and you will find that the exception will is caught so there is no problem with the code.
Suppose that user will enter "This is 1 String" even though it contains integer but still it is a String. Same applies every time even when user enter "43728" it is still considered a String
here is how you can accomplish your goal
while(true){
System.out.print("Enter test string");
str=sc.nextLine();
Pattern pattern = Pattern.compile("\\d");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
//System.out.println(matcher.group(0));
continue;
}
break;
}
I am trying to write a program that breaks string by '+' sign. For example, if my input is "1+2+3*4". the program will print 1, 2, 3*4. I used \s*\+\s* as my pattern. However, it doesn't print out when it matches the pattern?
private Scanner kbd = new Scanner(System.in);
private String tokenPattern = "\\s*\\+\\s*"; //pattern
public void repl() {
while(true) {
try {
System.out.print("-> ");
String input = kbd.nextLine();
if (input.equals("quit")) break;
Scanner tokens = new Scanner(input);
while(tokens.hasNext(tokenPattern)) { //figure out why its not printing
String token = tokens.next(tokenPattern);
System.out.println(token);
}
tokens.close();
} catch(Exception e) {
System.out.println("Error, " + e.getMessage());
}
}
System.out.println("bye");
}
You should use findWithHorizon
I'm new to programming and trying to write a script that outputs a line containing pangram if the input s is a pangram, or otherwise not pangram. When I compile the script I get an error "reached end of file while parsing." I believe I have balanced parenthesis. Any help would be greatly appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
boolean flag = false;
Scanner key = new Scanner(System.in);
String s = key.nextLine();
String upperCaseStr = s.toUpperCase();
for(char alphabet = 'A'; alphabet <='Z'; alphabet++) {
if(upperCaseStr.indexOf(alphabet)==-1){
flag=true;
break;
}
}
if (flag){
System.out.print("not ");
}
System.out.println("pangram");
}
}
Try this if you want to keep doing multiple inputs:
import java.util.*;
class Main {
public static void main(String[] args) {
boolean continue = true;
while (continue){
boolean flag = false;
Scanner key = new Scanner(System.in);
String s = key.nextLine();
String upperCaseStr = s.toUpperCase();
//if (upperCaseStr.trim() == "QUIT"){
// continue = false;
//} -> don't compare Object's values by their references
continue = "QUIT".equals(s.toUpperCase());
for(char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
if(upperCaseStr.indexOf(alphabet)==-1){
flag=true;
break;
}
}
if (flag){
System.out.print(s + " is not a pangram");
}
else
System.out.println(s + " is a pangram");
}
}
}
Though you need to do something to break out the while loop, like look for if the user types quit or something, but should help
[Edit] Added quit clause
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.