Set Method And Get Method Of A Fixed Size Array - java

I'm a bit mixed up on how to apply the 'sets' and 'gets' methods for a fixed array. Here is some of my work in Netbeans:
//creating 5 fixed arrays of size 10
private String [] itemnames = new String [10];
private String [] itemcodes = new String [10];
private String [] category = new String [10];
private String [] quantity = new String [10];
private Double [] sellingprice = new Double [10];
//initialising each array to null in the class constructor
for (int i = 0; i < 10; i++){
itemnames[i] = "";
}
for (int i = 0; i < 10; i++){
itemcodes[i] = "";
}
for (int i = 0; i < 10; i++){
category[i] = "";
}
for (int i = 0; i < 10; i++){
quantity[i] = "";
}
for (int i = 0; i < 10; i++){
(Double.parseDouble(sellingprice[i])) = 0;
}
Now, i'm stuck in the set method and the get method of each array. Any help please?
Thanks :)

You make set and get methods according to what you want to do (or later be able to do) with the arrays.
If you want to be able to retrieve an array into another class, you could make a get method like this:
public String[] getItems()
{
return itemnames;
}
If on the other hand you only want other classes to get the specific items in your arrays, one method might look like this:
public String getItemMatchingCode(String code)
{
for(int i = 0; i < ARR_LENGTH; i++)
{
if(code.equals(itemcodes[i]) return itemnames[i];
}
}
Or you might want to set and get the different values based on ideces:
public String getItemnameAt(int i)
{
return itemnames[i];
}
public void setItemnameAt(int i, String newItemname)
{
itemnames[i] = newItemname;
}
Sidenotes:
You are not "//initialising each array to null in the class constructor", they are that by default. What you are doing is filling them with empty strings, which in most cases is unnecessary.
When iterating through the arrays and filling them with values you can do them all in one loop.
for (int i = 0; i < 10; i++)
{
itemnames[i] = "";
itemcodes[i] = "";
category[i] = "";
}
Edit:
Also consider using a constant when declaring the size of the arrays, like so:
private static final int ARR_SIZE = 10;
private String[] array = new String[ARR_SIZE];

Related

Java - Problem at sorting array list using bubblesort

I have a problem at the moment I have a college assignment and we need to list a file that contain books and should be sorted A to Z,
My sort algorithm is a bubble sort and at the moment is not sorting alphabetically but don't give errors, I cant see where I should change to make it work as the coding seems correct to me.
We are not allowed to use collections so that is the reason I am not using sort().
package Book;
public class AlphabeticalOrderTitle{
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
public static void main(String[] args)
{
ArrayList<Book> books = BubbleSort();
System.out.println(linearSearch(books));
}
public static ArrayList<Book> loadData() {
//Creating an array list;
ArrayList<Book> books = new ArrayList<>();
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.txt"));
//This header string will allow to skip the header so does not mismatch with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
return books;
}
public static int linearSearch(ArrayList<Book> array){
//Variables for holding values
int n;
String temp;
// Going one by one the elements in the array
for(int g = 0; g < array.size(); g++){
//Getting the array size from the file and giving the array name a size
n = array.size();
String names[] = new String[n];
//Load all the names
for(int i = 0; i < n; i++) {
names[i] = array.get(g).getBookTitle();
}
//Bubble sort starts
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
//Print sorted
System.out.println(names[n-1]);
}
return -1;
}
}
Outpout:
Captains
Romeo
Don
-1
and what I am aiming is Captains, Don, Romeo.
My book.txt contains is like this:
book
Any suggestion for me to fix it ? Thank you very much.
Bubble Sort Example
I linked a bubble sort example. You can click on Java to see a version in Java. And you can see there are differences between yours and theirs, even though they are very similar.
What I would do is do it manually. That is, grab some paper, write down what your array looks like then actually pretend you're the computer and see what you end up with. It will be a good exercise for you, and you'll probably figure out what you're doing wrong.
First of all, BubbleSort() is not an appropriate name for this method as all it does is reading the file and storing the content inside the list.
If this course is not an upper-level algorithms class, you could probably use java libraries to sort your list instead.
Something like this should work and produce the needed result:
Collections.sort(books);
Also, I usually just do the following:
List books = new ArrayList<>();
In case you have to implement bubble sort, please use the following link which shows how to use bubble sort to sort string arrays: https://www.geeksforgeeks.org/sorting-strings-using-bubble-sort-2/
For array A of 'n' elements A[n], then the first loop in bubble sort always ends with n-1.
The idea of bubble sort is to compare the adjacent elements and then swap if the are not in order (increasing / decreasing depending on the use case).
So, when i=n-1, as you mentioned in your first for loop=>j=n-1. We are basically comparing A[i=n-1] to A[j=n-1].
//Bubble sort starts
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
you can try a quick dry-run whenever you are stuck in such problems by substituting with small numbers and writing the loop content on paper. Helps a lot to learn and to build logic. :)
So after a couple days working on it I have come with a working solution thanks to everyone.
public class Alphabetical_Order {
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
//Creating an array list;
public static ArrayList<Book> books = new ArrayList<>();
public static void main(String[] args)
{
loadData();
int n = 0;
String temp;
//Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
//get size of arraylist
for (int g = 0; g < books.size(); g ++) {
n = books.size();
}
String names[] = new String[n];
//Names to be get from user
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = books.get(i).getAuthorName();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
public static void loadData() {
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.csv"));
//This header string will allow to store the header so does not mistach with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
}}

Trouble trying to find a word in a String array

For the code, it wakes a user input and splits it by witespaces then takes the individual words from the user input and checks to see if the singular word is in the text file( containing parallel arrays with one being a string array and the other an int array). For every time it finds the user inputted word it needs to add one but the problem is that I don't know how to implement either match, or compare or equalsTo to check to see if the word is in the String array.
public class MovieReviewSentimentAnalysis {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// TODO: complete me
//make own arrays to pass by value
//movieReviewComments = the text
String[] movieReviewComments = new String[10000];
//movieReviewScores = numeric values, avoid lit. values
int[] movieReviewScores = new int[10000];
String userComment = "";
// String reviewFile = "";
// reviewFile = args[0];
String whiteComment = "";
MovieReviewReader.readMovieReviews("movie_reviews.txt", movieReviewComments, movieReviewScores); //string, string array, and int array
System.out.println("Please type one line of review and when you are done press either Ctr D or Ctr Z");
userComment = userInput.nextLine();
System.out.println(userComment);
String[] words2 = userComment.split("[\\W]");
double itemCount = 0;
double wordTotal = 0;
double totalSumOfUserCommentWords = 0;
String test = "";
// int itemCount = words.length;
for (int i = 0; i < words2.length; i++)
{
test = words2[i];
itemCount = wordCount(test, movieReviewComments, movieReviewScores);
wordTotal += itemCount;
totalSumOfUserCommentWords = wordTotal / userComment.length();
// System.out.println(totalSumOfUserCommentWords);
}
// System.out.println(reviewFile);
System.out.println("Incomplete assignment");
userInput.close();
}
public static double wordCount(String test, String[] movieReviewComments, int[] movieReviewScores)
{
double storeScore = 0;
double totalSumofReviewScores = 0;
double numOfTimesWordAppears = 0;
for (int i=0; i < (movieReviewComments.length); i++)
{
if (test.equals(movieReviewComments[i])) //////////////////////////////////////////////////////////SOMETHING'S OFF
{
storeScore = movieReviewScores[i];
totalSumofReviewScores += storeScore;
numOfTimesWordAppears++;
System.out.println("Found"); //QUQ when will you appear!?!?
}
else
System.out.println("You dun goofed"); //delete after fixing problem
}
double wordScoreAverage = totalSumofReviewScores / numOfTimesWordAppears;
return wordScoreAverage;
}
It is very simple. You can do it the following way:
if (movieReviewComments[i].toLowerCase().contains(test.toLowerCase())
And if you want to test an equal comparison and not containment, use following instead:
if (test.equalsIgnoreCase(movieReviewComments[i])

null pointer exception string builder

I am trying to use the setCharAt method in a StringBuilder but I am getting a null pointer exception. Is there a way I can add values to the StringBuilder array I have made so I wont get these error.
From research I have found the .append() method but I'm not even sure how it works.
import java.util.*; // Allows for the input of a scanner method.
import java.io.*; // Allows for the inputting and outputting of a data file.
import java.lang.*; // Allows for the use of String Methods.
//////////////////////////////////////////////////////////////////////////////////////
public class TESTY
{
static Scanner testanswers;
static PrintWriter testresults;
public static void main(String[] args) throws IOException
{
testanswers = new Scanner(new FileReader("TestInput.dat"));
testresults = new PrintWriter("TestOutput.dat");
String StudentID;
String answers;
// Reads first two lines first to know how many records there are.
String answerKey = testanswers.nextLine();
int count = Integer.parseInt(testanswers.nextLine());
// Allocate the array for the size needed.
String[][] answerArray = new String[count][];
for (int i = 0; i < count; i++)
{
String line = testanswers.nextLine();
answerArray[i] = line.split(" ", 2);
}
for(int row = 0; row < answerArray.length; row++)
{
for(int col = 0; col < answerArray[row].length; col++)
{
System.out.print(answerArray[row][col] + " ");
}
System.out.println();
}
gradeData(answerArray, answerKey);
testanswers.close();
testresults.close();
}
///////////////////////////////////////////////////////////
//Method: gradeData
//Description: This method will grade testanswers showing
//what was missed, skipped, letter grade, and percentage.
///////////////////////////////////////////////////////////
public static double gradeData(String[][] answerArray, String answerKey)
{
String key = answerKey;
double Points = 0;
StringBuilder[] wrongAnswers = new StringBuilder[5];
String studAnswers;
for(int rowIndex = 0; rowIndex < answerArray.length; rowIndex++) /// Counting rows
{
studAnswers = answerArray[rowIndex][1].replace(" ", "S"); ///Counts rows, Col stay static index 1
for(int charIndex = 0; charIndex < studAnswers.length(); charIndex++)
{
if(studAnswers.charAt(charIndex) == key.charAt(charIndex))
{
Points += 2;
}
else if(studAnswers.charAt(charIndex) == 'S')
{
Points --;
}
else if(studAnswers.charAt(charIndex) != key.charAt(charIndex))
{
for(int i = 0; i < wrongAnswers.length; i++)
{
wrongAnswers[i].setCharAt(charIndex, 'X');
}
Points -= 2;
}
}
System.out.println(Points);
}
return Points;
}
}
The error is occurring on line 91 :
wrongAnswers[i].setCharAt(charIndex, 'X');
You have declared an array of StringBuilders, but you haven't initialized any of the slots, so they're still null.
Initialize them:
StringBuilder[] wrongAnswers = new StringBuilder[5];
for (int i = 0; i < wrongAnswers.length; i++)
{
wrongAnswers[i] = new StringBuilder();
}
Additionally, using setCharAt won't work here, because initially, there is nothing in the StringBuilder. Depending on what you want here, you may need to just call append, or you may initially want a string full of spaces so that you can set a specific character to 'X'.
StringBuilder[] wrongAnswers = new StringBuilder[5];
does not create 5 empty StringBuilders but 5 null StringBuilders.
You need to call something like
wrongAnswers[i] = new StringBuilder()
in order to initialize your 5 array members.
Your problem is that
StringBuilder[] wrongAnswers = new StringBuilder[5];
does not create 5 StringBuilder objects. It only creates an array with 5 null StringBuilder references. You need to create each StringBuilder separately with a line such as
wrongAnswers[i] = new StringBuilder();
inside a loop over i.

How to convert a char array to an int array?

Say I am using this code to convert a String (containing numbers) to an array of characters, which I want to convert to an array of numbers (int).
(Then I want to do this for another string of numbers, and add the two int arrays to give another int array of their addition.)
What should I do?
import java.util.Scanner;
public class stringHundredDigitArray {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
String num1 = in.nextLine();
char[] num1CharArray = num1.toCharArray();
//for (int i = 0; i < num1CharArray.length; i++){
//System.out.print(" "+num1CharArray[i]);
//}
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = num1CharArray[i];
}
for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
System.out.print(" "+num1intarray[i]);
}
}
}
I really have to split the string, to preferably an array of additionable data types.
try Character.getNumericValue(char); this:
for (int i = 0; i < num1CharArray.length; i++){
num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}
Try This :
int[] num1intarray = new int[num1CharArray.length];
for (int i = 0; i < num1CharArray.length; i++)
{
num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
System.out.print(num1intarray[i]);
}
Short and simple solution!
int[] result = new int[charArray.length];
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i]));

