I'm new to programming and logical errors; I've looked for a similar problem but nothing quite matches mine. We have an assignment to make a program where the user enters their first and last name--if the names are the same, it returns "your first and last name are the same" and if the names are different, it returns "your first and last name are different".
My problem is that it keeps returning BOTH answers no matter what names are typed in. If you run it and try your own name in it, you'll see what I mean.
Here's my code (we have to use scanner):
import java.util.Scanner;
public class NameAssignment
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String firstName;
System.out.print("Enter your first name: ");
firstName = stdIn.nextLine();
String lastName;
System.out.print("Enter your last name: ");
lastName = stdIn.nextLine();
if (firstName == lastName);
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are the same.");
if (firstName != lastName);
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
} // end main
} // end class NameAssignment
UPDATE
I tried correcting it with the suggestions below, and here's what it looks like now:
import java.util.Scanner;
public class NameAssignment
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String firstName;
System.out.print("Enter your first name: ");
firstName = stdIn.nextLine();
String lastName;
System.out.print("Enter your last name: ");
lastName = stdIn.nextLine();
if (firstName.equals(lastName))
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are the same.");
else (!firstName.equals(lastName)
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
} // end main
} // end class NameAssignment
I ran it in terminal, and it gave me this:
NameAssignment.java:16: error: ')' expected
else (!firstName.equals(lastName)
^
NameAssignment.java:16: error: not a statement
else (!firstName.equals(lastName)
^
NameAssignment.java:17: error: illegal start of expression
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
^
NameAssignment.java:17: error: ';' expected
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
^
4 errors
To compare 2 Strings in java, you must use if (firstName.equals(lastName)) because in Java == operator checks 2 String objects and .equals() checks String values.
Also, you must remove the semicolon ; after the if statement or else that wont execute your if condition.
Your else clause is wrong. Just replace your else clause with the following else clause:
else
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
That's it. else doesn't need a condition. That's why else (!firstName.equals(lastName)) is wrong.
you were missing the ) which i added and removed the "," + " " because it was un-efficient and it should just be included in the same string which i fixed. Just replace your code with that and it should work
if (firstName.equals(lastName)){
System.out.println("Hello " + firstName + " " + lastName + ", your first name and last name are the same.");
}
else (!firstName.equals(lastName)){
System.out.println("Hello " + firstName + " " + lastName + ", your first name and last name are different.");
}
Related
I'm pretty new to Java and I'm having some trouble figuring out where I'm going wrong with my program. I have it so it's doing a mad libs sort of thing where it reads a document with questions(or categories), then prompts for an answer on loop till it has all the answers. It commits these answers to a text file called "answers" then reads the file and prints a message, along with another file containing the full madlib.
I don't actually get an error upon compiling but after I've input all the answers I get
Exception in thread "main" java.util.NoSuchElementException: no line found
-at java.util.Scanner.nextLine(Scanner.java:1540)
-at reader.main(reader.java:68)
Here's the complete code for reference
import java.util.Scanner; // importing scanner object for usage
import java.io.*;
import java.io.PrintWriter;
public class reader{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("enter the name of a file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
int limit = inputFile.nextInt();
int n;
inputFile.nextLine();
PrintWriter answers = new PrintWriter("answers.txt");
for(n = 0; n < limit; n++)
{
String line = inputFile.nextLine();
System.out.println(line);
String answer = keyboard.nextLine();
answers.println(answer);
}
inputFile.close();
answers.close();
File useanswers = new File("answers.txt");
Scanner inputFile2 = new Scanner(useanswers);
String outputline = inputFile2.nextLine();
String outputline2 = inputFile2.nextLine();
String outputline3 = inputFile2.nextLine();
String outputline4 = inputFile2.nextLine();
String outputline5 = inputFile2.nextLine();
String outputline6 = inputFile2.nextLine();
String outputline7 = inputFile2.nextLine();
String outputline8 = inputFile2.nextLine();
String outputline9 = inputFile2.nextLine();
String outputline10 = inputFile2.nextLine();
String outputline11 = inputFile2.nextLine();
String outputline12 = inputFile2.nextLine();
String outputline13 = inputFile2.nextLine();
String outputline14 = inputFile2.nextLine();
String outputline15 = inputFile2.nextLine();
String outputline16 = inputFile2.nextLine();
String outputline17 = inputFile2.nextLine();
String outputline18 = inputFile2.nextLine();
String outputline19 = inputFile2.nextLine();
PrintWriter result = new PrintWriter("Madlibs_result.txt");
System.out.println("Batman is " + outputline + ". Teenager " + outputline2 +
"was traumatized by " + outputline3 + "his parent's murder and vowed to " + outputline4 +
" their deaths by bringing the " + outputline5 + " to justice. " + outputline6 + " used his " +
outputline7 + "fortune to study criminology, to train his body to " + outputline8 + " perfection, " +
"and to acquire hight tech vehicles and " + outputline9 + " to fight crime in his homw town of " + outputline10 + ". One night " +
outputline11 + "was " + outputline + " by a bat outside his window and decided to dress himself as a \"bat man\" to strike " +
outputline12 + " in the \"" + outputline13 + " and " + outputline14 + "\" hearts of " + outputline15 + ". From that moment forward, " +
outputline16 + " became \"Batman\" in his altered " + outputline17);
result.println("Batman is " + outputline + ". Teenager " + outputline2 +
"was traumatized by " + outputline3 + "his parent's murder and vowed to " + outputline4 +
" their deaths by bringing the " + outputline5 + " to justice. " + outputline6 + " used his " +
outputline7 + "fortune to study criminology, to train his body to " + outputline8 + " perfection, " +
"and to acquire hight tech vehicles and " + outputline9 + " to fight crime in his homw town of " + outputline10 + ". One night " +
outputline11 + "was " + outputline + " by a bat outside his window and decided to dress himself as a \"bat man\" to strike " +
outputline12 + " in the \"" + outputline13 + " and " + outputline14 + "\" hearts of " + outputline15 + ". From that moment forward, " +
outputline16 + " became \"Batman\" in his altered " + outputline17);
result.close();
}
}
Resolved, I had too many String outputline... lines, and I assume when it tried to go to the nonexistent 19th and 20th lines of the text file created, it gave me an error.
public String toString()
{
String name = "Customer name: " + this.name;
String address = "Customer address: " + street + " " + city + " " + state + " " + zip;
String bala = "Balance: " + bal;
return name + "\n" + address + "\n" + bala;
}
I want these variables to be returned in three separate lines, but the actual string "\n" is just being added where I want the new line to be. Any help?
Untested, but may work :
return name + System.lineSeparator() + address + System.lineSeparator() + bala;
This question already has answers here:
Comparing strings by their alphabetical order
(10 answers)
Closed 8 years ago.
How can I print which word comes first (alphabetically) when I prompts the user to write two words? and how to check if a certain character exist in that scanned words?
For ex: if the user wrote "Word" and "Apple" how can I print these two words in alphabetical order. Also, I wrote a program to check if char 'z' appears on either words or not, but I don't know what's wrong about it? Here is my program:
import java.util.*;
public class Pr7{
public static void main(String[] args){
//print two words and read them..
Scanner scan = new Scanner (System.in);
String Word1;
String Word2;
System.out.println();
System.out.print("* Please write one word: ");
Word1 = scan.nextLine();
System.out.print("* Please write one word: ");
Word2 = scan.nextLine();
//Prints which word has more characters in it..
if (Word1.length() > Word2.length())
System.out.println("- " + "(" + Word1 + ")" + " has more characters.");
else if (Word2.length() > Word1.length())
System.out.println("- " + "(" + Word2 + ")" + " has more characters.");
else
System.out.println("- " + "(" + Word1 + ")" + " has equal characters with " + "(" + Word2 + ")");
//Prints which word comes first (alphabetically)..
/*
char ch;
int compare = Word1.compareTO(Word2);
*/
//Prints whether the letter 'z' appears in either word..
if (Word1.indexOf('z') == true)
System.out.print("- Letter 'z' appears in the first word.");
else if (Word2.indexOf('z') == )
System.out.print("- Letter 'z' appears in the second word.");
else
System.out.print("- Letter 'z' doesn't appears in either word.");
System.out.println();
//Prompts the user for a sentence and reads it..
String Str1;
String Str2;
System.out.println();
System.out.print("* Please write a string: ");
Str1 = scan.nextLine();
System.out.print("* Please write a string: ");
Str2 = scan.nextLine();
//Prints how many characters are in the first sentence and the second sentence..
if (Str1.length() > Str2.length()){
System.out.println("- " + "(" + Str1 + ")" + " has more characters.");
System.out.print("- " + "(" + Str1 + ")" + " = " + Str2.length() + " Character(s)" + " && " + "(" + Word2 + ")" + " = " + Word2.length() + " Character(s)");
}
else if (Str2.length() > Str1.length()){
System.out.println("- " + "(" + Str2 + ")" + " has more characters.");
System.out.print("- " + "(" + Str2 + ")" + " = " + Str2.length() + " Character(s)" + " && " + "(" + Word1 + ")" + " = " + Word1.length() + " Character(s)");
}
else{
System.out.println("- " + "(" + Str1 + ")" + " has equal characters with " + "(" + Str2 + ")");
System.out.print("- " + "(" + Str1 + ")" + " = " + Str1.length() + " Character(s)" + " && " + "(" + Word2 + ")" + " = " + Word2.length() + " Character(s)");
}
System.out.println();
}//main
}//Pr7
I know the methods I need to call, but I don't know how to use it.
To sort a list of strings in alphabetical order, you can do the following:
List<String> lst = new ArrayList<>();
lst.add("asd");
lst.add("ffsd");
Collections.sort(lst, new Comparator<String>() {
#Override
public int compare(String foo, String bar) {
return String.CASE_INSENSITIVE_ORDER.compare(foo, bar);
}
});
// will print the first of the sorted strings
System.out.println(lst.get(0));
I'm prompting the user to enter their first and last name but I can't figure out how to show just their first and last initials
import javax.swing.*;
//import java.awt.*;
public class Lab2Program2 {
public static void main (String [] args) {
String firstName;
String lastName;
firstName = JOptionPane.showInputDialog(null, "What is your first name?");
lastName = JOptionPane.showInputDialog(null, "What is your last name?");
JOptionPane.showMessageDialog(null, " Your initials are " +
firstName + " " + lastName);
}
}
If you want to show a message box like you were doing before, this should work:
JOptionPane.showMessageDialog(null,
"Your initials are " + firstName.substring(0, 1) + " " + lastName.substring(0, 1));
You can use chatAt() method.
JOptionPane.showMessageDialog(null,
"Your initials are " + firstName.charAt(0) + " " + lastName.charAt(0));
firstName.charAt(0) returns the char value at the 0 index. That is the first letter of your firstName String.
I dont get why when i compile this code i get the incorrect zip code.
John Smith
486 test St.
Yahoo, MA 898 - 2597JohnSmith
486 test St.
Yahoo, MA 898 2597
Code
public class test
{
public static void main(String[] args) {
String firstName = "John";
String lastName = "Smith";
int streetNumber = 486;
String streetName = "test St.";
String city = "Yahoo";
String state = "MA";
int zip = 01602;
int zipplus4 = 2597;
System.out.print(firstName + " " + lastName + "\n" + streetNumber + " " + streetName + "\n" + city + ", " + state + " " + zip + " - " + zipplus4);
System.out.println(firstName + lastName);
System.out.println(streetNumber + " " + streetName);
System.out.println(city + ", " + state + " " + zip + " - " + zipplus4);
}
}
When you specify a number with a leading zero, it gets treated as an Octal (base-8, as opposed to decimal base-10 or hexadecimal base-16).
01602 octal == 898 decimal
Since Java wasn't desgined with Zip codes in mind, to get the desired effect, drop the leading zero, and format it when you print it:
System.out.println(city + ", " + state + " " + new java.text.NumberFormat("00000").format(zip) + " - " + new java.text.NumberFormat("0000").format(zipplus4));
Make those zip codes String instead of int and it'll be fine.
public class test
{
public static void main(String[] args)
{
String firstName = "John";
String lastName = "Smith";
int streetNumber = 486;
String streetName = "test St.";
String city = "Yahoo";
String state = "MA";
String zip = "01602";
String zipplus4 = "2597";
System.out.print(firstName + " " + lastName + "\n" + streetNumber + " " + streetName + "\n" + city + ", " + state + " " + zip + " - " + zipplus4);
System.out.println(firstName + lastName);
System.out.println(streetNumber + " " + streetName);
System.out.println(city + ", " + state + " " + zip + " - " + zipplus4);
}
}
Outcome:
John Smith
486 test St.
Yahoo, MA 01602 - 2597JohnSmith
486 test St.
Yahoo, MA 01602 - 2597
Process finished with exit code 0
I'd also advise you to encapsulate those into sensible objects. Why deal with String primitives when you can use an Address class? Java's object-oriented; better to think in terms of objects.
01602 - this 0 at the beginning means you are using octal rather than decimal numbers. Remove it and you'll be fine :-).
BTW IntelliJ IDEA even displays warning here.
You should use String type for zip and zipplus4.
If you cannot change the type then you can use the following in your println statement
String.format("%05d", zip)
Take off the leading zero~ or make it a string
A Zipcode shouldn't be stored in a numeric datatype because it isn't really something you wnat to do math on, instead store it as a String and it'll work fine.