Taking a string from a user and checking it against a "Password" variable - string

I am trying to create a program that takes a string from a user and checks it against a "password" variable. If the password is equal it prints "valid" if not then "invalid"
Here is what I have so far, it looks correct to me, but it apparently isn't.
import java.util.*;
class WS6Q5 {
public static void main (String[] args){
Scanner in=new Scanner(System.in);
String s =" ";
int x = 123;
System.out.println("Please type in the Password");
s=in.nextLine();
if (s.length()==x){
System.out.println("Access Granted");
}
else if (s.length()!=x){
System.out.println("Invalid");
}
}

As one might expect, s.length() gives you the length, in characters, of string s. Your variable x is set to the integer (not string!) value 123. So your if-statement is seeing whether x is 123 characters long. Probably not what you want!
You probably want x to be a string. String x = "123".
You want to compare the value of x to the value of s. Look at String.equals() (http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object))

Related

Program to find if a string is a palindrome keeps on failing. Even after using toLowerCase() command for both strings, output doesn't come

import java.util.Scanner;
class Palindrome_string
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String a = sc.nextLine();
int b = a.length();
String rev = "";
for (int i = b - 1; i >= 0; i--)
{
char c = a.charAt(i);
rev = rev + c;
}
System.out.println("Original word "+a);
System.out.println("Reversed word "+rev);
a = a.toLowerCase();
rev = rev.toLowerCase();
if (a == rev)
{
System.out.println("It is a palindrome");
}
else
{
System.out.println("It is not a palindrome");
}
sc.close();
}
}
The program compiles properly. Still, when running the program, the message which tells if it is a palindrome prints incorrectly. What changes do I make? Here is a picture of the output. Even though the word 'level' (which is a palindrome) has been inputted, it shows that it isn't a palindrome. What changes should I make? output pic
You should not use == to compare two strings because it compares the reference of the string, i.e. whether they are the same object or not.
Use .equals() instead. It tests for value equality. So in your case:
if (a.equals(rev))
{
System.out.println("It is a palindrome");
}
Also try not to use single-letter variable names except for index variables when iterating over a list etc. It's bad practice.

Making sure every Alphabet is in a string (Kotlin)

So I have a question where I am checking if a string has every letter of the alphabet in it. I was able to check if there is alphabet in the string, but I'm not sure how to check if there is EVERY alphabet in said string. Here's the code
fun isPangram (pangram: Array<String>) : String {
var panString : String
var outcome = ""
for (i in pangram.indices){
panString = pangram[i]
if (panString.matches(".^*[a-z].*".toRegex())){
outcome = outcome.plus('1')
}
else {outcome = outcome.plus('0')}
}
return outcome
}
Any ideas are welcomed Thanks.
I think it would be easier to check if all members of the alphabet range are in each string than to use Regex:
fun isPangram(pangram: Array<String>): String =
pangram.joinToString("") { inputString ->
when {
('a'..'z').all { it in inputString.lowercase() } -> "1"
else -> "0"
}
}
Hi this is how you can make with regular expression
Kotlin Syntax
fun isStrinfContainsAllAlphabeta( input: String) {
return input.lowercase()
.replace("[^a-z]".toRegex(), "")
.replace("(.)(?=.*\\1)".toRegex(), "")
.length == 26;
}
In java:
public static boolean isStrinfContainsAllAlphabeta(String input) {
return input.toLowerCase()
.replace("[^a-z]", "")
.replace("(.)(?=.*\\1)", "")
.length() == 26;
}
the function takes only one string. The first "replaceAll" removes all the non-alphabet characters, The second one removes the duplicated character, then you check how many characters remained.
Just to bounce off Tenfour04's solution, if you write two functions (one for the pangram check, one for processing the array) I feel like you can make it a little more readable, since they're really two separate tasks. (This is partly an excuse to show you some Kotlin tricks!)
val String.isPangram get() = ('a'..'z').all { this.contains(it, ignoreCase = true) }
fun checkPangrams(strings: Array<String>) =
strings.joinToString("") { if (it.isPangram) "1" else "0" }
You could use an extension function instead of an extension property (so it.isPangram()), or just a plain function with a parameter (isPangram(it)), but you can write stuff that almost reads like English, if you want!

Get String Between 2 Strings with Arduino

