Printing specific user input in java - java

I have to design a program that gets 3 user-inputs in the form:
Name1 (any number of spaces) age1
Name2 (any number of spaces) age3
Name3 (any number of spaces) age3
Then print line which has the highest age (suppose Name3 age3 had the highest age I'd print his line).
My Code:
import java.util.*;
public class RankAge{
public static void main(String[] args){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n1 = sc.nextLine();
String n2 = sc.nextLine();
String n3 = sc.nextLine();
}
}
I know how to scan the user-inputs, but i don't know how to do a comparison of the number within the acquired string to print a specific one (also since there can be any number of spaces it seems even more complicated to me).

You can use split to get the person's age:
String age = "Jon 57".split("\\s+")[1]; // contains "57"
You can then use Integer.parseInt(age) to get the person's age, as a number.
If you need to allow the user to input a name with spaces, you can adjust the number in square brackets ([]). For example, [2] would require the user to input a first name and last name.

Managed to do it with frenchDolphin's suggestion. This is the code i used (it's quite beginner friendly):
import java.util.*;
public class RankAge{
public static void main(String[] args){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n1 = sc.nextLine();
String a1 = n1.split("\\s+")[1];
String n2 = sc.nextLine();
String a2 = n2.split("\\s+")[1];
String n3 = sc.nextLine();
String a3 = n3.split("\\s+")[1];
if(Integer.parseInt(a1) > Integer.parseInt(a2)){
} if(Integer.parseInt(a1) > Integer.parseInt(a3)){
System.out.println(n1);
}else if(Integer.parseInt(a2) > Integer.parseInt(a3)){
System.out.println(n2);
}else{
System.out.println(n3);
}
}
}

+1 because at first look it seemed very simple but when I started implementing the complexities started showing up. Here is the complete solution for your problem,
import java.util.*;
public class RankAge {
public static void main(String s[]){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n[] = new String[3];
for(int i=0;i<3;i++){
n[i] = sc.nextLine();
}
int age[] = new int[3];
age[0] = Integer.parseInt(n[0].split("\\s+")[1]);
age[1] = Integer.parseInt(n[1].split("\\s+")[1]);
age[2] = Integer.parseInt(n[2].split("\\s+")[1]);
int ageTemp[] = age;
for(int i=0;i<age.length;i++){
for(int j=i+1;j<age.length;j++){
int tempAge = 0;
String tempN = "";
if(age[i]<ageTemp[j]){
tempAge = age[i];
tempN = n[i];
age[i] = age[j];
n[i] = n[j];
age[j] = tempAge;
n[j] = tempN;
}
}
}
for(int i=0;i<3;i++){
System.out.println(n[i]);
}
}
}

Related

Comparing Strings ( the user types as many as he wants) and then telling which one is first (based on which first letter comes first) using for loop

First I have to ask the user to type a number. That number will decide how many sentences he has to type (should be >2 ) and then I have to compare those sentences. I have to tell which one comes first ( based on alphabet letters order). This is all I have done so far. I don't know how to compare Strings since I don't know how many the user will type and don't have names for them.
import java.util.*;
public class Sentences {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.println("Type a number > 2");
number = scan.nextInt();
}
scan.nextLine();
String sentence;
int y = 0;
for (int i = 0; i < number; i++) {
System.out.println("Type a sentence");
sentence = scan.nextLine();
}
}
}
You were close. Instead of a single variable(sentence), you need an array(sentences[]) as shown below:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.print("Type a number > 2: ");
number = Integer.parseInt(scan.nextLine());
}
String[] sentences = new String[number];
int y = 0;
for (int i = 0; i < number; i++) {
System.out.print("Type a sentence: ");
sentences[i] = scan.nextLine();
}
Arrays.sort(sentences);
for (String sentence : sentences) {
System.out.println(sentence);
}
}
}
To sort String sentences[], you need to use Arrays.sort(sentences) as shown above.
A sample run:
Type a number > 2: 0
Type a number > 2: 3
Type a sentence: Hello world
Type a sentence: You are awesome
Type a sentence: My name is Jane
Hello world
My name is Jane
You are awesome
[Update]
As per your clarification, you wanted to print only one sentence which is the lowest in alphabetical order. It is like tracking the minimum number from a list of numbers.
The algorithm is as follows:
Store the first input to a variable, say lowestAlphabetical.
In a loop, compare the value of lowestAlphabetical with the next input and if the next input is lower in alphabetical order put the next input into lowestAlphabetical.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.print("Type a number > 2: ");
number = Integer.parseInt(scan.nextLine());
}
// Scan the first sentence
System.out.print("Type a sentence: ");
String sentence = scan.nextLine();
// Since we have only one sentence till now, it is also the lowest in
// alphabetical order
String lowestAlphabetical = sentence;
// Loop for next inputs
for (int i = 1; i < number; i++) {
System.out.print("Type the next sentence: ");
sentence = scan.nextLine();
if (sentence.compareTo(lowestAlphabetical) < 0) {
lowestAlphabetical = sentence;
}
}
System.out.println(lowestAlphabetical);
}
}
A sample run:
Type a number > 2: 3
Type a sentence: Hello world
Type the next sentence: Good morning
Type the next sentence: My name is Jane
Good morning

