String input into String array - java

import java.util.*;
public class Student {
private String [] first;
private String [] last;
private String [] HKID;
private String[] SID;
private int []Exam;
private int num;
Scanner kb= new Scanner(System.in);
public Student (String f, String l, String h, String s, int e, int n){
System.out.println("Please enter number of students:");
n = kb.nextInt();
for(int i=0;i >n; i++){
System.out.println("First name:");
f = kb.next();
first = new String[f];
System.out.println("Last name:");
l=kb.next();
last= new String[l];
System.out.println("HKID:");
h=kb.next();
HKID=new String[h];
System.out.println("SID:");
s=kb.next();
SID=new String [s];
System.out.println("Final exam score:");
e=kb.nextInt();
Exam=new int [e];
}
public String[] getFirst(){return first;}
public String [] getLast(){return last;}
public String [] getHKID(){return HKID;}
public String [] getSID(){return SID;}
public int [] getExam(){return Exam;}
public void setFirst(String [] f){f=first;}
public void setLast(String [] l){l=last;}
public void setHKID(String [] h){h=HKID;}
public void setSID(String [] s){s= SID;}
public void setExam(int [] e){e=Exam;}
}
I am creating a code that first asks user how many students are in the class. From this it asks several details to enter for each student and stored in their respective arrays. Problem: I can't put enter a String variable into my String array. I can't think of any way around this. Please help.

Problem is :
for(int i=0;i >n; i++)
{
}
Write This :
for(int i=0;i <n; i++)
{
// your code
}
You are not initialize a String array .
import java.util.*;
class Student
{
private String [] first;
private String [] last;
private String [] HKID;
private String[] SID;
private int []Exam;
private int num;
Scanner kb= new Scanner(System.in);
int n=0;
public Student (){
System.out.println("Please enter number of students:");
n = kb.nextInt();
first = new String[n];
last= new String[n];
HKID=new String[n];
SID=new String [n];
Exam=new int [n];
for(int i=0;i <n; i++)
{
System.out.println("First name:");
first[i]= kb.next();
System.out.println("Last name:");
last[i]=kb.next();
System.out.println("HKID:");
HKID[i]=kb.next();
System.out.println("SID:");
SID[i]=kb.next();
System.out.println("Final exam score:");
Exam[i]= kb.nextInt();
}
System.out.print("Student Detail");
System.out.print("First Name \t Last Name \t HKID \t SID \t Final exam score \n " );
for(int i=0;i<n;i++)
{
System.out.print(first[i]+"\t"+last[i]+"\t"+HKID[i]+"\t"+SID[i]+"\t"+Exam[i]);
System.out.println();
}
}
public static void main (String[] args) {
new Student();
}
}

Firstly initialize all arrays to size 'n' which you are reading outside for loop.
Then,Inside your for loop you can directly mention
for(i=o;i<n;i++){
System.out.println("First name:");
f = kb.next();
first[i] = f;
}
kb.next() returns a String object so u can also directly do first[i]=kb.next();
The main issue with your code here is that you are passing string object to define size of array which is incorrect (i.e here new String[f])
Hope this helps!
All The Best!

First , I don't konw why you create the constructor like this
public Student (String f, String l, String h, String s, int e, int n)
Meanwhile , you override each parameter in it
Second , one way to convert a String parameter into array is
char arr1[]=new char[len1];
arr1=s1.toCharArray()
String[] is an array of String , and char[] is a array of char ,which means a String.

Related

String name is not getting printed

import java.util.*;
//student class
class Student{
String name;
int rollNo;
Student(String name, int rollNo){
this.name=new String(name);
this.rollNo=rollNo;
}
}
class Demo {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int noOfStudents = in.nextInt();
Student[] StudentList= new Student[noOfStudents];
PriorityQueue<Student> set=new PriorityQueue<Student>(new Comparator<Student>(){
public int compare(Student a, Student b){
return b.rollNo-a.rollNo;
}
});
for(int i=0;i<noOfStudents;i++){
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
set.add(new Student(name,rollNo));
}
while(!set.isEmpty()){
Student tmp = set.poll();
System.out.println(tmp.name+" "+tmp.rollNo);
}
}
}
I am trying to take n students name and roll no and then printing it. But this is not printing the names of student
I have added the extra nextline() to enable integer entry
I always feel difficulty in this thing. Please help!
Replace
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
by
in.nextLine();
String name = in.nextLine();
int rollNo = in.nextInt();
You can find the full explanation of your issue here : https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/
Change:
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
to
String name = in.next();
int rollNo = in.nextInt();
I think this version works as you can see from the picture. I added this line:
in.nextLine(); // it consumes the newline and moves to the starting of the next line.
Here's the code:
import java.util.*;
//student class
class Student{
String name;
int rollNo;
Student(String name, int rollNo){
this.name=new String(name);
this.rollNo=rollNo;
}
}
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Inert the number of students, please");
int noOfStudents = in.nextInt();
Student[] StudentList= new Student[noOfStudents];
PriorityQueue<Student> set=new PriorityQueue<Student>(new Comparator<Student>(){
public int compare(Student a, Student b){
return b.rollNo-a.rollNo;
}
});
for(int i=0;i<noOfStudents;i++){
in.nextLine(); // it consumes the newline and moves to the starting of the next line.
System.out.println("Enter the student's name "+i);
String name = in.nextLine();
System.out.println("Enter the student ID number "+i);
int rollNo = in.nextInt();
set.add(new Student(name,rollNo));
}
while(!set.isEmpty()){
Student tmp = set.poll();
System.out.println(tmp.name.toString()+" "+tmp.rollNo);
}
}
}
Execution of Java program
Best regards from Italy.

