The script below will compare two string to see if they are equal. In this case one string is declared and the other string is input from the scanner. I understand why these two string are not equal when compared (say aName = test and anotherName= test) because they will contain different references addresses.
This next paragraph will lead into my question. The nextLine() method returns a string. I know normally if two strings contain the same text they would have the same address in the string pool. So my question is, why isn't the string returned from the nextLine() method to the anotherName variable assigned to the string pool and given the same address as aName, since they have the same text? *
import java.util.Scanner;
public class TryToCompareString
{
public static void main(String[] args)
{
String aName = "test";
String anotherName;
Scanner input = new Scanner(System.in);
System.out.println("Enter your name");
anotherName = input.nextLine();
if (aName == anotherName)
{
System.out.println(aName + " equals " + anotherName);
}
else
{
System.out.println(aName + " does not equal " + anotherName);
}
}
}
Related
I am currently learning programming in Java and was practicing the String contains(), which is used to check whether a particular string within a string exists or not. But in the given code, the contains() returns false even if the string is present.
import java.util.*;
class StringPractice1{
public static void main(String arg[]){
System.out.println("Enter a string:- ");
Scanner sc1 = new Scanner(System.in);
String s1 = sc1.next();
System.out.println("Enter the string you want to find:- ");
Scanner sc2 = new Scanner(System.in);
String s2 = sc2.next();
if(s1.contains(s2)){
System.out.println("It contains the string '"+s2+"'.");
}
else{
System.out.println("No such string exists.");
}
}}
Output screen
String s1 = sc1.next();
will only take one word i.e. I in your case because of the occurrence of a space.
However if you use sc1.nextLine();, the whole sentence will be taken, i.e. "I am a boy". Thereby solving your problem.
I'm learning Java on netbeans so I looked for some exercises.
I was trying to complete this exercise : write a java program that prompt user to enter a word and check if this word starts with letter 'A'.
So I wrote this code :
package testone;
import java.util.Scanner;
public class TestOne {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String strA = "A";
Scanner s = new Scanner(System.in);
System.out.println("Please enter a word : ");
String userWord = s.next();
char firstLetter = userWord.charAt(0);
if (strA.equals(firstLetter)) {
System.out.println("Your word starts with letter A ");
}else {
System.out.println("Your word doesn't start with letter A ");
}
}
}
but It didn't work probably, any ideas ?
You are comparing a String with a char here: if (strA.equals(firstLetter)) {. That's like checking if an apple is equal to a pear; it will always be false.
Instead, simply check if the input starts with A:
if (userWord.startsWith("A")) {
See Java - String - startsWith for more information.
According to the doc:
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if
and only if the argument is not null and is a String object that
represents the same sequence of characters as this object.
You are call ing this method with a parameter of type char, which will be boxed into a Character instance, which does not extend String. The result will always be false.
Use userWord.startsWith("A") instead, or userWord.charAt(0) == 'A'...
Can you try with that userWord.startsWith("A")
You cant directly compare char and String. Besides what others have given as solution, you can use the String.valueOf(...) function and then you'll be able to compare String and char.
package testone;
import java.util.Scanner;
public class TestOne {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String strA = "A";
Scanner s = new Scanner(System.in);
System.out.println("Please enter a word : ");
String userWord = s.next();
char firstLetter = userWord.charAt(0);
if (strA.equals(String.valueOf(firstLetter))) { //Try this
System.out.println("Your word starts with letter A ");
}else {
System.out.println("Your word doesn't start with letter A ");
}
}
}
I think you can try the method yourstring.indexOf('A'), it returns an int, if its 0 so you found "A" at the first position , otherwise no .
Syntax
if(yourstring.indexOf('A') == 0 ){
//do something .....
}
This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
How to upper case every first letter of word in a string? [duplicate]
(16 answers)
Closed 8 years ago.
Hey guys so im new to java and im trying to write a program that declares two strings
First && Last name ( both under case )
And i need to use the .uppercase to convert the first letter in both the first name and last name from lower case to uppercase.
Example convert jon to Jon
This is what i have so far
I really dont understand how i make the first letter uppercase.
/////
public class firstProgram {
public static void main(String args[])
{
//NAME GOES HERE. DECLARED 2 STRINGS
String first = "firstname";
String last = "lastname";
//PRINT OUT STRINGS
System.out.println(first);
System.out.println(last);
}
}
You can do something like -
String first = "firstname";
String last = "lastname";
first = String.valueOf(first.charAt(0)).toUpperCase() + first.substring(1);
last = String.valueOf(last.charAt(0)).toUpperCase() + last.substring(1);
//PRINT OUT STRINGS
System.out.println(first);
System.out.println(last);
You can check documentation for toUpperCase().
If you only want to capitalize the first letter of a string named first and leave the rest alone:
first = first.substring(0, 1).toUpperCase() + first.substring(1);
Now first will have what you want.
Do like this for last
You can do this by employing the String class subString methods.
String input = "first name";
String out = input.substring(0, 1).toUpperCase() + input.substring(1);
firstName = Character.toUpperCase(firstName.charAt(0)) + firstName.substring(1);
lastName = Character.toUpperCase(lastName.charAt(0)) + lastName.substring(1);
or in class
class FirstProgram {
public static void main(String[] args) {
String firstName = "arun";
String lastName = "kumar";
firstName = Character.toUpperCase(firstName.charAt(0)) + firstName.substring(1);
lastName = Character.toUpperCase(lastName.charAt(0)) + lastName.substring(1);
System.out.println(firstName+ " "+lastName);
}
}
I wanted to take a String using Scanner.next() and see if it contains a number or not. I used regex to check if a string contains anything but a number. The regex works correctly if the string is hard coded, but not when taken from keyboard. I expected input of 5 to be detected as a number, but it is not. Please tell me why. My code:
import java.util.Scanner;
public class Error {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int num = 0;
String input = "";
boolean isStringNumber = true;
System.out.println("\nPlease enter a number only...");
input = inp.nextLine();
isStringNumber = input.contains("[^0-9]+");
if (isStringNumber == false) {
System.out.println("\nYou entered a non number " + input);
}
}
}
contains uses a String literal as its argument. Use matches instead
isStringNumber = input.matches("[0-9]+");
or simply
isStringNumber = input.matches("\\d+");
BTW: Scanner has a nextInt method for accepting integer values
instead isStringNumber = input.contains("[^0-9]+");
try isStringNumber = input.matches("[0-9]+");
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am making a simple matchmaker as a learning project in JAVA. My program so far just asks a few questions, but I wanted to do gender specific questions, so I asked for their sex (m or f) and then attempted to add a message that only showed if sex was m. The dialog should say "well done, you are male!". Else it restarts method. Every time, no matter what I type it restarts the program.
Here is my code:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args){
setVars();
}
public static void setVars(){
String name = JOptionPane.showInputDialog(null, "What is your name?");
String sAge = JOptionPane.showInputDialog(null, "What is your age?");
String sex = JOptionPane.showInputDialog(null, "What is your sex?\n(Enter m or f)");
if (sex == "m"){
JOptionPane.showMessageDialog(null, "Well done, you are male.\nKeep Going!");
}
int age = Integer.parseInt(sAge);
String chars = JOptionPane.showInputDialog(null, "Name three charectaristics");
}
}
try
if ( "m".equalIgnoreCase(sex))
you should use equals for comparing string value and == for checking their references
In Java, you dont' compare strings with ==, you have to compare them with the equals() method on String. String has two variants of this method: equals() which is case sensitive, and equalsIgnoreCase(), which is case insensitive. In the examples below, you can use either one.
Try this:
if(sex.equalsIgnoreCase("m") {
...
}
Or to guard against nulls...
if("m".equalsIgnoreCase(sex)) {
...
}
Your code should be:
if ("m".equals(sex)) {
//
}
== compares objects' addresses / references
.equals compares objects' values
because String is an object not a data type like int when it comes to compare two Strings it is done by .equals() method:
package example;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args){
setVars();
}
public static void setVars(){
String name = JOptionPane.showInputDialog(null, "What is your name?");
String sAge = JOptionPane.showInputDialog(null, "What is your age?");
String sex = JOptionPane.showInputDialog(null, "What is your sex?\n(Enter m or f)");
if (sex.equals("m")){
JOptionPane.showMessageDialog(null, "Well done, you are male.\nKeep Going!");
}
int age = Integer.parseInt(sAge);
String chars = JOptionPane.showInputDialog(null, "Name three charectaristics");
}
}