Facing an issue while displaying output to the console

I'm trying to store input in the array indoor_games and output it to the screen, but when I'm executing the code, it abruptly ends the execution after accepting 1 value.
package games;
import java.util.*;
import java.lang.*;
class Indoor{
String name;
Indoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Outdoor{
String name;
Outdoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
for(int i=0;i<size;i++){
name = sc.next();
indoor_games[i] = new Indoor(name);
}
for(int i=0;i<size;i++)
indoor_games[i].display();
}
}
Updated code with nextLine added but still the same problem:
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
sc.nextLine(); //To consume the newline character
Indoor[] indoor_games = new Indoor[size];
for(int i = 0 ; i < size ; i++){
name = sc.nextLine();
indoor_games[i] = new Indoor(name);
}
for(int i = 0 ; i < size; i++)
indoor_games[i].display();
}
}
Output(Command Line)
D:\Docs Dump\School stuff\JAVA\Java slips>java games.Slip20
Enter number of Players in Indoor Games:
3
Neeraj
D:\Docs Dump\School stuff\JAVA\Java slips>
As you can see, the scanner only accepts "Neeraj" and the program ends
execution.
just replace sc.next() by sc.nextLine()
This is because nextLine() required. But be aware use it, documentation say that:
Advances this scanner past the current line and returns the input
* that was skipped.
This method returns the rest of the current line, excluding any line
* separator at the end. The position is set to the beginning of the next
* line.
Known that you should use before loop and problem will be solved.
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
sc.nextLine();
for (int i = 0; i < size; i++) {
System.out.println("Please write a name:");
indoor_games[i] = new Indoor(sc.nextLine());
}
Hey thanks for the answers and help. It was actually a compilation problem, I was compiling the package in a wrong way. It's working now.

Java-Returning an Array from an Array Method to the Main Function

public static public static void main(String[] args) {
System.out.print("Enter the number of student names to input: ");
int studentNum = new Scanner(System.in).nextInt();
String students[ ] = new String[studentNum];
for(int i = 0; i<studentNum; i++){
students[ i ] = inputStudent(i+1);
}
}
public static String[] inputStudent(int i) {
String studentNum[] = new String[i];
for(int a=0; a<i; a++) {
System.out.print("Enter student name"+(a+1)+": ");
studentNum[a]=new Scanner(System.in).nextLine();
}
return studentNum;
}
ERROR:
students[ i ] = inputStudent(i+1);
IT SAYS:
incompatible types: String[] cannot be converted to String
PS:
The main function should not be modified.
You are trying to assign String array to String
i.e
inputStudent(int i)
returns Array, but you are trying to assign Array to students[ i ] = inputStudent(i+1);
As
String[i] is the element String array which will accept String only
Change your method to this. You cannot assign a String array to a String. Also, why do you loop in your method? If I understand correctly you want to add n students to a student array? You loop in your main and method runs for each student.
public static String inputStudent(int i) {
System.out.print("Enter student name");
String studentName = new Scanner(System.in).nextLine();
return studentName;
}
Modify your input student method in such a way that it returns a single student only.
public static String inputStudent(int i) {
String studentNam = null;
System.out.print("Enter student name"+i+": ");
studentNum=new Scanner(System.in).nextLine();
return studentNum;
}
Since you stipulate that the main function can not be modified you are going to have to change the return type of your inputStudent function from String[] to String. This will mean you have to change how you are storing the data inside that function.
So, change the String studentNum[] to String studentNum and instead of asking for a new user input for every index of the array, ask for all inputs at once comma separated and store them in studentNum.
This is one possible approach according to your criteria.
I understand what you want to implement, the code below will solve your problem, every line of code has the explanation.
public static void main(String[] args) throws Exception {
System.out.print("Enter the number of student names to input: ");
Scanner scanner = new Scanner(System.in); // get the scanner
int numOfStudents = scanner.nextInt(); // get the number of students from user
String [] students = new String [numOfStudents]; // create an array of string
int studentAdded = 0; // counter
scanner = new Scanner(System.in); // recreate the scanner, if not it will skip the first student.
do {
System.out.println("Enter student name "+(studentAdded+1)+": ");
String studentName = scanner.nextLine(); // ask for student name
students[studentAdded] = studentName; // add student name to array
studentAdded++; // add 1 to the counter
} while (studentAdded < numOfStudents); // loop until the counter become the same size as students number
System.out.println("students = " + Arrays.toString(students)); // and show the result
}
What you can do to do is change:
students[ i ] = inputStudent(i+1);
to
students[ i ] = Arrays.toString(inputStudent(i + 1));
As students is a String you are unable to assign an array directly to a String. By using Array.toString() it will return a representation of the contents of the array as a String value.
Looking at your question again you are unable to modify the main. In this case we can set inputStudent to return a String type.
public static String inputStudent( int i )
{
String studentNum[] = new String[i];
for( int a = 0; a < i; a++ )
{
System.out.print( "Enter student name" + (a + 1) + ": " );
studentNum[a] = new Scanner( System.in ).nextLine();
}
return Arrays.toString(studentNum);
}
Or short and sweet.
public static String inputStudent( final int id )
{
System.out.print("Enter student name at ID: "+id+": ");
return new Scanner( System.in ).next();
}
You have an error in your code. For loop is not needed in main
public static public static void main(String[] args) {
System.out.print("Enter the number of student names to input: ");
int studentNum = new Scanner(System.in).nextInt();
String students[ ] = inputStudent(studentNum);
}
public static String[] inputStudent(int i) {
String studentNum[] = new String[i];
for(int a=0; a<i; a++) {
System.out.print("Enter student name"+(a+1)+": ");
studentNum[a]=new Scanner(System.in).nextLine();
}
return studentNum;
}

