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;
}
Related
Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}
I'm quite new to Java and I've been asked to create a program in which the user is able to input two values and store them in separate arrays. The two values I'm asking the user are name and cell number, then I must allow the user to search by typing either a name or a cell number and return the corresponding name or cell number. I made it possible to input the values and search within them by number but when I try searching by name I get this error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "B"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
This is my code:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int i, x = 2;
static String names[] = new String[x];
static int numbers[] = new int[x];
public static void main(String[] args) {
Input();
Compare();
}
public static void Input() {
System.out.println("Enter a name followed by the persons number");
while (i < x) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.nextInt();
i++;
}
}
public static void Compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
var temp = sc.next();
System.out.println("NAME\tNUMBER");
for (i = 0; i < numbers.length; i++)
if ((names[i].equals(temp)) || (numbers[i] == Integer.parseInt(temp.trim()))) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
}
Thanks! :)
Looking at your problem statement it doesn't seem like you need to do any additional processing on numbers. Hence, even if you store the number as a string it should be fine in this case.
Hence after getting a user search criteria, you could do a simple string search within both arrays.
Hope this helps :)
First of all, the highest number that can be represented as an int in Java is 2147483647 (214-748-3647). This clearly will not be able to hold a high enough number to accommodate any phone number. To address this issue and also fix your main error, I would suggest storing the numbers as a string instead. Here's my solution:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int x = 2;
static String names[] = new String[x];
static String numbers[] = new String[x];
public static void main(String[] args) {
input();
compare();
}
public static void input() {
System.out.println("Enter a name followed by the persons number");
for (int i = 0; i < x; i++) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.next();
i++;
}
}
public static void compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
String temp = sc.next();
System.out.println("NAME\tNUMBER");
for (int i = 0; i < numbers.length; i++) {
if ((names[i].equals(temp)) || numbers[i].equals(temp)) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
System.out.println("===END OF SEARCH====")
}
}
Please also note that I un-defined your variable i. As far as I can see there's no reason for you to be defining it. Hope this helps, good luck!
I need to allow the user to input any number of students. They press "C" to end data entry. I was thinking to make a student class (my code does not currently represent that) and 4 objects per student. Each set of 4 objects are the number grades that will be summed up and averaged.
I've already tried using a while loop, making arrayLists, and I've looked into maps. Each set of 4 grades corresponds to a student and must be summed and averaged separately.
package arrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> studentName = new ArrayList<String>();
ArrayList<Double> studentGrade = new ArrayList<Double>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String student = scanner.nextLine();
if(student.equals("C"))
{
break;
}
else
{
studentName.add(student);
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++) {
Double grade = Double.parseDouble(scanner.nextLine());
studentGrade.add(grade);
}
System.out.println(studentName);
System.out.print(studentGrade);
}
}
}
Problem here really is that I have all the entered numbers in one arrayList and I don't know if I can automatically create a new arrayList each time they enter a new student. Each arrayList would ideally hold just 4 double values.
Well please consider that grades are related to student and limited to always 4.
Therefore I suggest to implement a dynamic list of a class student with enclosed array of grades.
Example:
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> studlist = new ArrayList<Student>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String scanedline = scanner.nextLine();
if(scanedline.equals("C"))
{
break;
}
else
{
studlist.add(new Student(scanedline));
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++)
{
System.out.print(""+j+">");
Double scannedgrade = Double.parseDouble(scanner.nextLine());
studlist.get(studlist.size() - 1).grade[j]=scannedgrade;
}
System.out.println(studlist.get(studlist.size() - 1).name);
for (int j = 0; j < 4; j++)
System.out.print(studlist.get(studlist.size() - 1).grade[j] + " ");
System.out.println("");
}
}
private static class Student
{
String name;
Double [] grade;
Student (String s)
{
this.name = s;
grade = new Double[4];
}
}
}
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
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.