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.
Related
I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:
anyone could help, thx!
here is my code
Scanner sc = new Scanner(System.in);
int i = 0;
String classname = " ";
String rating = " ";
int plus = 0;
while(i < 3){
System.out.print("What class are you rating? ");
classname = sc.nextLine();
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus = Integer.parseInt(rating);
i++;
}
System.out.print(classname + ": ");
while (plus > 0){
System.out.print("+");
plus --;
}
System.out.println();
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,
public class Course {
private String name;
private int rating;
public Course(String name, int rating) {
this.name = name;
this.rating = rating;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rating; i++) {
sb.append("+");
}
return String.format("%s: %s", name, sb);
}
}
Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,
Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
System.out.print("What class are you rating? ");
String className = sc.nextLine();
System.out.printf("How many plus signs does %s get? ", className);
int classRating = Integer.parseInt(sc.nextLine());
courses[i] = new Course(className, classRating);
i++;
}
i = 0;
while (i < courses.length) {
System.out.println(courses[i]);
i++;
}
You overwrite your variables classname and rating in each loop. You need to store each iteration in a field of an array.
Scanner sc = new Scanner(System.in);
int i = 0;
String[] classname = new String[3]; //create array
String rating = " "; //rating can be overwritten, it is not needed after the loop
int[] plus = new int[3];
while(i < 3){
System.out.print("What class are you rating? ");
classname[i] = sc.nextLine(); //name[index] to read/write fields of an array
//index starts at 0
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus[i] = Integer.parseInt(rating);
i++;
}
for(i = 0;i<3;i++){ //iterate over all elements in the array
System.out.print(classname[i] + ": ");
while (plus[i] > 0){
System.out.print("+");
plus[i] --;
}
System.out.println();
}
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]);
}
}
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
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.
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;
}