Java exception running function listEmployee(): java.util.IllegalFormatConversionException

I'm very new to java and I can't figure out what it is I'm doing wrong, it's properly something really basic, I want to be able to add information about employees and then then display/list that data (id, first name, last name, salary, position etc ) using a menu() method.
Everything compiles and adding employee information with addEmployee() seems to work fine but when running listEmployees() I get the exception: java.util.IllegalFormatConversionException.
I have been playing around with it for a bit but I'm not getting anywhere, any help would be greatly appreciated.
import java.util.*;
public class Employee
{
final static int MAX=20;
static int [] idArray= new int[MAX];
static String [] firstnameArray= new String[MAX];
static String [] lastnameArray= new String[MAX];
static int count=0;
public static void add(int id, String fname, String lname)
{
idArray[count] = id;
firstnameArray[count] = fname;
lastnameArray[count] = lname;
++count;
}
public static void addEmployee()
{
Scanner sc=new Scanner(System.in);
for(int i=0; i<idArray.length; i++)
{
System.out.println("Enter your id as an integer");
System.out.print(" (0 to finish): ");
int id = sc.nextInt();
sc.nextLine();
if (id==0)E
return;
System.out.println("Enter your First name");
String fname = sc.nextLine();
System.out.println("Enter your Last name");
String lname = sc.nextLine();
add(id, fname, lname);
}
}
public static void listEmployees()
{
for(int i=0; i<count; ++i)
{
System.out.printf("%-15s %10d \n",idArray[i],firstnameArray[i],lastnameArray[i] );
}
}
public static void printMenu()
{
System.out.println
(
"\n ==Menu==\n" +
"1. Add Employee\n"+
"2. Display Employee\n"+
"3. Quit\n"
);
}
public static void menu()
{
Scanner input = new Scanner(System.in);
int option = 0;
while(option!=3)
{
printMenu();
System.out.println("Please enter your choice");
option = input.nextInt();
switch(option)
{
case 1:
addEmployee();
break;
case 2:
listEmployees();
break;
case 3:
break;
default:
System.out.println("Wrong option");
}
}
}
public static void main(String [] args)
{
menu();
}
}
You are passing a string (lastnameArray[i]) to a numeric format (%10d). You need to first convert the string lastnameArray[i] to an int/long and then pass that value to %10d.
System.out.println(idArray[i] + " " + firstnameArray[i] + " " + lastnameArray[i]);
use this one instaed of your printing statement
The printf function has the wrong arguments passed to it. You should match the format and parameters passed to print them in the same order. Assuming you are passing the correct parameter to be printed, the first parameter should have %d , %s , %s respectively.

How to print the middle name in reverse order?

The problem I am having is that when I enter for example Gina Charlene Doe it will print out enelr.
import java.util.Scanner;
import java.io.*;
public class test_1
{
static Scanner in = new Scanner(System.in);
public static void main() {
String name, middle;
System.out.println("Enter your first, middle, and last name ");
name=in.nextLine();
int space1=name.indexOf(" ");
int space2=name.lastIndexOf(" ");
middle=name.substring(space1+1,space2);
for (int x=middle.length();x>=space1;x--)
{
System.out.print(middle.substring(x-1,x));
}
}
}
Sorry I am new to posting things to here so I hope it's formatted well enough.
Based on your output, your loop is working but terminating too early. So something is wrong with your for loop
for (int x=middle.length();x>=space1;x--)
Your condition, x>=space1, is the source of error because you set it to 5 here:
int space1=name.indexOf(" ");
So in your loop, it works down your string from 8 and terminates when x = 4, which is midway through your string, obviously not what you want. So the correct fix is
for (int x=middle.length();x>0;x--)
Your for loop is just logically flawed. Here is the correct code
import java.util.Scanner;
public class Middle
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String name, middle, reversed = "";
System.out.println("Enter your first, middle, and last name ");
name=in.nextLine();
int space1=name.indexOf(" ");
int space2=name.lastIndexOf(" ");
middle=name.substring(space1+1,space2);
for(int i=middle.length(); i > 0; i--)
{
reversed = reversed + middle.charAt(i-1);
}
System.out.println(reversed);
}
}
Try this way!
import java.util.Scanner;
public class Middle{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter your first, middle and last name.");
String[] name = in.nextLine().split(" ");
for(int i=name[1].length()-1; i>=0; i--){
System.out.print(name[1].charAt(i));
}
}
}
How to print the middle name in reverse order?
The straight answer is new StringBuilder(middle).reverse().toString();
Solution:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// input
System.out.println("Enter your first, middle, and last name ");
String fullname = in.nextLine();
// split
String[] fullnameArray = fullname.trim().split("\\s");
// parse
String first = fullnameArray[0];
String middle = fullnameArray[1];
String last = fullnameArray[2];
// reverse middle name
String middleReversed = new StringBuilder(middle).reverse().toString();
// output
System.out.println("First name:" + first);
System.out.println("middle name (reversed):" + middleReversed);
System.out.println("last name:" + last);
}

How to read and use the String array using scanner class or other in java

How to read and use the String array using scanner class or other in java
i could read the String into array like that below
arr[0]="apple";
arr[1]="mango";
arr[2]="banana";
.
.
.
and soon
but in by using scanner class how it possible pls tell me
and any help full "for each" in java String arrays...
To read into string array and then read the populated array you could use:
public static void main(String [] args){
// to populate string array`enter code here`
Scanner sc = new Scanner(System.in);
int length = 10, pos = -1;
String arr[] = new String[length];
while(++pos < length){
System.out.print("Enter string : ");
arr[pos] = sc.nextLine();
}
// to read the already populated string array1
for(String s: arr){
System.out.println(s);
}
}
Program to read specific number of elements from the console and write them on the console.
public class Test {
public static void main(String args[]) {
System.out.println("Enter string array size");
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String[] arr = new String[i];
for (int j = 0; j < i; j++) {
System.out.println("Enter next element");
arr[j] = in.next();
}
for (String s : arr) {
System.out.println("Next element[" + s+"]");
}
}
}
import java.util.Scanner;
public class StringRWrite {
public static void main(String[] args) {
Scanner sc1=new Scanner(System.in);
System.out.println("enter the length of String array");
int n=sc1.nextInt();
String[] larray=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter the "+(i+1)+" String :");
larray[i]=sc1.next();
}
System.out.println("Strings Entered by user:");
for(String s:larray){
System.out.println(s);
}
}
}
import java.util.Scanner;
public class StringReadAndWrite {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the length of String array");
int n=sc.nextInt();
String[] sarray=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter the "+(i+1)+" String :");
sarray[i]=sc.next();
}
System.out.println("Strings Entered by user:");
for(String s:sarray){
System.out.println(s);
}
}
}
import java.util.Scanner;
public class BasketballPlayers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of basketball players");
int numberOfPlayers = input.nextInt();
String[] playersArray =new String[numberOfPlayers];
for(int i=0;i< numberOfPlayers;i++){
System.out.println("enter the "+(i+1)+" String :");
playersArray[i]= input.next();
}
System.out.println("BasketBall Player names:");
for(String s:playersArray){
System.out.println(s);
}
}
}

Why is the LinkedList being printed as blank?

Can someone tell me why my baggage won't print?
For passenger name I enter, say, John.
For country code I enter: BI
For flight number I enter: 095
For number of baggage I can enter any amount.
Let's say I enter: John, BI, 095, 3.
This is what I get: [John with baggage(s) [, , ]] when I should be getting
[John with baggage(s) [BI0950, BI0951, BI0952]]
Sorry if the code is quite messy.
It's amended. Thanks guys.
import java.util.*;
public class baggageSys{
public static String getUser_command(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter command B-baggage, n-next, q-quit");
String s = keyboard.nextLine();
return s;
}
public static String getUser_flight(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the flight number");
String s = keyboard.nextLine();
return s;
}
public static String getPassenger(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter passenger name");
String s = keyboard.nextLine();
return s;
}
public static String getUser_country(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the country code");
String s = keyboard.nextLine();
return s;
}
public static int getUser_number(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter number of baggage");
int s = keyboard.nextInt();
return s;
}
public static String next(ListIterator<Passenger> passenger){
String k = "";
passenger.next();
return k;
}
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
public static void main(String args[]) {
LinkedList<Passenger> passenger = new LinkedList<Passenger>();
ListIterator<Passenger> iterator = passenger.listIterator();
LinkedList<String> baggage = new LinkedList<String>();
String command = "";
while (!command.equals("q")){
command = getUser_command();
if(command.equals("B") || command.equals("b")){
String p = "";
p = getPassenger();
passenger.add(new Passenger(p));
// command = getUser_command();
String country = "";
country = getUser_country();
String flight = "";
flight = getUser_flight();
int amount = 0;
amount = getUser_number();
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i]);
passenger.getLast().setBaggages(baggage);
}
System.out.println(passenger);
} else if(command.equals("n")){
next(iterator);
}
else
System.out.println("Enter 'q' to end the program");
}
}
public static class Passenger {
String passengers;
List<String> baggage;
public Passenger(String passengers) {
this.passengers = passengers;
baggage = Collections.emptyList();
}
public void setBaggages(List<String> baggage) {
this.baggage = baggage;
}
#Override
public String toString() {
return passengers + " with baggage(s) " + baggage;
}
}
}
You're not returning anything in your makeBaggage method, as you can see after the loop it returns the x variable which is not either set inside the loop, in this case your loop is useless.
public static String makeBaggage(String country, String flight, int num){
String x = "";
for(int i = 0; i < num; i++){
String[] bgs = new String[num];
bgs[i] = country + flight + i;
// System.out.println(bgs[i]);
}
return x;
}
I think this is the one you're looking for:
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
For this specific line in your code:
for(int i = 0; i < amount; i++){
String[] bg = new String[amount];
bg[i] = makeBaggage(country, flight, amount);
baggage.add(bg[i]);
System.out.println(bg[i]);
...
Move the String[] bg = new String[amount]; declaration outside of the for loop and instead of supplying the amount in the makeBaggage method, use the loop counter instead as follows: bg[i] = makeBaggage(country, flight, i);
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i])
..
I think that should do it. Also, your code could be greatly improved, and that would be your tasks.

Categories