rotating string array in java

How would i rotate a string array in java for a tetris game i am making. For example, the string array
[
"JJJJ",
"KKKK",
"UUUU"
]
would become
[
"UKJ",
"UKJ",
"UKJ",
"UKJ"
]
I can do it with a char matrix using this code
public char[][] rotate(char[][] toRotate)
{
char[][] returnChar = new char[toRotate[0].length][toRotate.length];
for(int rows = 0; rows<toRotate.length; rows++)
{
for(int cols = 0; cols<toRotate[0].length; cols++)
{
returnChar[cols][toRotate.length-1-rows]=toRotate[rows][cols];
}
}
return returnChar;
}
With the Array String is similar to want you have done:
public static String[] rotate(String [] toRotate)
{
String [] returnChar = new String[toRotate[0].length()];
String [] result = new String[toRotate[0].length()];
Arrays.fill(returnChar, "");
for(int rows = 0; rows<toRotate.length; rows++)
for(int cols = 0 ; cols < toRotate[rows].length(); cols++)
returnChar[cols] = returnChar[cols] + toRotate[rows].charAt(cols);
for(int i = 0; i < returnChar.length; i++)
result[i] = new StringBuffer(returnChar[i]).reverse().toString();
return result;
}
I go through all char in each String on array toRotate, concat this char (toRotate[rows].charAt(cols)) to each String returnChar[cols] on the array returnChar
Strings are immutable in Java, so you have a few options
Write a wrapper for rotate(char [][]) that turns it back into a string array
Modify the function to create a new array of strings from the input
Create a data structure that holds the data in the most efficient format and then has getters that return it in the format you want it.
3 is essentially what you 'should' be doing. In a Tetris game, you would create a matrix of the size of the game field (possibly padded).
This function does the job of converting the Strings into char[][] so you can use your function.
public static String[] rotateString(String[] toRotate) {
char[][] charStrings = new char[toRotate.length][];
for(int i = 0; i < toRotate.length; i++) {
charStrings[i] = toRotate[i].toCharArray();
}
// This is YOUR rotate function
char[][] rotatedStrings = rotate(charStrings);
String[] returnStrings = new String[rotatedStrings.length];
for(int i = 0; i < rotatedStrings.length; i++) {
returnStrings[i] = new String(rotatedStrings[i]);
}
return returnStrings;
}

Categories

Resources