need advice with making a name generator in java - java

Hi, I'm trying to make a Star Wars name Generator and I am stuck. I am suppose to make the program follow these guidelines:
I should make a method called promptstring.
The user's Star Wars name is composed of a first and last name:
For the first name, use the first 3 characters of the user's real first name, concatenated with the first 2 characters of the user's real last name.
For the last name, use the first 2 characters of the user's mother's maiden name, concatenated with the first 3 characters of the user's city of birth.
For the user's Star Wars planet, use the last 2 characters of the user's last name, concatenated with the user's car.
Example:
Enter your first name: Thom
Enter your last name: Yorke
Enter your mother's maiden name: Selway
Enter the city where you were born: Wellingborough
Enter the first car your drove: Audi
You are THOYO SEWEL of KEAUDI
Right now I'm just having compiler errors which are
8 errors found: File: J:\CS Projects\NameGenerator.java [line: 15]
Error: input cannot be resolved
File: J:\CS Projects\NameGenerator.java [line: 18] Error: The method
nextLine() in the type java.util.Scanner is not applicable for the
arguments (int, int)
File: J:\CS Projects\NameGenerator.java [line: 19] Error: last1
cannot be resolved to a variable
File: J:\CS Projects\NameGenerator.java [line: 19] Error: end cannot
be resolved to a variable
File: J:\CS Projects\NameGenerator.java [line: 22] Error: The method
nextLine() in the type java.util.Scanner is not applicable for the
arguments (int, int)
File: J:\CS Projects\NameGenerator.java [line: 25] Error: The method
nextLine() in the type java.util.Scanner is not applicable for the
arguments (int, int)
File: J:\CS Projects\NameGenerator.java [line: 31] Error:
Starwarsname cannot be resolved to a variable
File: J:\CS Projects\NameGenerator.java [line: 34] Error:
Starwarsname cannot be resolved to a variable
I have reworked this program over and over again and I am stuck. Can anyone point me in the right direction or tell me what I am doing wrong. Thank you in advance.
import java.util.*;
public class NameGenerator {
static Scanner wars = new Scanner(System.in);
public static void main(String[] args) {
//Prompt for User's Name
String first,last,mother,city,car;
System.out.printf("Please state your First Name");
first= wars.Line(0,2);
System.out.printf("Please state your Last name");
last=wars.nextLine(0,1);
last1=wars.nextLine(-1,end);
System.out.printf("Please state your mothers maiden name");
mother=wars.nextLine(0,1);
System.out.printf("Please state the city you were born in ");
city=wars.nextLine(0,2);
System.out.printf("Please state your first car");
car=wars.nextLine();
Starwarsname=first+last + mother + city + "of" + last + car ;
System.out.println("In a galaxy far, far away you are known as " + Starwarsname + " MAY THE FORCE be with you!");
}
}

You're using the scanner incorrectly. It should be like this:
first = wars.nextLine();
If you want only the first two characters of first, then:
first = first.substring(0,2);
Same with the rest of your strings. You can't get a substring from using the scanner class. Scanner class only scans your input. Use the String.substring method (show above) to get the substring.
Edit: Also, you're trying to use a few variables that are undeclared. Make sure you declare the variable "Starwarsname" as String first before assigning it to something.

The change the statements having
wars.nextLine(0,1);
to
wars.nextLine();
Later use
str.substring(beginIndex, endIndex)
method of String to get whatever part of the entered string you want,concatenate and print them.

Error: end cannot be resolved to a variable
Indicates that you never declared the variable end. Make sure to have a line that is something like String end; before you use every variable.
Error: The method nextLine() in the type java.util.Scanner is not applicable for the arguments (int, int)
Indicates that nextLine() cannot take any parameters (see the javadocs). If you want to get a substring from the input, do something like wars.nextLine().substring(0,2). Additionally, both numbers must be positive (the -1 in your code will cause an ArrayOutOfBoundsException).

