Generating reverse words - java

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]);
}
}

Related

Having trouble calling a method to edit a string from another class in java

I've got a simple java program that is supposed to take the specified characters in a string and print them back out to the user by doing everything within a secondary method in a secondary class while taking input from the user in the first class.
The problem that I'm having is that when I try to invoke the secondary method in my main method, I get an error that says "The method copy(String) is unidentified for my main method.
My code for the main method is:
System.out.println("Copying - Enter a string");
String currentString = input.next();
System.out.println("The current string is: " + currentString);
System.out.println("Enter the starting position");
int startPosition = input.nextInt();
System.out.println("Enter one past the ending position");
int onePastLastPosition = input.nextInt();
System.out.println("The new string is: " + copy(currentString));
And for the copy method is:
public static String copy(String currentString, int startPosition, int onePastLastPosition) {
currentString = currentString.substring(startPosition, onePastLastPosition);
return currentString;
}
So for example, what the code is supposed to do, is if I input a string "abcd", it returns back to me "bc", but the system gets hung up on the last line in the first method.
Any help with understanding where I went wrong, and how to fix it in the future would be much appreciated.
You didn't provide the method the necessary parameters for it to execute properly.
Method copy is accepting three parameters: currentString, startPosition, onePastLastPosition as per the parameters specified:
public static String copy(String currentString, int startPosition, int onePastLastPosition) {
So you should be calling the method like so:
System.out.println("The new string is: " + copy(currentString, startPosition, onePastLastPosition));
Test Run
Copying - Enter a string
spectric
The current string is: spectric
Enter the starting position
1
Enter one past the ending position
2
The new string is: p
Your copy method is in different class.You have to create the second class instance in first class to call the second class function.
First class
System.out.println("Copying - Enter a string");
....
System.out.println("The new string is: " +
SecondClass.copy(currentString));
P/S : Make sure the number of the parameters are correct.
Your copy method is static, so you should call the method with class prefix, and pass additional arguments (startPosition, onePastLastPosition) you declared.
System.out.println("The new string is: " + YourClassName::copy(currentString, startPosition, onePastLastPosition))
Two things.
your parameters to copy are different than the method signature shows.
you should be calling Copy as a static by prefixing the name of the containing class.
The copy method requires 3 parameters, but you have only provided 1. Add the other two:
copy(currentString, startPosition, onePastLastPosition)
Add an import statement for the copy method:
import static SecondClass.copy;
Or qualify the method:
SecondClass.copy(currentString, startPosition, onePastLastPosition)

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!

Why is indexOf() not recognizing spaces?

For this program it asks for the user to input their full name. It then sorts out the first name and last name by separating them at the space the put between the first and last name. However, indexOf() is not recognizing the space and only returns -1. Why is that? Thanks.
Here is the prompt off of PracticeIt:
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
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String fullName = inputScanner.next();
int space = fullName.indexOf(" "); // always return -1 for spaces
int length = fullName.length();
String lastName = fullName.substring(space+1,length+1);
String firstname = fullName.substring(0, space);
System.out.print("Your name in reverse order is " + lastName + ", " + firstname);
}
}
As next will return the next token use nextLine not next to get the whole line
see http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
When you do String fullName = inputScanner.next() you only read till the next whitespace so obviously there is no whitespace in fullName since it is only the first name.
If you want to read the whole line use String fullName = inputScanner.nextLine();

need advice with making a name generator in 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!");
}
}

Algorithm to output the initials of a name

I have just started the java programming and at the moment I am doing the basic things. I came across a problem that I can't solve and didn't found any answers around so I thought you might give me a hand. I want to write a program to prompt the user to enter their full name (first name, second name and surname) and output their initials.
Assuming that the user always types three names and does not include any unnecessary spaces. So the input data will always look like this : Name Middlename Surname
Some of my code that I have done and stuck in there as I get number of the letter that is in the code instead of letter itself.
import java.util.*;
public class Initials
{
public static void main (String[] args)
{
//create Scanner to read in data
Scanner myKeyboard = new Scanner(System.in);
//prompt user for input – use print to leave cursor on line
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String initials1 = name.substring(0, 1);
int initials2 = name.
//output Initials
System.out.println ("Initials Are " + initials1 + initials2 + initials3);
}
}
Users will enter a string like
"first middle last"
so therefore you need to get each word from the string.
Loot at split.
After you get each word of the user-entered data, you need to use a loop to get the first letter of each part of the name.
First, the nextLine Function will return the full name. First, you need to .split() the string name on a space, perhaps. This requires a correctly formatted string from the user, but I wouldn't worry about that yet.
Once you split the string, it returns an array of strings. If the user put them in correectly, you can do a for loop on the array.
StringBuilder builder = new StringBuilder(3);
for(int i = 0; i < splitStringArray.length; i++)
{
builder.append(splitStringArray[i].substring(0,1));
}
System.out.println("Initials Are " + builder.toString());
Use the String split() method. This allows you to split a String using a certain regex (for example, spliting a String by the space character). The returned value is an array holding each of the split values. See the documentation for the method.
Scanner myKeyboard = new Scanner(System.in);
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String[] nameParts = name.split(" ");
char firstInitial = nameParts[0].charAt(0);
char middleInitial = nameParts[1].charAt(0);
char lastInitial = nameParts[2].charAt(0);
System.out.println ("Initials Are " + firstInitial + middleInitial + lastInitial);
Note that the above assumes the user has entered the right number of names. You'll need to do some catching or checking if you need to safeguard against the users doing "weird" things.

Categories