I am looking for a way to get a String between 2 Strings using Arduino. This is the source String:
Hello, my name is John Doe# and my favourite number is 32#.
The output has to be:
String name = "John Doe"; //Between "name is " and "#"
String favouriteNumber = "32"; //Between "number is " and "#"
How can this be achieved with Arduino?
I am not able to find any information online about this. Those examples for C are not working anyway. I understand that using String is not recommended in Arduino, but I have to do it this way to make things simpler.
By the way, this method of using a '#' to indicate the end of the data is not an ideal way to do it as I would like the input to be more human readable and more natural. Would anyone please suggest another way to do this as well?
Thanks in advance!
Function midString find the substring that is between two other strings "start" and "finish". If such a string does not exist, it returns "". A test code is included too.
void setup() {
test();
}
void loop() {
delay(100);
}
String midString(String str, String start, String finish){
int locStart = str.indexOf(start);
if (locStart==-1) return "";
locStart += start.length();
int locFinish = str.indexOf(finish, locStart);
if (locFinish==-1) return "";
return str.substring(locStart, locFinish);
}
void test(){
Serial.begin(115200);
String str = "Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive";
Serial.print(">");
Serial.print( midString( str, "substring", "String" ) );
Serial.println("<");
Serial.print(">");
Serial.print( midString( str, "substring", "." ) );
Serial.println("<");
Serial.print(">");
Serial.print( midString( str, "corresponding", "inclusive" ) );
Serial.println("<");
Serial.print(">");
Serial.print( midString( str, "object", "inclusive" ) );
Serial.println("<");
}
just searched for this and saw no answer so i cooked one up.
i prefer working with String as well because of code readability and simplicity.
for me its more important than squeezing every last drop of juice out of my arduino.
String name = GetStringBetweenStrings("Hello, my name is John Doe# and my favourite number is 32#." ,"name is ","#");
String GetStringBetweenStrings(String input, String firstdel, String enddel){
int posfrom = input.indexOf(firstdel) + firstdel.length();
int posto = input.indexOf(enddel);
return input.substring(posfrom, posto);
}
watch out for the first case its fine, but for the second one you would have to change the second filter sting to "#." so it doesn't use the first occurrence of the #

java apps. string manipulation

I want to limit the no. of character that can be put on JTextField because on my database I have this column that has Sex,Status (which the no. of char. allowed is 1 only).
and Middle Initial (which the no. of char. allowed is 2 only).
This what I have in my mind :
(for Sex,Status column)
String text = jTextField2.getText();
int count = text.();
if (count>1) {
(delete the next character that will be input)
}
(for M.I. column)
String text = jTextField1.getText();
int count = text.();
if (count>2) {
(delete the next character that will be input)
}
is this possible? is there a command that will delete the next character, so the no. of char. is acceptable for my database?
Sure. Just use String#substring.
String middleInitial = "JKL";
middleInitial.substring(0, 2);
System.out.println(middleInitial); // => JK
Similarly, you can use substring(0, 1) for sex.
It might be better if sex is an enum, though.
public enum Sex {
MALE("m"), FEMALE("f");
final String symbol;
private Sex(String symbol) {
this.symbol = symbol;
}
}
Now you can use it like this:
String sex = "male";
Sex.valueOf(sex.toUpperCase());
Or directly
Sex.MALE;
Instead of a text field for sex, you might use a JComboBox so the user can only choose one of the two options. This way you're sure to have valid input.

Binary search of an ArrayList object method to retrieve a string will not identify if strings are identical?

The program in it's entirety sorts an ArrayList of Student objects by integers highest average, last name, and also has the option to perform a search. My program works flawlessly except for my binary search, for which I can absolutely not determine the cause of failure. I have printed all the information as it comes up.
Here is the student class with the method that references the Student's first and last name (String).
public String getFirstName (){
return firstname;
}
public String getLastName(){
return lastname;
}
In addition, here is the code for the binary search. Yes, I know Collections has a method for this exact purpose, but for my class I need to write up the search myself.
private static void searchStudent(ArrayList<Student> a){
Scanner reader = new Scanner(System.in);
System.out.print("Please enter search term: ");
String term = reader.next();
//System.out.println(term + " " + term.length());
System.out.println("---SEARCH RESULTS:---");
for (int i = 0; i < a.size(); i++){
String fName = (a.get(i).getFirstName());
String lName = (a.get(i).getLastName());
//System.out.println(fName + " " + fName.length());
//System.out.println(lName + " " + lName.length());
if (term == fName){
System.out.println(a.get(i));
} else if (term == lName){
System.out.println(a.get(i));
}
}
}
In Java, you need to use .equals() to compare strings. E.g. instead of this:
if (term == fName){
you need to do this:
if (term.equals(fName)){
Otherwise, you are comparing references only.
Btw, this is not a binary search, it's a linear search. You can see one implementation of binary search e.g. here:
http://leepoint.net/notes-java/algorithms/searching/binarysearch.html
though to compare strings you would use .compareTo / .compareToIgnoreCase methods on the String class instead of < / > operators.

Resources