How do u write to a next array index by modifying this code? I'm a noob at java. for e.g, I am calling this method from my main method, so the first time it is run, it writes to index 1 of the array. the second time it is run, it writes to index 2 of the array. however, I do not want it to loop. I have also not learnt arraylists' yet so its out of the picture unfortunately.
public class staffName {
public static void staffDetails(){
String[] staffname= new String[20];
int i=0;
staffname[i]=JOptionPane.showInputDialog(null,"Please enter staff name:")
i++;
}
You are setting variable i everytime you call a function to 0. So you only change element 0 all the time. You need to put variable i outside a function and make it static so it increments when you call the function and stays incremented.
You also must put array staffname outside, otherwise, you make new empty array everytime you call a function.
public class staffName {
public static int i = 0;
public static String[] staffname= new String[20];
public static void staffDetails(){
staffname[i] = JOptionPane.showInputDialog(null,"Please enter staff name:");
i++;
}
Define the Array only once in the main and do it like this:
public class staffName {
private static int i = 0;
String[] staffname= new String[20];
public static void staffDetails(String[] array){
array[i] = JOptionPane.showInputDialog(null,"Please enter staff name:")
i++;
}
}
calling this method from my main method, so the first time it is run, it writes to index 1 of the array. the second time it is run, it writes to index 2 of the array.
Problem is both array and index loses its scope once the method staffDetails() does its job.
Option 1: Consider sending array and index as parameter
public static void staffDetails(final String[]staffname, final int i){
staffname[i] = JOptionPane.showInputDialog(null,"Please enter staff name:");
}
public static void main(String[]args){
final String[]staffname=new String[20];
int i = 0;
staffDetails(staffname,i++);
staffDetails(staffname,i++);
}
Option 2: Make array and index as class/static members
public static void staffDetails(){
staffname[i++] = JOptionPane.showInputDialog(null,"Please enter staff name:");
}
public static void main(String[]args){
staffDetails();
staffDetails();
}
private static final String[]staffname=new String[20];
private static int i = 0;
Related
I am a beginner in Java and I've been stuck on this for three days. I have two classes. Class called Main has the main method and asks for user input and class called DoThings does things with the user input.
I want the main class to ask the user for a number. The doThings class will take this number, multiply it by 4 and set it as the length of a 1D array. Then print the length of the array.
public class Main {
public static void main(String[] args) {
//Create object called Exercise to perform the task
DoThings Exercise = new DoThings();
Scanner scanner = new Scanner(System.in);
//Ask user for a number
System.out.print("Please enter a number: ");
//Number is passed to the setNumber setter method in DoThings class
Exercise.setNumber(scanner.nextInt());
//Getter method is used to pass number to the setMultiplyFour setter method in DoThings class
Exercise.setMultiplyFour(Exercise.getNumber());
//Print out the length of the array
System.out.println(Exercise.array.length);
}
}
This is the second class.
public class DoThings {
private int number;
private int multiplyFour;
//Created array with the length as multiplyFour
char[] array = new char[this.multiplyFour];
//Setters
public void setNumber(int number) {
this.number = number;
}
public void setMultiplyFour(int number) {
this.multiplyFour = number * 4;
}
//Getters
public int getNumber() {
return this.number;
}
public int getMultiplyFour() {
return this.multiplyFour;
}
}
But when I print the result, it's coming as 0? Why is this?
Thank you!!
When char[] array = new char[this.multiplyFour]; this code is executed, the value of this.multiplyFour is 0 (ints have a default value of 0 in Java). When you update this.multiplyFour, its value change but the array doesn't magically gets re-allocated. You have to re-allocate your array manually, when you update this.multiplyFour.
public void setMultiplyFour(int number) {
this.multiplyFour = number * 4;
this.array = new char[this.multiplyFour];
}
I have my example code below. I'm trying to convert the gradeString into gradeInt and I can't seem to do it properly. When I print the value of gradeInt at the end using toString.
It says a blank array which is like this one: [ ]
Thanks for the help!
import java.util.*;
class testing{
public static Scanner console = new Scanner(System.in);
public static int studSize;
public static String [] gradeArr = new String[studSize];
public static int [] gradeInt = new int[gradeArr.length];
public static void initialize(){
System.out.print("Please enter student size: ");
String studString = console.nextLine();
studSize = Integer.parseInt(studString);
enterData();
}
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
convert();
}
public static void convert(){
for(int i=0; i<gradeInt.length; i++){
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
print();
}
public static void print(){
System.out.print(Arrays.toString(gradeArr));
System.out.print(Arrays.toString(gradeInt));
}
public static void main(String [] args){
initialize();
//Main and Class Closing Braces
}
}
Add this line just before your call to convert for the "quick fix":
gradeInt = new int[gradeArr.length];
Try this. The problem is that you are assigning sizes of arrays etc before any data is entered. Actually the usuage of studSize is not needed at all - see comments in code
public static Scanner console = new Scanner(System.in);
public static int studSize;
public static String [] gradeArr;
public static int [] gradeInt;
public static void initialize(){
// not needed -
System.out.print("Please enter student size: ");
String studString = console.nextLine();
// not needed
studSize = Integer.parseInt(studString);
enterData();
}
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
convert();
}
public static void convert(){
// set here as the size is know
gradeInt = new int[gradeArr.length];
for(int i=0; i<gradeArr.length; i++){
// should be carefull of NumberFormatException
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
print();
}
public static void print(){
System.out.print(Arrays.toString(gradeInt));
}
public static void main(String [] args){
initialize();
//Main and Class Closing Braces
}
I ran your code and it works
Output:
[95, 85, 75]
Process finished with exit code 0
I suspect there may be an error in other parts of your code if you're getting a empty array.
What's the context you're running the code in? If you paste the rest of the code it might help finding the real source of the error.
SOLUTION:
Like Andy mentioned. The root error is contained here:
public static int [] gradeInt = new int[gradeArr.length];
You're defining this variable at runtime and assigning it the same length as gradeArr which is 0 at the time.
This results in a logic error that happens in the convert() method.
for(int i=0; i<gradeInt.length; i++){
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
You are telling the code to loop if i was smaller than gradeInt which has a length of 0. Basically it never loops. It just skips the loop entirely.
The quickest way to fix this is to modify the code like this:
Don't assign a length to the gradeInt variable at runtime. Modify the line to this:
public static int [] gradeInt;
And then modify your enterData() method to this:
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
gradeInt = new int[gradeArr.length];
convert();
}
I am practising dynamic coding so I want to create a list for class. I hereby Initialized a list for class and want to create an array with different length for each iteration in list. But It doesnt initialize it like I expected instead its length says 0.
import java.io.*;
import java.util.*;
class testcase
{
int N;
int play []= new int [N];
int villain[]=new int [N];
String status;
}
public class Main {
public static void main(String args[] ) throws Exception {
List<testcase> caseno=new ArrayList<testcase>();
Scanner sc=new Scanner(System.in);
int n1=1;
//int n1=sc.nextInt();
int i,j;
testcase t;
for(i=0;i<n1;i++)
{
int n=6;
//int n=sc.nextInt();
t=new testcase();
t.N=n;
System.out.println(t.N+" "+t.play.length);
}
}
}
The array length should print 6 instead it shows 0
You have to create a parametrized constructor in which you'll pass the value of N and then initilaze the arrays. Like
class testcase // Name should be in PASCAL
{
int N;
int [] play;
int [] villain;
String status;
public testcase (int n) { // Constructor
this.N=n;
play = new int [N];
villain=new int [N];
}
}
And in the main methos you create object like this
int n= . . .;//taking input from user
testcase t=new testcase(n);
You need to write a constructor which does these assignment based on the value passed.
// Implement your constructor something like this
public Testcase(int value) {
this.N = value;
play = new int [value];
// Some more assignment based on the need
}
And after that, you need to create the object instance
int N = 6;
Testcase newTestcase = Testcase(N);
NOTE: Clase name should always start with a capital letter.
Try declaring these variable like N, status, play e.t.c as private. After that assign and access them using getter() and setter().
I have two classes that basically function as the most simplest database, where the user is supposed to enter a string and the program adds it in the array using a class that holds all the methods. Except that when i enter the first name it gives me java.lang.ArrayIndexOutOfBoundsException: 0. I know this means that no memory is being allocated for the array but i thought i did this in my second class where there is a constructer that defines the size of the array. Im not experienced enough with arrays to fix this debug on my own. Much help would be appreicated!
import java.util.*;
public class TestDatabase {
//contant value for data base 'size' of array
public static final int constant = 10;
public static void main (String[] args){
//Database object sets the array size to constant value
Database get = new Database(constant);
//input stream
Scanner in = new Scanner (System.in);
//varaibles for the count and index; prompt
int count = 0;
int index = 0;
System.out.println("Please enter 10 names to add them to the database. Name: " + (count += 1));
//while the count is lower than or equal to 10...
while(count<=10){
//input stream equal to input
String input = in.nextLine();
//if the count equals, stop the loop
if (count == 10)
{
//breaks the loop
break;
}
//prints out the current name
System.out.print(" Name: " + (count +=1));
//adds the input to the array
get.add(index,input);
//increments index by 1
index++;
}
//prints the array
get.print();
}
}
Here is my class with my all my methods:
import java.util.*;
public class Database{
//size of array
public int _size;
//array which has a varaible size
String[] userArray = new String[_size];
//contructer for the array size
public Database(int size){
_size = size;
}
//add method which adds a value to an index of an array
public void add(int index, String name){
//the values of string is placed into some index of the array
userArray[index] = name;
}
//print method which prints the contents of the array
public void print(){
//prints array
System.out.println(Arrays.toString(userArray));
}
//sort method which sorts the array
public void sort(){
//sorts the array
Arrays.sort(userArray);
}
//find method which finds a particular string in any index
public void find(String value){
Arrays.asList(userArray).contains(value);
}
}
Your ArrayList is never instantiated properly, you need to move it into your constructor so when the new operator is called, then the arraylist is created with the size variable that is passed, so something like this:
public Database {
private String[] data;
public Database(int size){
this.data = new String[size];
}
}
With your current code, the array is created before the size is actually given, so it defaults to a size of 0.
userArray init with zero length before your constuctor set _size. Create userArray in constructor.
there next steps performed when you create class:
_size init with 0
userArray init with zero length array
_size init with size value.
Change the code as below
String[] userArray;
public Database(int size){
_size = size;
userArray = new String[_size];
}
I have one class called DVD collection and another one called movies. The method with the array that I'm trying to return looks like this:
public class DVDCollection
{
public static DVD[] collection;
public static void searchForDVD( String DVD[], String a) {
System.out.println("What DVD would you like to search for?");
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
int N = DVD.length;
for (int i = 1; i < N; i++)
for (int j = i; j > 0; j--)
if (DVD[j-1].compareTo(DVD[j]) > 0)
change(DVD, j, j-1);
else break;
for (int i = 0; i < DVD.length; i++) {
System.out.print(DVD[i] + a);
}
System.out.println();
}
}
And I'm trying to call it from my main method like so:
public class Movies
{
public static void main (String[] args)
{
DVDCollection movies = new DVDCollection();
movies.searchForDVD(DVD);
}
}
But it gives me an error saying cannot find symbol - variable DVD
So what exactly is the problem here?
You're calling
movies.searchForDVD(DVD);
but there is no DVD variable defined in the main method. And BTW, even if there was one, the searchForDVD() method takes two arguments, and not just one.
Also note that the searchForDVD() method is static. So you don't need any instance of DVDCollection to call it. Instead of
DVDCollection movies = new DVDCollection();
movies.searchForDVD(...);
you should use
DVDCollection.searchForDVD(...);
In your main method when calling the searchForDVD method you must pass it an array of strings for the dvds along with the name of the dvd as a string.
At the moment you are passing the variable DVD which you have not declared anywhere in the main method.
Code in main method should be:
String[] dvds = new String[] {"firstDVD","secondDVD","thirdDVD");
String movie = "secondDVD";
DVDCollection.searchForDVD(dvds,movie);
problem 1
movies.searchForDVD(DVD);
the parameter DVD is not defined.
problem 2
public static void searchForDVD(...) is a static method of class DVDCollection you should call it DVDCollection.searchForDVD(...) you don't need the movie object.
You are calling DVD several times in this code. I believe the mistake here is the variable name.
You have defined public static DVD[] collection; which is an array of DVD objects called collection. The variable name is collection and that is what you need to use when referencing the variable.
ie: collection.length instead of DVD.length.
When you say public static DVD[] collection;, you are telling the compiler to create you a public, static Array of DVD objects called collection. At some point this array would need to be initialized. Arrays are initialized in the following format:
DVD[] collection = new DVD[];
or
String[] arrayOfStrings = {"a","b","c","d"};
Another problem is that your method is defined as follows:
public static void searchForDVD( String DVD[], String a)
This method is requiring two arguments, not one. If you are trying to require a String[] array called "DVD" then you should declare as follows:
public static void searchForDVD( String[] DVD, String a)
That declaration says this method takes an array of strings and we'll call it DVD and another String which will be called a.
Make sure to note what your variable type is and what your variable name is.
The type tells java what to expect in the variable, the name is how you access it.
String myString = "string data";
String is the type. myString is the variable name. "string data" is the value assigned to the variable.
What makes sense to me is something like:
public class Movies
{
public static void main (String[] args)
{
DVDCollection movies = new DVDCollection();
//create an Add function inside DVDCollection which reads lines from a text file into collection
movies.Add("list_of_movies.txt");
// no arguments are needed here imo, just have it print to user to ask for a DVD to search and then search the collection
movies.searchForDVD();
}
}
public class DVDCollection
{
public DVD[] collection;
public void Add(string file)
{
// parse file and add contents to collection
}
public void searchForDVD()
{
System.out.println("What DVD would you like to search for?");
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
int N = DVD.length;
for (int i = 1; i < N; i++)
for (int j = i; j > 0; j--)
if (DVD[j-1].compareTo(DVD[j]) > 0)
change(DVD, j, j-1);
else break;
for (int i = 0; i < DVD.length; i++)
{
System.out.print(DVD[i] + a);
}
System.out.println();
}
}