PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] When having String and int as an output - how do I print string first?

 July 20, 2022     input, integer, java, output, string     No comments   

Issue

This code doesn't work, whenever I as an user input String data first and then int data, it just accepts input and doesn't print out the data. If I change:

String name = input.nextLine();
int age = input.nextInt(); 

position of these two code blocks, and enter int first and String as second value after then it happily prints first int number and then String. Please help out how to solve it. I want to be able Name and Family name first and then I want to have age.

package package1;

import java.util.Scanner;

public class experiment {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        try {
            System.out.println("Please enter your age and name: ");

            String name = input.nextLine();
            int age = input.nextInt();

            System.out.println("Your age is: " + age);
            System.out.println("Your name is: " + name);
        } finally {
            input.close();
        }
    }

}

My input is:

Aks Eyeless 2022


Solution

Here's how to enter the name and age on one line.

Please enter your name and age: Gilbert Le Blanc 66
Your age is: 66
Your name is: Gilbert Le Blanc

You perform a Scanner nextLine method, and then you parse (separate) the age from the name. The String class has lots of useful methods for parsing a string.

Here's the modified code.

import java.util.Scanner;

public class Experiment {
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        try {
            System.out.print("Please enter your name and age: ");

            String text = input.nextLine();
            int endIndex = text.lastIndexOf(' ');
            String name = text.substring(0, endIndex);
            int age = Integer.valueOf(text.substring(endIndex + 1));

            System.out.println("Your age is: " + age);
            System.out.println("Your name is: " + name);
        } finally {
            input.close();
        }
    }

}


Answered By - Gilbert Le Blanc
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing