At start ,I am initiating 20 size array fields for taking input (i.e. std_id, name,...etc) .
I wants to create a dynamic array for these fields instead intializing length at start.
The dynamic array should be assigned its length as per the input entered by the user.
Please help in the below code.
public class Input {
private int[] std_id = new int[20];// initiating 20 size
private String[] name = new String[20];
private int[] age = new int[20];
private String[] email = new String[20];;
Scanner in = new Scanner(System.in);
private final List<Student> Students = new ArrayList<Student>();
public Input()
{
initInput();
}
public void initInput()
{
int rec;
System.out.println("How many records do u want to enter:");
rec = in.nextInt();
for(int i=0 ; i <= rec; i++)
{
std_id[i] = in.nextInt();
name[i] = in.next();
age[i] = in.nextInt();
email[i] = in.next();
}
for(int i=0; i <= rec ; i++)
{
Students.add(new Student(std_id[i],name[i], age[i], email[i]));
}
}
}
Use following lines just after reading the value of rec from user:
std_id = new int[rec];
name = new String[rec];
age = new int[rec];
email = new String[rec];
Following is fully corrected code:
public class Input {
private int[] std_id;// initiating 20 size
private String[] name;
private int[] age;
private String[] email;
Scanner in = new Scanner(System.in);
private final List<Student> Students = new ArrayList<Student>();
public Input()
{
initInput();
}
public void initInput()
{
int rec;
System.out.println("How many records do u want to enter:");
rec = in.nextInt();
std_id = new int[rec];
name = new String[rec];
age = new int[rec];
email = new String[rec];
for(int i=0 ; i < rec; i++)
{
std_id[i] = in.nextInt();
name[i] = in.next();
age[i] = in.nextInt();
email[i] = in.next();
}
for(int i=0; i < rec ; i++)
{
Students.add(new Student(std_id[i],name[i], age[i], email[i]));
}
}
}
Note: While using loop, don't use i <= rec because you are using wrong index and you will get ArrayIndexOutOfBoundsException. Use i < rec instead.
Initialize the arrays after you know the value of rec:
int rec;
System.out.println("How many records do u want to enter:");
rec = in.nextInt();
std_id = new int[rec];
age = new int[rec];
etc.
And remove the initialization from the class variables at the top:
public class Input {
private int[] std_id;
private String[] name;
etc.
Get rid of the arrays. You don't need them.
Also, if you want rec number of records, don't loop from 0 to <= rec, because that would be rec + 1 records, so I changed loop to use < rec, which is the common way to do it.
Java naming convention is for field names to start with lowercase letter, so I renamed Students to students.
public class Input {
Scanner in = new Scanner(System.in);
private final List<Student> students = new ArrayList<Student>();
public Input()
{
initInput();
}
public void initInput()
{
System.out.println("How many records do u want to enter:");
int rec = in.nextInt();
for (int i = 0; i < rec; i++)
{
int std_id = in.nextInt();
String name = in.next();
int age = in.nextInt();
String email = in.next();
students.add(new Student(std_id, name, age, email));
}
}
}
One more solution:
class Input {
private Scanner in = new Scanner(System.in);
private List<Student> list = new ArrayList<>();
public Input() {
initInput();
}
public void initInput() {
int rec;
System.out.println("How many records do u want to enter:");
rec = in.nextInt();
for (int i = 0; i < rec; i++) {
Student student = new Student();
student.setId(in.nextInt());
student.setName(in.next());
student.setAge(in.nextInt());
student.setEmail(in.next());
list.add(student);
}
// this line to stop entering data
in.close();
// this one just to show the result
list.forEach(s -> System.out.println("Student ID " + s.getId() + ", name: " + s.getName()));
}
}
Comments:
Don't need to use array, take List instead!
In your for loop you need to use '<' not '<=' to prevent extra iteration
It's quite enough to use one for loop to do everything
Related
Basically, I'm trying to ask the user's input and the input should store in two arrays using a single scanner. Using two would ask the user twice and that would be impractical. The code looks like this
int record = 0;
Scanner midOrFinal = new Scanner(System.in);
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
record = midOrFinal.nextInt();
int midterm[] = new int[8];
int grades[] = new int[8];
{
if ( record == 1 )
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 8; i++ )
{
System.out.println(subjects[i]);
System.out.print("Enter Grade: ");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length) )
System.out.println();
}
System.out.println("Enter Grade Successful");
}
If the user chooses option 1, the user will be given some subjects in an array (which I didn't include) and asked to input the grades. The input shall then proceed to the midterm OR finalterm array but I can't seem to do it by using one scanner.
If there are better ideas than my proposed idea, then please share. I'm still very new in Java and my first time using stackoverflow. Thanks!
Break out the grade collection into a new function, and pass along the array you want to collect the grades into.
public static void main(String[] args) throws IOException {
int gradeType = 0;
// Use a single scanner for all input
Scanner aScanner = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
gradeType = aScanner.nextInt();
String[] subjects = { "Subject A", "Subject B" };
int[] midtermGrades = new int[subjects.length];
int[] finalGrades = new int[subjects.length];
int[] gradesToCollect;
// Use gradesToCollect to reference the array you want to
// collect into.
//
// Alternatively, we could call collectGrades() in both the if/else
// condition
if (gradeType == 1) {
gradesToCollect = midtermGrades;
} else {
gradesToCollect = finalGrades;
}
collectGrades(subjects, gradesToCollect, aScanner);
System.out.println("\n\nThese are the collected grades");
System.out.println("Mid Final");
for (int i = 0; i < subjects.length; i++) {
System.out.format("%3d %3d\n", midtermGrades[i], finalGrades[i]);
}
}
// Collect a grade for each subject into the given grades array.
public static void collectGrades(final String[] subjects, final int[] grades, Scanner scn) {
System.out.format("Enter %s subjects and their corresponding grades:",
subjects.length);
System.out.println();
for (int i = 0; i < subjects.length; i++) {
System.out.format("Enter Grade for %s : ", subjects[i]);
grades[i] = scn.nextInt();
if (i == (subjects.length))
System.out.println();
}
System.out.println("Enter Grade Successful");
}
class Main {
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
in.useDelimiter("\r?\n");
Student student = new Student();
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
int record = in.nextInt();
if (record == 1) {
student.setTerm(TermType.MID);
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println("Enter Subject and grades space separated. Example - \nMaths 79");
System.out.println();
for (int i = 0; i < 8; i++) {
System.out.println("Enter Subject " + (i + 1) + " details");
String subjectAndGrade = in.next();
int index = subjectAndGrade.lastIndexOf(" ");
String subject = subjectAndGrade.substring(0, index);
int grade = Integer.parseInt(subjectAndGrade.substring(index + 1));
student.getSubjects().add(new Subject(grade, subject));
}
System.out.println("Enter Grade Successful");
System.out.println("========================================================");
System.out.println("Details: ");
System.out.println("Term Type " + student.getTerm());
for(int i = 0; i< student.getSubjects().size(); i++) {
System.out.println("Subject: " + student.getSubjects().get(i).getSubjectName() + ", Grade: " + student.getSubjects().get(i).getGradeScore());
}
}
}
}
class Student {
private List<Subject> subjects = new ArrayList<>();
private TermType term;
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public TermType getTerm() {
return term;
}
public void setTerm(TermType term) {
this.term = term;
}
}
class Subject {
private int gradeScore;
private String subjectName;
public Subject(int gradeScore, String subjectName) {
this.gradeScore = gradeScore;
this.subjectName = subjectName;
}
public double getGradeScore() {
return gradeScore;
}
public void setGradeScore(int gradeScore) {
this.gradeScore = gradeScore;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
}
scanners work by separating the input into a sequence of 'tokens' and 'delimiters'. Out of the box, 'one or more whitespace characters' is the delimiter.
The goal of this program is to declare three separate arrays and then write a function to display them in a tabular form. Here's my code:
import java.util.Scanner;
public class MultiDArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("How many rows?");
int length = input.nextInt();
int [] ID = new int[length];
for(int counter = 0; counter<length; counter++) {
System.out.println("Enter ID number "+(counter+1));
ID[counter] = input.nextInt();
}
Scanner scan = new Scanner(System.in);
System.out.println("How many names?");
int words = scan.nextInt();
String [] Name = new String[words];
for(int counter = 0; counter<words; counter++) {
System.out.println("Enter Name "+(counter+1));
Name[counter] = scan.next();
}
Scanner figure = new Scanner(System.in);
System.out.println("How many Salaries?");
int sal = figure.nextInt();
int []Salary = new int[sal];
for(int counter = 0; counter<sal; counter++) {
System.out.println("Enter Salary "+(counter+1));
Salary[counter] = figure.nextInt();
}
input.close();
scan.close();
figure.close();
System.out.println("ID"+" "+"Name"+" "+"Salary");
System.out.println("Content of Array: " + (display(ID, Name, Salary)));
}
public static String display(int x[], String y[], int z[]) {
for (int i = 0; i<x.length; i++) {
System.out.println(x[i]+" "+y[i]+" "+z[i]);
}
return null;
}
}
Which prints out my system input in this way:
ID Name Salary
1 JK 3000
2 MK 4000
3 CK 5000
null
However, what I would like to see instead is the same without the "null" part.
ID Name Salary
1 JK 3000
2 MK 4000
3 CK 5000
If I do not specify any return type, I get errors.
You are returning null and then concatenating it in your calling println statement
System.out.println("Content of Array: " + (display(ID, Name, Salary)));
You could do something like
System.out.print("Content of Array: ");
String ret = display(ID, Name, Salary);
If you are trying to write a method without a return type, use void. You shouldn't be concatenating a void return to a string though.
public static void display(int x[], String y[], int z[]) {
for (int i = 0; i<x.length; i++) {
System.out.println(x[i]+" "+y[i]+" "+z[i]);
}
}
I am new to Java and am wondering whats wrong with the code below. I am trying to create multiple objects as an array if this is possible? The code will run and ask for a name, however just end after this and im not sure why. Any help would be great, thanks in advance.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
ABug[] BugObj = new ABug[3]; //Creating object BugObj of class ABug
for (int i=1; i<4; i++){
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Name: " + BugObj[i].name); //Printing bug information out
System.out.println("Species: " + BugObj[i].species);
}
}
}
class ABug {
int horpos, vertpos, energy, id;
char symbol;
String species, name;
}
You have two issues:
You need to have an instance of the object you are going to use.
The way to manage a for loop.
You can modify your source code to this:
Scanner reader = new Scanner(System.in); // Take out this from inside for loop
for (int i = 0; i < BugObj.length; i++) { // Notice we use BugObj.length instead of a number and start index at 0.
System.out.println("Please enter the name of the bug:");
BugObj[i] = new ABug(); // You need to initialize the instance before use it
BugObj[i].name = reader.next();
You have to create objects to store the data first.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
ABug[] BugObj = new ABug[3]; //Creating object BugObj of class ABug
for (int i=1; i<4; i++){
BugObj[i] = new ABug(); // add this line
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Name: " + BugObj[i].name); //Printing bug information out
System.out.println("Species: " + BugObj[i].species);
}
}
}
class ABug {
int horpos, vertpos, energy, id;
char symbol;
String species, name;
}
Two errors :
initialize object before use : you cannot write BugObj[i].name before writing this BugObj[i] = new ABug();
array bounds, Java array begin at [0] but not [1], so use for (int i=0; i<3; i++) instead of for (int i=1; i<4; i++)
The final code :
public class test {
public static void main(String[] args) {
ABug[] BugObj = new ABug[3];
for (int i=0; i<3; i++){
Scanner reader = new Scanner(System.in);
BugObj[i] = new ABug();
System.out.println("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Name: " + BugObj[i].name); //Printing bug information out
System.out.println("Species: " + BugObj[i].species);
}
}
}
class ABug {
int horpos, vertpos, energy, id;
char symbol;
String species, name;
}
I'm having problems on how and where to put arrays.
I figured out how and where to put a loop so it will keep on gathering multiple user data that will be stored inside the arrays but I don't know where to put arrays. There will be an array for product numbers, an array for product name, and an array for price.
import java.io.*;
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static void main(String args[])throws Exception
{
int y = 0;
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code =
Integer.parseInt(a.readLine());
System.out.println("");
if(code==l)
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices")
System.out.print("Enter product number:
") ;
int prodnum
Integer.parseInt(a.readLine());
System.out.println("")
}
if(code==3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}}}}
First of all, where do you get this l (lowercase L) value in your for loop? Shouldn't this be 1 (number one)? Furthermore, it would be even better if it is 0 (zero) so you can use it as an index for your array.
Second thing, what's the point of int y = 0'? You are not using y anywhere in your program.
int y = 0;
for(int x = l; x <= 100; x++)
Change it to:
for(int x = 0; x < 100; x++)
Since you want to have 3 separate arrays, you should have 3 separate indexes to keep track of them.
Now let's see how to initialize an array to store the data. You should declare the size as a variable at the top of your class (or locally in your main()) to make it easier to change it later across your program. You can do the same with your array. Declare it inside your class or locally inside the main(). I will show you how to declare both outside of the class, but you should try it the other way too for practice.
Now remember, when using arrays you have to know the size of the array in advance as soon as you create it and you cannot change that size after. This means only that many elements can fit inside the array. If you want variable size structures, check out some of the answers with ArrayLists.
public class DataInsideArrays
{
public static DataInputStream a = new DataInputStream(System.in)
public static int size = 100; // now you only change this number and everything works
public static int[] productNumbers = new int[size];
public static String[] productNames = new String[size];
public static int[] productPrices = new int[size];
public static void main(String args[]) throws Exception
{
int prodnumIndex = 0; // index for tracking product numbers
int prodnameIndex = 0; // index for tracking product names
int prodpriceIndex = 0; // index for tracking product prices
for(int x = 0; x < size; x++)
{
// ... your code...
// ...
int prodNum = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodnumIndex < productNumbers.length) {
productNumbers [prodnumIndex] = prodnum;
prodnumIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
String prodName = a.readLine();
// check if we didn't reach our maximum size
if(prodnameIndex < productNames.length) {
productNames [prodnameIndex] = prodName ;
prodnameIndex++; // increment
} else {
System.out.println("Cannot add product name. Reached maximum amount.");
}
// ...
int prodPrice = Integer.parseInt(a.readLine());
// check if we didn't reach our maximum size
if(prodpriceIndex < productPrices.length) {
productPrices [prodpriceIndex] = prodPrice ;
prodpriceIndex++; // increment
} else {
System.out.println("Cannot add product number. Reached maximum amount.");
}
// ...
}
Another way you can achieve this is to create an object called Product that will contain the properties you need and then have an array of that object.
class Product {
int num;
String name;
int price;
Product(int num, String name, int price) {
this.num = num;
this.name = name;
this.price = price;
}
}
// ...
// declare your array of `Product` objects...
Product[] products = new Product[size];
// ...
// then you can do something like
System.out.println("Enter product number:");
int prodNum = Integer.parseInt(a.readLine());
System.out.println("Enter product name:");
String prodName = a.readLine();
System.out.println("Enter product price:");
int prodPrice = Integer.parseInt(a.readLine());
products[INDEX] = new Product(prodNum, prodName, prodPrice);
// ...
Also, consider using a double of a float for the product price since it is more realistic representation of actual products.
Do you have to use an array and "if" statements?
Common practice is to use a List as switch statement:
int[] productArray = new int[100];
List<Integer> productList = new ArrayList<Integer>();
for(int x=1;x<=100;x++) {
switch (code){
case 1:
productArray[x-1] = Integer.parseInt(a.readLine());
productList.add(new Integer(a.readLine()) );
break;
default:
System.out.println("Invalid")
break;
}
}
You should use a List instead of an array, because you don't know a priori the length for them.
A List allows you to dinamically add an element as soon as you got it, so you should "put the array" under the user input.
List<String> names = new ArrayList<String>(); //<-- do the same for price(Integer) and product number (Integer)
public static void main(String args[]) throws Exception) {
//...
if(code==1) //<-- This was a l, check again your code.
{
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
names.add(prodname); //<-- add value to ArrayList
System.out.print("Price: ");
int price = Integer.parselnt(a.readLine());
System.out.println("");
}
//...
}
To print the array content you just need to iterate over the ArrayList:
for(String prodname: names)
System.out.println(prodname); //<-- This will print all your product names
public class DataInsideArrays {
public static DataInputStream a = new DataInputStream(System.in);
List<String> productname=new ArrayList<String>();
public static void main(String args[]) throws Exception {
// rest of your code...
if(code == 1) {
System.out.print("") ;
System.out.print("Product number: ");
System.out.print("Product name: ");
String prodname = a.readLine();
System.out.print("Price: ");
int price = Integer.parseInt(a.readLine());
System.out.println("");
////////////////////////to store data place arraylist here/////////////////////////////
productname.add(prod);
///////////////////// //same way use arr to store price and product no
} else if(code == 2) {
System.out.println("Display List of Products-Prices") ;
System.out.print("Enter product number:") ;
int prodnum=Integer.parseInt(a.readLine());
System.out.println("");
}
if(code == 3) {
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
}
}
Here's the correct codes for the output I want. Maybe is there any other way I can get the same output of this with different coding?
import java.io.*;
import java.util.ArrayList;
public class DataArrays
{
public static DataInputStream a = new DataInputStream(System.in);
public static void main(String args[])throws Exception
{
ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
ArrayList<String> prodName = new ArrayList<String>(100);
ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
ArrayList<Integer> prodPay = new ArrayList<Integer>(100);
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code = Integer.parseInt(a.readLine());
System.out.println("");
int y = 1;
if(code==1)
{
System.out.print("") ;
System.out.println("Product number: "+ x);
prodNum.add(x); //this brings 1st input to array element #0 which is not needed
prodNum.add(x);
System.out.print("Product name: ");
String prodname = a.readLine();
prodName.add(prodname); //this brings 1st input to array element #0 which is not needed
prodName.add(prodname);
System.out.print("Price: ");
int prodprice = Integer.parseInt(a.readLine());
prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed
prodPrice.add(prodprice);
System.out.print("Payment: ");
int prodpay = Integer.parseInt(a.readLine());
prodPay.add(prodpay); //this brings 1st input to array element #0 which is not needed
prodPay.add(prodpay);
System.out.println("");
System.out.println("Start New Transaction:");
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices");
System.out.print("Enter product number: ");
int i = Integer.parseInt(a.readLine());
i = prodNum.get(i); //this gets the data stored in the arraylist. Assuming it starts with 1 and above
prodNum.set(1, i);
System.out.println("");
System.out.println("Product name: "+ prodName.get(i));
System.out.println("Product price: "+ prodPrice.get(i));
System.out.println("Product payment: "+ prodPay.get(i));
System.out.println("");
System.out.println("Start New Transaction:");
}
else if(code>=3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
else if(code==0)
{
System.out.println("Program will end");
break;
}}}}
Thank for helping me guys. Really appreciated it.
I'm attempting to save an x amount of integers inside of an object class. I'm trying it via an array but am not sure if this is possible and as of now eclipse is giving me two errors. One asking me to insert an Assignment operator inside of my Gerbil() class and another saying that I can't make a static reference to to the non-static field food. The result I'm looking for is food 1 = first input; food 2 = second input; until it hits the total amount of food.
Here's my code so far:
import java.util.Scanner;
public class Gerbil {
public String name;
public String id;
public String bite;
public String escape;
public int[] food;
public Gerbil() {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
this.food[]; // I'm not sure what I should put here. This is where I want to store
} // the different integers I get from the for loop based on the
// total number of foods entered. So if totalFoods is 3, there should
// be 3 integers saved inside of the object class based on what's typed
// inside of the for-loop. Or if totalFoods = 5, then 5 integers.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many foods?");
int totalFood = keyboard.nextInt();
System.out.println("How many gerbils in the lab?");
int numberOfGerbils = keyboard.nextInt();
Gerbil[] GerbilArray = new Gerbil[numberOfGerbils];
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil();
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
food[j] = keyboard.nextInt();
}
}
}
}
You need to pass the number of food in the Gerbil constructor :
public Gerbil(int totalFood) {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
this.food[] = new int[totalFood];
}
And then in the loop will look like this :
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil(totalOfFood);
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
GerbilArray[i].food[j] = keyboard.nextInt();
}
}
Or something like that should do it.