I've been looking for an answer to this for a while, but for some reason, none of them seem to work.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.next().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];
System.out.println("Your info: " + firstName + " " + lastName);
There is my code. I'm basically trying to obtain the personal info, which would be the first and last name. I want to split the first and last name into 2 different strings, but whenever I try to print this, I get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 > out of bounds for length 1
at Fines.main(Fines.java:11)
I'm confused because I even started the array with 0 like I was supposed to.. I just don't understand what is going incorrectly.
Please give me a hand - thanks in advance!
What you want is scanner.nextLine() to read from standard input up until end of line. Then split would work as you expected.
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.nextLine().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];
System.out.println("Your info: " + firstName + " " + lastName);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 1 > out of bounds for length 1 at Fines.main(Fines.java:11)
As the size of the personalInfo is 1 not 2.
use nextLine() instead of next() because next() will only return the input that comes before a space.
String[] personalInfo = scanner.next().split(", "); should be
String[] personalInfo = scanner.nextLine().split(", ");
You might want to read this What's the difference between next() and nextLine() methods from Scanner class?
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Please enter full name (last, first)");
String firstName = scan.next();
String lastName = scan.next();
System.out.println("Your info: " + firstName + ' ' + lastName);
}
scanner.next() read until next delimiter (space by default), so it ready only the firstName. Just replace it with scanner.nextLine() or use scanner.next() two times.
Related
I am trying to create a code that accepts a user's full name and returns first and last names and initials. Since a user's name length varies, I did not want to use hard coding, so I extract names and initials programmatically.
However when I run it and enter a name, I get the following error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
I looked into my code carefully and cannot see where exactly I miscalculated on the index range. I tried to find similar questions here, but though I did see similar problems, they have to do with C++ or Perl, not Java.
package nameSubstring;
import java.util.Scanner;
public class NameSubstring {
public static void main(String[] args) {
/*
* This is a program that accepts a user’s full name as a string (e.g. Margaret Thatcher) and displays to the user his/her first name, last name and initials in the following format:
Your first name is Margaret and your last name is Thatcher and your initials are MT.
*/
System.out.println("This program will take your full name and display your first name, last name, and initials.");
Scanner scanner = new Scanner(System.in);
String firstName, lastName, firstNameInitial, lastNameInitial;
System.out.println("Please enter your full name, e.g. Jane Smith:");
String fullName = scanner.next();
int nameSpace = fullName.indexOf(' ');
firstName = fullName.substring(0, nameSpace);
lastName = fullName.substring(nameSpace)+1;
firstNameInitial = firstName.substring(0, 1);
lastNameInitial = lastName.substring(0, 1);
System.out.println("Your first name is " + firstName + ", " + "your last name is " + lastName + ", " + "and your initials are " + firstNameInitial + lastNameInitial + ".");
}
}
Instead of next() use nextLine():
String fullName = scanner.nextLine();
and correct the error with the +1 which must be inside the parenthesis:
lastName = fullName.substring(nameSpace+1);
public static void main(String[] args) {
// Create a usable instance of an input device
Scanner sc = new Scanner(System.in);
// Prompt user for input
System.out.println("Please enter you first name:");
// Capture first word and assign it to A Variable
String firstName;
firstName = sc.next();
//Construct the greeting
System.out.println("Hello, " + sc.next() + "!");
I am able to output the name on the screen but I have to type it in twice. I believe it is due to the sc.next statement but I am not for certain.
Yes, it is due to the sc.next() because you are doing it twice.
Change your last line to
System.out.println("Hello, " + firstName + "!");
use
System.out.println("Hello, " + firstName + "!");
after first sc.next() it's empty (also look nextLine)
The problem is that you call sc.next() twice:
firstName = sc.next(); // 1st time
//Construct the greeting
System.out.println("Hello, " + sc.next() + "!"); //2nd time
Please use the assigned variable firstnameinstead:
firstName = sc.next();
//Construct the greeting
System.out.println("Hello, " + firstName + "!");
This should fix you issue.
System asks you to enter 'first name' for 2 times because you calling sc.next() for two times.
To prevent this you can do it this way:
...
//Construct the greeting
System.out.println("Hello, " + firstName + "!");
...
or even this way, if you will not use String firstName in the future:
...
System.out.println("Please enter you first name:");
//Construct the greeting
System.out.println("Hello, " + sc.next() + "!");
...
I will also prefer to use nextLint() instead of next() because it automatically moves the scanner down after returning the current line.
If you interested you can take a look here:
https://stackoverflow.com/a/22458766/8913124
This code is supposed to print the user's name when they enter it and limit it's length to 20 characters, but it only works when the user's name is longer than 20 chars. I get en error when it's below 20. Any ideas on how to fix this?
Thank you.
String name;
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
String cutName = name.substring(0, 20);
if (name.length()>20) {
name = cutName;
System.out.print("Hello " +name+"!");
}
Just take the lower index between 20 and the String 's length .
name.substring(0, Math.min(20,name.length()));
If you place your String cutName inside the if, the error should disappear. You cannot take a substring from a string that is longer than the String itself.
if (name.length()>20) {
String cutName = name.substring(0, 20);
name = cutName;
}
System.out.print("Hello " +name+"!");
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
if(name.length()>20)
name = name.substring(0,20);
The assignment:
Write a program (Greetings) that prompts the user to enter the first name, the last name, and year of birth, then it returns a greetings message
in proper format (see the example below).
Create a method(s) that accept the scanner and a prompt as parameters and return the user input. A separate method should accept the user input results as parameters, format and print the results. No print statement or scanner input should happen inside main(). Here is an example dialogue with the user:
Please enter your first name:
tom
Please enter your last name:
cruise
Please enter your year of birth:
1962
Greetings, T. Cruise! You are about 53 years old.
I finished the code, but right now it is giving me a compilation error. How do i fix it?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
Scanner newscanner = new Scanner(System.in);
String ask = ("Please enter your first name: ");
String ask2 = ("Please enter your last name: ");
String ask3 = ("Please enter your year of birth: ");
public static String getString(Scanner newscanner, String ask, String ask2, String ask3){
System.out.println(ask);
String first = newscanner.next();
String firstletter = first.substring(0,1).toUpperCase() ;
return firstletter;
System.out.println(ask2);
String second = newscanner.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
String lastname = y.substring(0,1).toUpperCase();
return lastname;
System.out.println(ask3);
int third = newscanner.nextInt();
int age = (2015 - third);
return age
System.out.println("Greetings, "+ firstletter + ". " + lastname+"!" +" You are about " + age + " years old");
}
}
}
Hard to read, but I think you actually have the getString() method inside your main() method - it needs to be after it, and only be called from inside main(), not defined there.
I want to make a simple code, that prompts you to enter names, separated by comma or just a space, and when you click enter, to take every one word you entered, and put a #gmail.com at the end of it, how can I do it?
That's what I have for now
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
String names;
System.out.println("Enter names: ");
names = input.next();
System.out.println(names + mail);
This should be everything you asked for, if you put a list of names separated by commas it will loop through them, otherwise it will just print a single name.
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
System.out.println("Enter names: ");
String names = input.next();
if(names.contains(",")) {
for(String name : names.split(",")) {
System.out.println(name + mail);
}
} else {
System.out.println(names + mail);
}
Hope that helps.
Not knowing what language this is, here's the pseudo-code:
names = input.next();
namesArray = names.split(" ") -- replace with your preferred delimiter
foreach name in namesArray
print name + mail