Use the below code and test it...
i did the testing also.
points of concern:
You did not declare some variables
you did not check method names in the Scanner API. please check java
doc for that.
please check and tell
import java.util.*;
public class NameGenerator {
static Scanner wars = new Scanner(System.in);
public static void main(String[] args) {
//Prompt for User's Name
String first, last, mother, city, car,Starwarsname,last1;
int end=0;
System.out.printf("Please state your First Name");
first = wars.nextLine();//wars.Line(0, 2);
System.out.printf("Please state your Last name");
last = wars.nextLine();
// last1 = wars.nextLine();
System.out.printf("Please state your mothers maiden name");
mother = wars.nextLine();
System.out.printf("Please state the city you were born in ");
city = wars.nextLine();
System.out.printf("Please state your first car");
car = wars.nextLine();
Starwarsname = first +" "+ last +" "+ mother +" "+ city + " of " + last +" "+ car;
System.out.println("In a galaxy far, far away you are known as " + Starwarsname +
" MAY THE FORCE be with you!");
}
}

Related

Java cannot find enum variable

I am having issues calling the Severity.LOW variable from the Enum I created. I have tried importing it, wrapping it in a class, and importing the wrapper class. I cannot figure out what im doing wrong.
Here is the Main.java
package allergyProblem;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Name:");
String firstName = sc.nextLine();
System.out.println("Enter Last Name:");
String lastName = sc.nextLine();
System.out.println("Enter Phone Number:");
String phoneNumber = sc.nextLine();
System.out.println("Enter E-Mail Address:");
String emailAddress = sc.nextLine();
System.out.println("Enter Street Name:");
String streetName = sc.nextLine();
System.out.println("Enter City:");
String city = sc.nextLine();
System.out.println("Enter State:");
String state = sc.nextLine();
System.out.println("Enter Zipcode:");
int zipCode = sc.nextInt();
Address adr = new Address(streetName, city, state, zipCode);
Allergy allergy = new Allergy("coughing", "Arzoo", Severity.LOW, "Regular cough");
List<Allergy> allergies = new ArrayList<Allergy>();
allergies.add(allergy);
Patient patient = new Patient(firstName, lastName, phoneNumber, emailAddress, adr, allergies);
System.out.println(patient);
}
}
Here is the Enum im trying to access
package allergyProblem;
import java.util.*;
public enum Severity {HIGH, MEDIUM, LOW}
This is the error i get when trying to compile Main.java.
Severity.java which is the Enum, compiled properly without any errors.
Main.java:43: error: cannot find symbol
Allergy allergy = new Allergy("coughing", "Arzoo", Severity.LOW, "Regular cough");
^
symbol: variable LOW
location: class Severity
1 error
The error is telling you that Severity as a type is found (ignore that it says 'class Severity', it does that even if javac knows it is an enum, unfortunately), but that it does not contain the variable LOW.
There's only one explanation for that:
The Severity that javac is using here is NOT the result of compiling public enum Severity {HIGH, MEDIUM, LOW}. Check if there are other classes named Severity in your classpath in that package, or in the package that contains your Main.java file. Then, check that you properly (re)compiled Severity.java, because a stale class file can also mess with it. Then check that you don't have some old stale build result on the class path.
NB: Note that your code won't work even after fixing this, you're abusing Scanner. The right way to use scanner is to either only call .nextLine, or to never call it, with a strong preference for never calling it. If you want to read lines, after making the scanner, immediately run scanner.useDelimiter("\r?\n"); in order to tell the scanner that you want one token per enter, not one token per whitespace (this is a good idea in any case when taking command line input, the fact that scanner defaults to whitespace as delimiter is a dumb error that cannot be fixed due to backwards compatibility concerns. It's a good habit to get into: Making a scanner? Immediately set the delimiter). Then, you can just call next() instead of nextLine() for a lines worth of data, and then it will work - your take will not work due to well known issues mixing nextLine and nextAnythingElse.

Substring of Scanner Input

How do I get a substring from scanner input?
(Before you comment saying "duplicate" or "look it up", I have. I haven't gotten any answers that apply or are within the range of what I'm currently allowed to utilize in my programming course.)
I'm trying to get the program to accept user input using the scanner class, and then print out a part of the input, but only the tail end. In this example I have the scanner asking for a debit card number and want the input to be printed back as "**** **** **** nnnn" (nnnn being numbers from the scanner input). Here's what I have:
import java.util.Scanner;
public class CyberlifePurchase
{
public static void main(String[ ] args)
{
Scanner payment = new Scanner(System.in);
System.out.println("Please enter your debit card number: ");
String cardNumber = in.next();
System.out.println();
String concealedCardNumber = cardNumber.substring(15);
System.out.println("Card Number: " + "**** **** **** " + concealedCardNumber);
When I compile everything there are no compile errors, but when I run the program this is what I get after entering a card number (in nnnn nnnn nnnn nnnn format):
java.lang.StringIndexOutOfBoundsException: String index out of range: -11
You should use in.nextLine() rather than in.next()
next method in the Scanner class uses space as a token and only returns the data before the space, hence you can use nextLine method
As already mentioned, use scanner.nextLine() instead of scanner.next().
If you want the last part of the string, it is safer to use something like:
originalString.substring(originalString.length()-4);
Replace 4 with the actual character count you want to output. It would be also wise to check that the length of the original string is more that the amount you substract (4 in the example above).
Besides fixing your code, if you want to impress your teacher you should add some error checking as well. This can double as a safeguard against StringIndexOutOfBoundsException. For example, replace the last two lines of codes with this:
if (cardNumber.length() < 19) {
System.out.println("c'mon... its like this!! \"nnnn nnnn nnnn nnnn\"");
} else {
String concealedCardNumber = cardNumber.substring(15);
System.out.println("Card Number: " + "**** **** **** " + concealedCardNumber);
}

How do I use an int and printf

I need to use the following in my program and not sure how to get it to work.
Ask the user to enter their name(String variable) and age (int
variable).
Also I need to display their name, age and a welcome message using a printf statement.
This is what I have so far. Can anyone help me? Please
package myfirstprogram;
import java.util.Scanner;
public class MyFirstProgram {
public static void main(String[] args) {
String name;
int age;
Scanner sc = new Scanner(System.in);
System.out.printf("Please Type Your Name then press the Enter key.");
System.out.printf("Please Type Your Age then press the Enter Key.");
name = sc.next();
age = sc.next();
System.out.printf("Hello. My name is " + name + ", I am pleased to meet you.");
System.out.printf("Your Age is " + age);
System.out.printf("Hello and Welcome, " + name);
}
}
Did you even try to compile your code to see what errors are in it?
Are you using a GUI program (like Eclipse, et al.) to compile your code? Or javac on the command-line? Either way your code compiles with the error:
javac myfirstprogram/MyFirstProgram.java
myfirstprogram/MyFirstProgram.java:17: incompatible types
found : java.lang.String
required: int
age = sc.next();
^
1 error
This is saying that, as shmosel and others rightly pointed out in the comments, Scanner.next() returns a string, which is fine when you are getting the user's name input that is of type String, but this won't work for age input as you have defined age as an int.
So to "get it to work" you need to do as the compiler instructs which is to change the line 17 to:
age = sc.nextInt();
Then your program should "work" as you expect.
Hope this helps!
I would try something like this:
public static void main(String[] args) {
String name;
int age;
Scanner sc = new Scanner(System.in);
System.out.printf("Please enter your name");
name = sc.next();
System.out.printf("Please enter your age");
age = sc.nextInt();
System.out.printf("Hello " + name + "\nYour age is: " + age);
sc.close();
}
The reason this code works is because, like others have said, the age variable is an integer, not a String (what sc.next() returns). Also, it is much easier to separate both questions because that way the program will easily distinguish what is being inputted as the age and the name.
If you want it to be a bit more fail proof, you can throw an exception that will check to see that the user did not input a String as an integer.
A good place to see how libraries work in Java is both Stackoverflow and the Java API website (depending on your version of Java there are different sites)
Java™ Platform, Standard Edition 7
API Specification
Java™ Platform, Standard Edition 8
API Specification
If you need help with anything else in Java and the above is complicated, try these websites:
Tutorials Point - Java
Best of luck!

Generating reverse words

i am a beginner in java and i am doing practiceit questions off the internet.I tried attempting the question but i dont understand the error.
Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as necessary. Here is a sample dialogue with the user:
Please enter your full name: Sammy Jankis
Your name in reverse order is Jankis, Sammy
public static void processName(Scanner console) {
System.out.print("Please enter your full name: ");
String full=console.nextLine();
String first=full.substring(0," ");
String second=full.substring(" ");
System.out.print("Your name in reverse order is: "+ second + "," + first);
}
Maybe i will go about explaining my code.So i try to break the two words apart.So i use substring to find the both words and then i hardcode to reverse them.I think the logic is right but i still get these errors.
Line 6
You are referring to an identifer (a name of a variable, class, method, etc.) that is not recognized. Perhaps you misspelled it, mis-capitalized it, or forgot to declare it?
cannot find symbol
symbol : method substring(int,java.lang.String)
location: class java.lang.String
String first=full.substring(0," ");
^
Line 7
You are referring to an identifer (a name of a variable, class, method, etc.) that is not recognized. Perhaps you misspelled it, mis-capitalized it, or forgot to declare it?
cannot find symbol
symbol : method substring(java.lang.String)
location: class java.lang.String
String second=full.substring(" ");
^
2 errors
33 warnings
public static void processName(Scanner console) {
System.out.print("Please enter your full name: ");
String[] name = console.nextLine().split("\\s");
System.out.print("Your name in reverse order is: "+ name[1] + "," + name[0]);
}
Of course it only works if the name has 2 words. For longer names you should write a method which would reverse an array
Take a look at the documentation for the substring() method. It does not take a string as its second parameter.
String first=full.substring(0," ");
String second=full.substring(" ");
What you may want instead is the indexOf() method. First find the index of the space character. Then find the substring up to that point.
int n = full.indexOf(" ");
String first=full.substring(o, n); //gives the first name
As per Java API, substring() accepts either one int argument like substring(int beginIndex) and two int arguments like substring(int startIndex, int endIndex) but you are calling with String arguments. So you're getting those errors. More info can be found here
String API.
go to here http://docs.oracle.com/javase/6/docs/api/java/lang/String.html and read to understand.
public class ex3_11_padString {
public static void main(String[] args) {
System.out.print("Please enter your full name: ");
String f_l_Name = console.nextLine();
String sss[] = f_l_Name.split(" ", 2);
System.out.print("Your name in reverse order is " + sss[1] + ", " + sss[0]);
}
}

Trouble Using Input and Arraylists

I am having trouble. I am trying to allow a user to input a parameter for a method in another file. However it is giving me two errors. Can anyone help me please
public int countItem(Item purchase)
{
int quantity = 0;
if(cart.indexOf(purchase) == -1)
quantity = 0;
else
quantity = purchase.getQuantity() ;
return quantity;
}
This is from my second file.
System.out.println ("What item do you want to find?");
purchase = input.nextline(); //ERROR ERROR
System.out.println("You have " + basket.countItem() + purchase + "soup in your cart."); // ERROR
These are the errors am I getting.
--------------------Configuration: <Default>--------------------
F:\School\CS I AP\Chapter 7\Shopping Cart Lab\Shop.java:71: error: cannot find symbol
purchase = input.nextline();
^
symbol: variable purchase
location: class Shop
F:\School\CS I AP\Chapter 7\Shopping Cart Lab\Shop.java:71: error: cannot find symbol
purchase = input.nextline();
I also realized I got a third error.
error: method countItem in class ShoppingCart cannot be applied to given types;
It appears that the Java compiler cannot find the variable purchase. There are a few scenarios for this:
The Item class is in another folder and has not been imported. (very common error)
The variable purchase has not been declared.
Typo errors in the variable name, variable declaration, or method name.
From your error, it seems that you have not declared the variable purchase. It should be:String purchase = input.nextLine();
Also, you made a typo. It should be nextLine() instead of nextline().
Bear in mind that you need to convert your purchase object from a String into an Item object, since your countItem() method only accepts an Item object. The nextLine() method from the Scanner class only returns a String object, you cannot force it directly into a Item object or you will get another compiler error. For example, if you had a constructor for a new Item object that takes in a String:
Item item = new Item(purchase);
int count = itemCount(item);
As for your third error, you had declared your countItem() method to take in one parameter of type Item, but in your code you are calling it without any parameters, hence the compiler complains about it.
The error that you are getting is because the program doesn't know what the variable purchase is. Basically, there is not an object by the name of purchase in scope at the time that it is being called.
If you could post some more of the code to show the full scope of your Main method, that would help us show you where to define purchase so that it is in scope when it is called.
the last error is fixed with (), ie:
System.out.println("You have " + (basket.countItem() + purchase) + "soup in your cart.");
or like this:
int temp = basket.countItem() + purchase;
System.out.println("You have " + temp + "soup in your cart.");
That is of course, assuming that purchase is an int. More context is needed to be sure
you should declare purchase.
String purchase

Categories