I want get first name when input the name with array and looping
Example :
Enter the name :
1. Alvin Indra
2. Sada Rika
Output :
1. Alvin
2. Sada
Code:
public static void main(String[] args) {
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
System.out.println("First Name : ");
for(int i=0;i<n;i++){
if(teman[i] == ' '){ // this is where I need help
System.out.println((i+1)+". "+teman[i].substring(0,i));
}
}
}
Here you go
String name = "John Smith";
System.out.println(name.split(" ")[0]);
Using this will replace that second for loop, you don't need to cycle through each letter to look for a space you can just use the split method on the string and specifiy the character in which to split the string up and then call the first element.
Updated complete implementation
import java.util.Scanner;
public class testest {
public static void main(String[] args){
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
for(int i=0;i<n;i++){
System.out.println("First Name : ");
System.out.println(teman[i].split(" ")[0]);
System.out.print("\n");
}
}
}
You are probably looking for using contains and indexOf methods of String class in java, to use them as :
if (teman[i].contains(" ")) {
System.out.println((i + 1) + ". " + teman[i].substring(0, teman[i].indexOf(" ")));
}
Related
I am new to Java and have a task: Scanner a number of "strangers' " names, then read these names and print "Hello+name" to the console. If number of strangers is zero, then print "Looks empty", if the number is negative, then print "Looks negative to me".
So the input and output to console should look like this:
3
Den
Ken
Mel
Hello, Den
Hello, Ken
Hello, Mel
So I have this code edited from someone with some related task, but it seems I miss something as I am new to Java...
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
while (num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
} while (num<0) {
System.out.println("Seriously? Why so negative?");
break;
}
String[] numbers = new String[num];
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +input.nextLine());
}
With using do while loop you can ask the number to the user again and again if it is negative number.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int num;
String name;
Scanner scan = new Scanner(System.in);
//The loop asks a number till the number is nonnegative
do{
System.out.print("Please enter the number of strangers: ");
num = scan.nextInt();
if(num<0) {
System.out.println("It cannot be a negative number try again.");
}else if(num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
}else{
String[] strangers = new String[num];
//Takes the names and puts them to the strangers array
for(int i=0;i<num;i++) {
System.out.print("Name " + (i+1) + " : ");
name = scan.next();
strangers[i] = name;
}
//Printing the array
for(int j=0; j<num; j++) {
System.out.println("Hello, " + strangers[j]);
}
break;
}
}while(num<0);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
if(num==0) {
System.out.println("Oh, it looks like there is no one here");
}
else if(num<0) {
System.out.println("Seriously? Why so negative?");
}
else {
String numbers[] = new String[num];
input.nextLine();
for (int i=0; i< num;i++) {
numbers[i]=input.nextLine();
}
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +numbers[i]);
}
}
}
}
This is how your code will look and you'll need to add member function input.nextLine(); to read newline character, so there can't be problem regarding input
So, this below is my code:
public class StudentRun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[50];
int[] rolls = new int[50];
System.out.print("Do you want to register a student ?(yes/no): ");
String res = sc.nextLine();
while((res.toUpperCase()).equals("YES")) {
System.out.print("Enter the student's name: ");
String n = sc.nextLine();
for(int i=1; i<50; i++) {
names[i] = n;
}
System.out.print("Enter their roll number: ");
int r = sc.nextInt();
for(int j=0; j<50; j++) {
rolls[j] = r;
}
}
for(int a=0; a<50; a++) {
System.out.println(names[a]);
System.out.println(rolls[a]);
}
}
}
What I want is to happen is that, the program should keep registering students name and roll no. until the array is full or the user ends it. How do I do it ? I got that far
You need to have the "continue" question in the while loop, and you don't need the for loop every time you insert a name.
public class StudentRun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[50];
int[] rolls = new int[50];
int index = 0;
while(true) {
System.out.print("Do you want to register a student ?(yes/no): ");
String res = sc.nextLine();
if(res.toUpperCase().equals("NO") || index == 50)
break;
System.out.print("Enter the student's name: ");
String n = sc.nextLine();
names[index] = n;
System.out.print("Enter their roll number: ");
int r = sc.nextInt();
rolls[index] = r;
index++;
}
for(int i=0; i<50; i++) {
System.out.println(names[i]);
System.out.println(rolls[i]);
}
}
}
A common approach when using fixed sized arrays is to use a separate int variable to track the current index position for a new item, as well as the total used slots in the array:
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int size = 50;
String[] names = new String[size];
int[] rolls = new int[size];
int counter = 0;
String res = "";
do {
System.out.print("Do you want to register a student ?(yes/no): ");
res = sc.nextLine().toUpperCase();
if (res.equals("YES")) {
System.out.print("Enter the student's name: ");
names[counter] = sc.nextLine();
System.out.print("Enter their roll number: ");
rolls[counter] = sc.nextInt();
sc.nextLine(); // clear enter out of buffer;
counter++;
}
} while (counter < size && res.equals("YES"));
for(int a=0; a<counter; a++) {
System.out.print(names[a] + " : ");
System.out.println(rolls[a]);
}
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
import java.util.Scanner;
public class stringclass {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = input.nextInt();
String [] friends = new String[a];
int count=1;
for(int i=0;i<a;i++){
System.out.println("Enter the name of your friend "+count +":");
friends[i] = input.nextLine();
count++;
}
int count1=1;
for (int j=0;j<a;j++){
System.out.println("Name of your friend "+count1+ "is "+friends[j].toUpperCase());
count1++;
}
}
}
I was writing code to display name of friends using string in java by getting input. But index 0 is not getting a entry
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = Integer.parseInt(input.nextLine());
String[] friends = new String[a];
for (int i = 0; i < a; i++) {
System.out.print("Enter the name of your friend " + (i + 1) + ":");
friends[i] = input.nextLine();
}
for (int j = 0; j < a; j++) {
System.out.println("Name of your friend " + (j + 1) + "is " + friends[j].toUpperCase());
}
}
You need to consume the end of the line that contains the input integer, as explained in comments.
import java.util.Scanner;
public class stringclass {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = input.nextInt();
// This is what you want
input.nextLine();
String [] friends = new String[a];
int count=1;
for(int i=0;i<a;i++){
System.out.println("Enter the name of your friend "+count +":");
friends[i] = input.nextLine();
count++;
}
int count1=1;
for (int j=0;j<a;j++){
System.out.println("Name of your friend "+count1+ "is "+friends[j].toUpperCase());
count1++;
}
}
}
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]);
}
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 7 years ago.
I would like to create a shopping list program, after entering the name and price of product enters them into the arrays and then print the entire list of what is wrong with this code?
import java.util.Scanner;
import java.util.Arrays;
public class List {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
String [] name = new String[4];
double [] price = new double[4];
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = sc.nextDouble();
}
System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price));
}
}
You can resolve it by using nextLine() instead of nextDouble(). However, you need to parse it to a double as your value declared as double :
Scanner sc = new Scanner(System.in);
String [] name = new String[4];
double [] price = new double[4];
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = Double.parseDouble(sc.nextLine()) ;
}
System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price));
Scanner#nextLine() reads the whole line.
Scanner#nextDouble() reads the next token and not the whole line.
So for the second iteration of loop nextLine() will read the same line where you placed the token giving you empty in name[1] and error for double[1]=sc.nextDouble().
Docs
The problem can be solved by adding a nextLine() after reading double variable
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = sc.nextDouble();
if(i<name.length-1)
sc.nextLine(); //will skip the line
}
Demo
So I was using input.nextDouble() and it was giving me Type mismatch error
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[4];
String [] name = new String[4];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter product price");
numbers[i] = Double.parseDouble(input.nextLine());
System.out.println("Please enter product name");
name[i] = input.nextLine();
}
System.out.println(Arrays.toString(name));
System.out.println(Arrays.toString(numbers));
}