get input from user and store it in String Array in Java

i write one program that get input from user as "Enter number of students:" then add the student names into it and print it in console. I write one code that run fine but problem is the loop is already ramble one time the code is not properly working i also want to know that how to get inputs using command line argument without Scanner and store it in String Array
Current Output is like that
Here is my code please help and i am in learning phrase of Java
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns
the input that was skipped.
Try placing a scanner.nextLine(); after each nextInt() if you intend
to ignore the rest of the line.
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
You can use array args[]
Need not pass number of students there.
So what ever name you pass on command prompt after java <className> shall be stored in this array and you can iterate over it.
Add in.nextLine(); after you assign this int totalstudents = in.nextInt();
use ArrayList instead of String Array
declare header file
import java.util.ArrayList;
change your code
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
Try this code:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}

Converting a 5 digit integer into a column

I have to write a program to convert a 5 digit integer such as 12345 or 00005 into a column showing each individual digit on separate lines. I am asked to use two different methods, a mathematical method and string method. While the string method has given me no problems at all I am having trouble pulling each digit out individually using a mathematical method. This is my code thus far.
import java.util.Scanner; //load scanner
public class digitseparator{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter a five-digit integer: ");
String name = in.nextLine();
double n = in.nextDouble();
double ffthdgt = Double.parseInt((double)n%10000);
double frthdgt = Double.parseInt((double)n%1000);
double thrddgt = Double.parseInt((double)n%100);
double scnddgt = Double.parseInt((double)n%10);
double frstdgt = Double.parseInt((double)n%1);
System.out.println(frstdgt);
System.out.println(scnddgt);
System.out.println(thrddgt);
System.out.println(frthdgt);
System.out.println(ffthdgt);
System.out.println("String method Solution");
char frst = name.charAt(0);
System.out.println(frst);
char scnd = name.charAt(1);
System.out.println(scnd);
char thrd = name.charAt(2);
System.out.println(thrd);
char frth = name.charAt(3);
System.out.println(frth);
char ffth = name.charAt(4);
System.out.println(ffth);
}
}
First, Double has no parseInt method. It has parseDouble, which is meant to parse a String into a double. But you already have a double.
Next, you can extract a digit by...
Dividing by a power of 10 to eliminate digits to the right of the desired digit.
Taking the remainder of dividing by 10 to extract the last digit, with the % operator.
import java.util.Scanner; //load scanner
public class digitseparator
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int arr[] = new int[5];
System.out.println("Enter a five-digit integer: ");
int d =in.nextInt();
String name = Integer.toString(d);
System.out.println(name);
for(int i=0;i<5;i++)
{
arr[i] = d%10;
d = d/10;
}
for(int k=0;k<5;k++)
{
System.out.println(arr[k]);
}
System.out.println("String method Solution");
for(int m=0;m<5;m++)
{
System.out.println(name.charAt(m));
}
}
}
Hope this is what you want

Categories

Resources