I have a user input their name as a string and then the name is printed out onto the screen. How can i limit what is printed to only 12 characters so that a user cannot type an insanely long name? Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter your player name: ");
String name= input.next();
System.out.print("\n" + name + " has started the game\n");
Something like:
String name = input.next();
name = name.length() > 12 ? name.substring(0, 11) : name;
and accept some of your previous answers.
{
public static void main (String[]args){
String s = new String();
String n = new String();
s = "ya ali madad";
if (s.length() > 10) {
n = s.substring(10, 12);
}
System.out.println("String s:" + s);
System.out.println("String n:" + n);}}
Related
System.out.println("Please enter your first and last names separated by a space: ");
try (Scanner scan = new Scanner(System.in)) {
String s1 = scan.next();
int space = s1.indexOf(" ");
String First_Name = s1.substring(0,space);
String init1 = First_Name.substring(0,1);
String Last_Name = s1.substring(space+1,s1.length());
String init2 = Last_Name.substring(0,1);
int First_N = First_Name.length();
int Last_N = Last_Name.length();
System.out.println("You entered the name "+s1+".");
System.out.println("Your first name "+First_Name+": has "+First_N+" characters.");
System.out.println("Your last name "+Last_Name+": has "+Last_N+" characters.");
System.out.println("Your initials are "+init1+init2+".");
You should use
String s1 = scan.nextLine();
instead of
String s1 = scan.next();
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I just started Java and wanted to tinker with the syntax. Whenever I input "F" into gender and age being greater than or equal to 20 I should be prompted to input if the user is married or not, for some reason the scanner is skipping over it. Everything else works fine.
Output I'm getting:
Whats is your gender (M or F): F
First name: Kim
Last name: Kardashian
Age: 32
Are you married, Kim (Y or N)?
Then I shall call you Ms. Kardashian.
Code:
import java.util.Scanner;
public class GenderGame
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int age = 0;
String Gender = null, fName = null, lName = null, M = null, type = null;
System.out.print("Whats is your gender (M or F): ");
Gender = sc.nextLine();
Gender = Gender.toUpperCase();
System.out.print("First name: ");
fName = sc.nextLine();
System.out.print("Last name: ");
lName = sc.nextLine();
System.out.print("Age: ");
age = sc.nextInt();
if(Gender.equals("F") && age >= 20)
{
System.out.print("\nAre you married, " + fName + " (Y or N)? ");
M = sc.nextLine();
M = M.toUpperCase();
if(M.equals("Y"))
{
type = "Mrs. ";
type = type.concat(lName);
}
else
{
type = "Ms. ";
type = type.concat(lName);
}
}
else if(Gender.equals("F") && age < 20)
{
type = fName.concat(" " + lName);
}
else if(Gender.equals("M") && age >= 20)
{
type = "Mr. ";
type = type.concat(lName);
}
else if(Gender.equals("M") && age < 20)
{
type = fName.concat(" " + lName);
}
else
{
System.out.println("There was incorrect input. EXITING PROGRAM");
System.exit(1);
}
System.out.println("\nThen I shall call you " +type+ ".");
}
}
The nextInt() method of Scanner leaves the new line character out, that is, it does not consume it. This newline character is is consumed by your nextLine() method, which is why you do not see it wait for your input.
To avoid this, call sc.nextLine() after age = sc.nextInt();, then leave the rest of code unchanged.
...
System.out.print("Age: ");
age = sc.nextInt();
sc.nextLine(); //added
if(Gender.equals("F") && age >= 20)
{
System.out.print("\nAre you married, " + fName + " (Y or N)? ");
M = sc.nextLine();
M = M.toUpperCase();
if(M.equals("Y"))
{
type = "Mrs. ";
type = type.concat(lName);
}
...
public class Registration {
public static void main(String[] args) {
final String MY_DELIMITER = "','";
boolean tryAgain = true;
String fName = "";
String A = fName.substring(0,2);
String lName = "";
int lNameLength = lName.length();
String B = lName.substring(lNameLength-4,lNameLength);
String address = "";
String zip = "";
String C = zip.substring(0,5);
String age = "";
String D = age.substring(0,1);
String gender = "";
String race = "";
String regList = "";
Scanner myScanner = new Scanner(System.in);
boolean showList = false;
// Get input from the user until they type "q"
// For each input check for "q"
// if not q, append the input
// to the existing String + the delimiter
while(tryAgain)
{
System.out.println("Name: (q to quit)");
fName = myScanner.nextLine();
System.out.println("Last Name: (q to quit)");
lName = myScanner.nextLine();
System.out.println("Addess: ");
address = myScanner.nextLine();
System.out.println("Age: ");
age = myScanner.nextLine();
System.out.println("Gender: ");
gender = myScanner.nextLine();
System.out.println("Race: ");
race = myScanner.nextLine();
if(fName.equals("q"))
{
tryAgain = false;
}
else
{
// Append new name to the list using a delimiter
regList = fName + lName + "\n" + address + "\n" + age + "\n" + gender + "\n" + race + MY_DELIMITER;
}
} // end of while( )
System.out.println("Here is your registration:" + regList);
// Convert the String into an array, using the same delimiter
String[ ] regArray = regList.split(MY_DELIMITER);
// Ask the user if they want to display the contents of the array
// If "y" then display the list using a foreach loop
System.out.println("Would you like to see the registration from the Array? [y-n]");
fName = myScanner.nextLine( );
myScanner.close();
fName = fName.toLowerCase( );
showList = fName.equals("y")?true:false;
if(showList)
{
// Display the results using for each
System.out.println("Here is your registration from the array: ");
// Use a for each statement instead of the more complex for( ) loop
// for(int counter=0; counter < employeeArray.length; counter++)
for(String thisReg:regArray)
{
System.out.println(thisReg);
System.out.printf("USER ID: ", A + "-" + B + "-" + C + "-" + D);
}
} // end of if(showList)
}
}
I am trying to extract out the first 3 letters of the fName input, so I figured I could use fName.substring to do that, but it gives me this error.
Sorry I didn't add all of my code, to save time. Apparently it looked confusing. Any way so the fName input is the name of the user. Can it not be in that order?
Erm...your sequence of operations is suspect. Everywhere, actually.
Look at the following interaction:
String fName = "";
String A = fName.substring(0,2);
You declare an empty string, then immediately take the substring of it. Where are you getting the data for the substring from? There's nothing to substring here - the empty string has a length of zero.
You should be certain that you're putting data into your string before taking a substring of it. Using a Scanner would go a long way here.
Or better yet, moving your instance of myScanner at the top of main would make it much clearer as to where that's supposed to go, and how it's supposed to work.
Always check the length of string before substring anything. Especially when a user is giving you this variable.
You are trying to get a substring of an empty string.
String fName = "";
String A = fName.substring(0,2); // here fName is empty!!!
Change fName into some actual String and also check for length of the String before calling substring to make sure substring of the size you want exists.
String fName = "somestring";
if(fName.length() >= 2) {
String A = fName.substring(0,2);
System.out.println(A); // prints out "so"
}
That is the case with all of your other Strings as well.
Can someone help me please. I have done numerous searches but can't find a solution anywhere.
I'm a beginner to Java and currently practicing some code while on a break from college.
I am trying to make a Phonebook program. At the moment I am trying to add a new contact, below is the code i have but i am not sure how to store the information in an array can someone give me some pointers please.
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
//inputs
String name = "";
String phone = "";
String add1 = "";
String add2 = "";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (name.equals(""))
{
System.out.println("Enter contacts name: ");
name = input.nextLine();
name += contactName[];
}
while (add1.equals(""))
{
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[];
}
while (add2.equals(""))
{
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[];
}
while (phone.equals(""))
{
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[];
}
}
}
A cleaner approach would be to create a Person object that contains contactName, contactPhone, etc. Then, use an ArrayList rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:
while (!done) {
Person person = new Person();
String name = input.nextLine();
person.setContactName(name);
...
myPersonList.add(person);
}
Using the list will remove the need for array bounds checking.
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index.
The second problem you have is that you don't have the variable index.
What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)
//go through this code I have made several changes in it//
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (i<11)
{
i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}
while (i<12)
{
i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}
}
}
Would this work better?
import java.util.Scanner;
public class Work {
public static void main(String[] args){
System.out.println("Please enter the following information");
String name = "0";
String num = "0";
String address = "0";
int i = 0;
Scanner input = new Scanner(System.in);
//The Arrays
String [] contactName = new String [7];
String [] contactNum = new String [7];
String [] contactAdd = new String [7];
//I set these as the Array titles
contactName[0] = "Name";
contactNum[0] = "Phone Number";
contactAdd[0] = "Address";
//This asks for the information and builds an Array for each
//i -= i resets i back to 0 so the arrays are not 7,14,21+
while (i < 6){
i++;
System.out.println("Enter contact name." + i);
name = input.nextLine();
contactName[i] = name;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact number." + i);
num = input.nextLine();
contactNum[i] = num;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact address." + i);
num = input.nextLine();
contactAdd[i] = num;
}
//Now lets print out the Arrays
i -= i;
while(i < 6){
i++;
System.out.print( i + " " + contactName[i] + " / " );
}
//These are set to print the array on one line so println will skip a line
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactNum[i] + " / " );
}
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactAdd[i] + " / " );
}
System.out.println();
System.out.println("End of program");
}
}
Please correct me if I'm wrong.`
public static void main(String[] args) {
Scanner na = new Scanner(System.in);
System.out.println("Please enter the number of contacts: ");
int num = na.nextInt();
String[] contactName = new String[num];
String[] contactPhone = new String[num];
String[] contactAdd1 = new String[num];
String[] contactAdd2 = new String[num];
Scanner input = new Scanner(System.in);
for (int i = 0; i < num; i++) {
System.out.println("Enter contacts name: " + (i+1));
contactName[i] = input.nextLine();
System.out.println("Enter contacts addressline1: " + (i+1));
contactAdd1[i] = input.nextLine();
System.out.println("Enter contacts addressline2: " + (i+1));
contactAdd2[i] = input.nextLine();
System.out.println("Enter contact phone number: " + (i+1));
contactPhone[i] = input.nextLine();
}
for (int i = 0; i < num; i++) {
System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
}
}
`
There is no use of pointers in java so far. You can create an object from the class and use different classes which are linked with each other and use the functions of every class in main class.
I've created a scanner class to read through the text file and get the value what I'm after. Let's assume that I have a text file contains.
List of people: length 3
1 : Fnjiei : ID 7868860 : Age 18
2 : Oipuiieerb : ID 334134 : Age 39
3 : Enekaree : ID 6106274 : Age 31
I'm trying to get a name and id number and age, but everytime I try to run my code it gives me an exception. Here's my code. Any suggestion from java gurus?:) It was able to read one single line....... but no more than a single line of text.
public void readFile(String fileName)throws IOException{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
try {
while (input.hasNextLine()){
int howMany = 3;
System.out.println(howMany);
String userInput = input.nextLine();
String name = "";
String idS = "";
String ageS = "";
int id;
int age;
int count=0;
for (int j = 0; j <= howMany; j++){
for (int i=0; i < userInput.length(); i++){
if(count < 2){ // for name
if(Character.isLetter(userInput.charAt(i))){
name+=userInput.charAt(i); // store the name
}else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 2){ // for id
if(Character.isDigit(userInput.charAt(i))){
idS+=userInput.charAt(i); // store the id
}
else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 3){ // for age
if(Character.isDigit(userInput.charAt(i))){
ageS+=userInput.charAt(i); // store the age
}
}
id = Integer.parseInt(idS); // convert id to integer
age = Integer.parseInt(ageS); // convert age to integer
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
userInput = input.nextLine();
}
}
}finally{
if (input != null){
input.close();
}
}
}
My appology if my mere code begs to be changed.
Edited It gives me a number format exception!!!
I dont know how many empty space would be there between these values.
Here's a solution that uses only Scanner API, the important one being findInLine. It can handle minor syntactic variations in the input format, and yet it's very readable, requiring no need for fancy regex or magic array indices.
String text =
"List of ##%^$ people : length 3 !#%# \n" +
"1 : Fnjiei : ID 7868860 ::: Age 18\n" +
" 2: Oipuiieerb : ID 334134 : Age 39 (old, lol!) \r\n" +
" 3 : Enekaree : ID 6106274 => Age 31\n";
Scanner sc = new Scanner(text);
sc.findInLine("length");
final int N = sc.nextInt();
for (int i = 0; i < N; i++) {
sc.nextLine();
sc.findInLine(":");
String name = sc.next();
sc.findInLine("ID");
long id = sc.nextLong();
sc.findInLine("Age");
int age = sc.nextInt();
System.out.printf("[%s] %s (%s)%n", id, name, age);
}
This prints:
[7868860] Fnjiei (18)
[334134] Oipuiieerb (39)
[6106274] Enekaree (31)
API links
Scanner.findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern ignoring delimiters.
Use this Pattern.compile overload if performance is an issue
This seems to be shorter:
public void readFile(String fileName)throws IOException
{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
String userInput;
try
{
while (input.hasNextLine())
{
userInput = input.nextLine().trim();
if (userInput.length() > 0)
{
String[] userInfo = userInput.split(":");
int count = Integer.parseInt(userInfo[0].trim());
String name = userInfo[1].trim();
int id = Integer.parseInt(userInfo[2].trim().split("\\s+")[1].trim());
int age = Integer.parseInt(userInfo[3].trim().split("\\s+")[1].trim());
System.out.println("Count: " + count + " Name: " + name + " ID:" + id + " Age:" + age);
}
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
}
finally
{
if (input != null)
{
input.close();
}
}
}
For the input you have us, it prints this:
Count: 1 Name: Fnjiei ID:7868860 Age:18
Count: 2 Name: Oipuiieerb ID:334134 Age:39
Count: 3 Name: Enekaree ID:6106274 Age:31
More information about the split method can be found here. I basically first split the line by using the : as delimiter, then, I split again using the \\s+, which basically splits a string and return an array containing the words that were separated by white spaces.
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader("filename")));
try{
while(input.hasNextLine()){
String userInput = input.nextLine();
String[] data = userInput.split(":");
System.out.println("Name: "+data[1]+" ID:"+data[2].split("\\s+")[2]+
" Age:"+data[3].split("\\s+")[2]);
}
}finally{
if(input != null)
input.close();
}
Above snippet shows the basic idea.Also please keep in mind that this might not be the optimal solution.