Here is my code
public class NEW {
String Firstname;
String Lastname;
String Position;
int Jnum;
String Team;
public static void main(String[] args) throws Exception {
String a = JOptionPane.showInputDialog("Enter in 0 to sort by First Name\nEnter in 1 to sort by Last Name\n" +
"Enter in 2 to sort by position\nEnter in 4 to sort by Team names");
int q = Integer.parseInt(a);
File input = new File("Roster.txt");
Scanner players = new Scanner(input);
NEW [] array = new NEW [435];
int x=0;
while (players.hasNext()){
array[x] = new NEW();
array[x].Firstname = players.next();
array[x].Lastname = players.next();
array[x].Position = players.next();
array[x].Jnum = players.nextInt();
array[x].Team = players.next();
}
JOptionPane.showMessageDialog(null, array.toString()," ", JOptionPane.INFORMATION_MESSAGE);
players.close();
}
public static NEW[] BubbleSort(int num, NEW []array){
int p=0;
if (num==0){
String temp = null;
for(int k =1;k<435;k++){
for(int i=0;i<435-k;i++){
if(array[i].Firstname.compareTo(array[i+1].Firstname)>0){
temp = array[i].Firstname;
array[i].Firstname=array[i+1].Firstname;
array[i+1].Firstname= temp;
}
p++;
}
}
return array;
}
if (num==1){
String temp = null;
for(int k =1;k<435;k++){
for(int i=0;i<435-k;i++){
if(array[i].Lastname.compareTo(array[i+1].Lastname)>0){
temp = array[i].Lastname;
array[i].Lastname=array[i+1].Lastname;
array[i+1].Lastname= temp;
}
p++;
}
}
return array;
}
if (num ==2){
String temp = null;
for(int k =1;k<435;k++){
for(int i=0;i<435-k;i++){
if(array[i].Position.compareTo(array[i+1].Position)>0){
temp = array[i].Position;
array[i].Position=array[i+1].Position;
array[i+1].Position= temp;
}
p++;
}
}
return array;
}
if (num ==3){
int temp = 0;
for(int k =1;k<435;k++){
for(int i=0;i<435-k;i++){
if(array[i].Jnum>(array[i+1].Jnum))
temp = array[i].Jnum;
array[i].Jnum=array[i+1].Jnum;
array[i+1].Jnum= temp;
p++;
}
}
return array;
}
if (num ==4){
String temp = null;
for(int k =1;k<435;k++){
for(int i=0;i<435-k;i++){
if(array[i].Team.compareTo(array[i+1].Team)>0){
temp = array[i].Team;
array[i].Team=array[i+1].Team;
array[i+1].Team= temp;
}
p++;
}
}
return array;
}
else return array;
}
}
In the stack trace, there will be the name of your source file and a line number. These will tell you exactly which line of code is the source of the problem, which is ultimately that you are trying to access an element of a collection where there is none. For example:
List<String> l = Collections.emptyList();
String s = l.get(0); //will throw NoSuchElementException
Or it might also indicate that you are iterating over the end of an Iterator (note that a Scanner implements Iterator<String>):
Iterator<String> itr = Collections.singleton("Hey").iterator();
itr.next(); // ok!
itr.next(); //will throw NoSuchElementException
Every time you call next() on an Iterator, the "pointer" moves forwards. If you need to access the next element more than once, you need to save it in a local variable, and always use hasNext() to check that an element is available:
while (itr.hasNext()) {
String s = itr.next();
System.out.println("Length of \"" + s + "\" is: " + s.length()); //access twice
}
Unless you are using itr.remove(), you can take advantage of the java foreach loop, which removes the need for writing much of the boilerplate above, although this will not work in the case of a Scanner (which is an Iterator - foreach only works on instances of Iterable):
for (String s : someIterable) {
//can use s as many times as you want
}
As oxbow_lakes mentions, more information about the exception would be good.
But this code is suspicious:
while (players.hasNext()){
array[x] = new NEW();
array[x].Firstname = players.next();
array[x].Lastname = players.next();
array[x].Position = players.next();
array[x].Jnum = players.nextInt();
array[x].Team = players.next();
}
If players has fewer than five tokens available at the top of the loop, one of those nexts is going to fail. All that hasNext tells you is that there is at least one token available. You're assuming here that at least one means you have all five, which is (apparently) not a valid assumption as you're getting the exact exception that next is documented to throw when there's no token available.
you have used hasNext() method which actually is an enumerator() change ur array into a list... it would be much easier.. also you used next()
change it to List newelement = new LinkedList();
then the other codes..
sir, its not that he has more than 435 in the file.. its that its less than 435..
and thats why it returned null...
he used next()
make it into a list...
atleast it would be equal to what you have inputed.. it would not be 435 but it would be equal to the length of the file...
as stated by this link
http://download.oracle.com/javase/1.4.2/docs/api/java/util/NoSuchElementException.html
Related
I am trying to do a programming problem a day on leetcode to improve my programming and am having issues adding to a LinkedList in the problem below. I was wondering if anyone could give me some pointers. I know my answer isn't the most efficient, I just wanted to start somewhere and work myself up. Everything within the method is stuff I did so far. I really appreciate any help.
///
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Here's a picture with an example for a possible output:
https://imgur.com/a/g9rlb
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode(-1);
ListNode curr = new ListNode(-1);
ListNode newNode = new ListNode(-1);
// Take numbers from linkedList and store in strings
String s1 = "";
String s2 = "";
// String values after being reveresed in the right direction.
String sR1 = "";
String sR2 = "";
while(l1 != null) {
s1 += l1.val;
l1 = l1.next;
}
while(l2 != null) {
s2 += l2.val;
l2 = l2.next;
}
//check
System.out.println(s1);
System.out.println(s2);
//reverse the string;
for(int i = s1.length()-1; i >= 0; i--) {
sR1 += s1.charAt(i);
}
for(int j = s2.length()-1; j >= 0; j--) {
sR2 += s2.charAt(j);
}
//Adding the numbers together to get the final value.
int n3 = Integer.parseInt(sR1) + Integer.parseInt(sR2);
//Converting ints to string so i can parse them into characters that will eventually be parsed into an int to return back to the LinkedList
String fin = Integer.toString(n3);
System.out.println(fin);
//adding the values to my final linked list that i'd be returning here. This is the part that isn't working.
for(int i = 0; i < fin.length()-1; i++){
String s = String.valueOf(fin.charAt(i));
int num = Integer.parseInt(s);
newNode = new ListNode(num);
if(l3.val == -1) {
l3 = newNode;
}
else {
curr = l3;
while(curr.next != null){
curr = curr.next;
}
curr.val = num;
}
}
return l3;
}
Maybe something like this? The concept here is straight forward.
The requirement is to reverse the nodes and adding them. Which means you just need to choose the right data structure to meet this requirement, which provides you last in first out? Stack. Now that you have you data in a stack just pop the items from the stack and add it up and get your expected result.
There are many ways to solve this, Using an ArrayList, using LinkedList, or plain old arrays, but try to correlate the problem with a known data structure and addressing it that way would give you meaningful output consistently. I could have just pointed you to the concept but having this code will help you think on how to address a specific problem based on the user requirement. Cheers, hope it helps.
import java.util.Scanner;
import java.util.Stack;
public class AddTuple {
public static void main(String[] args) {
Stack<Integer> leftTuple = new Stack<Integer>();
Stack<Integer> rightTuple = new Stack<Integer>();
populateTuple(leftTuple, rightTuple, 3);
Stack<Integer> result = addTuples(leftTuple, rightTuple);
System.out.print("Output: {");
int i = 0;
while (!result.isEmpty()) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(result.pop());
i++;
}
System.out.println("}");
}
private static void populateTuple(Stack<Integer> leftTuple, Stack<Integer> rightTuple, int count) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Input: ");
String input = scanner.nextLine();
if (input == null || !input.contains("+") || !input.contains("{")) {
throw new RuntimeException("Usage: {x,y,z} + {a,b,c}");
}
String[] operandSplit = input.split("\\+");
String left = operandSplit[0].trim();
String right = operandSplit[1].trim();
left = left.replaceAll("\\{", "");
left = left.replaceAll("\\}", "");
right = right.replaceAll("\\{", "");
right = right.replaceAll("\\}", "");
String[] leftSplit = left.split(",");
String[] rightSplit = right.split(",");
for (int i = 0; i < leftSplit.length; i++) {
leftTuple.push(Integer.parseInt(leftSplit[i].trim()));
}
for (int i = 0; i < rightSplit.length; i++) {
rightTuple.push(Integer.parseInt(rightSplit[i].trim()));
}
} finally {
scanner.close();
}
}
private static Stack<Integer> addTuples(Stack<Integer> leftTuple, Stack<Integer> rightTuple) {
Stack<Integer> result = new Stack<Integer>();
int carryForward = 0;
while (!leftTuple.isEmpty()) {
int addition = leftTuple.pop() + rightTuple.pop() + carryForward;
if (addition > 9) {
carryForward = 1;
addition = 10 - addition;
}
result.push(addition);
}
return result;
}
}
I am currently solving this problem on Hackerrank, and below is the code that I have written so far.
When I ran it, there are a couple of errors: the output is totally wrong even though the input and the process are correct, and when the input is 1, it does not add it into my hashmap. I believe that both errors exist because of using HashMap. For example, if the input is
3(testcases) ==> 12, 5, 7. It will print out Prime, Prime, Not prime instead of the correct output like Not prime, Prime, Prime.
For more information, I commented out the lines,saying "output purposes". You can see, it added to the hashmap in correct order, but when it prints, it messed up.
So, I am just curious if someone can please explain why printing is wrong, and fix for the part when the input is 1.
import java.io.*;
import java.util.*;
public class Solution1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] myarray = new int[n]; // read number of testcases
for(int i=0;i<n;i++){ // add input to my int array
myarray[i]=sc.nextInt();
}
HashMap<Integer, String> newmap = new HashMap <>(); // create empty hashmap
int temp;
int value;
for(int i=0;i<n;i++){ // loop based on num of testcases
temp =myarray[i];
boolean isprime = true;
if(temp ==1){ // hardcode for input 1
isprime = false;
continue;
}
for(int j=2;j<=temp/2;j++){ // checking whether the input is prime or not
value = temp%j;
if(value==0){
isprime = false;
continue;
}
}
if(isprime==true){
//System.out.println("temp(Prime): "+temp); //output purpose
newmap.put(temp,"Prime");
}
else{
//System.out.println("temp(Not prime): "+temp); //output purpose
newmap.put(temp,"Not prime");
}
}
Set set = newmap.entrySet();
Iterator iterator = set.iterator();
//printing out values of the each element in hashmap(newmap)
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.println(mentry.getValue());
}
}
}
The problem in your code is that your myarray is not sorted and and when you are inserting into newmap , it's not getting inserted in the desired order.
I recommend you to sort the array and used ordered map like LinkedHashMap or linked list.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] myarray = new int[n]; // read number of testcases
Arrays.sort(myarray);
for (int i = 0; i < n; i++) { // add input to my int array
myarray[i] = sc.nextInt();
}
HashMap<Integer, String> newmap = new LinkedHashMap<Integer, String>(); // create
// empty
// hashmap
int temp;
int value;
for (int i = 0; i < n; i++) { // loop based on num of testcases
temp = myarray[i];
boolean isprime = true;
if (temp == 1) { // hardcode for input 1
isprime = false;
break;
}
for (int j = 2; j <= temp / 2; j++) { // checking whether the input
// is prime or not
value = temp % j;
if (value == 0) {
isprime = false;
break;
}
}
if (isprime == true) {
// System.out.println("temp(Prime): "+temp); //output purpose
newmap.put(temp, "Prime");
} else {
// System.out.println("temp(Not prime): "+temp); //output
// purpose
newmap.put(temp, "Not prime");
}
}
Set set = newmap.entrySet();
Iterator iterator = set.iterator();
// printing out values of the each element in hashmap(newmap)
while (iterator.hasNext()) {
Map.Entry mentry = (Map.Entry) iterator.next();
System.out.println(mentry.getValue());
}
}
}
#Jim Lewis and #Michael Markidis have already provided the right answers for how to fix the bugs in this code.
I think to satisfy the requirements of the coding exercise you're doing, you'll need to output the results in the same order as the input numbers, so you'll want to collect the results into something with an order, rather than the (unordered) HashMap. Here's some slightly cleaned up code that uses an ArrayList instead (though frankly you should be able to just print out the results as you go):
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] inputs = new int[n]; // read number of testcases
for (int i = 0; i < n; i++) { // add input to my int array
inputs[i] = sc.nextInt();
}
List<String> results = new ArrayList<>();
for (int number : inputs) {
boolean isprime = true;
if (number == 1) { // hardcode for input 1
isprime = false;
} else {
for (int j = 2; j <= number / 2; j++) { // checking whether the input is prime or not
if (number % j == 0) {
isprime = false;
continue;
}
}
}
results.add(isprime ? "Prime" : "Not prime");
}
for (String result : results) {
System.out.println(result);
}
}
}
A HashMap doesn't have predictable order. However, you can print out the keys associated with each value like this:
for (Iterator<Integer> iter = newmap.keySet().iterator(); iter.hasNext(); )
{
int key = iter.next();
System.out.println(key + "=" + newmap.get(key));
}
This will output:
5=Prime
7=Prime
12=Not prime
EDIT: As suggested by MeBigFatGuy and smarx, an entrySet() iterator is better while used with an enhanced loop.
Example:
for (Map.Entry mentry : newmap.entrySet())
{
System.out.format("%s = %s\n", mentry.getKey(), mentry.getValue());
}
You are assuming that the Iterator over the entrySet of your Hashmap will return the entries in the same order you added them. A plain old HashMap guarantees nothing of the sort (no pun intended). Try using a LinkedHashMap instead.
While checking for 1 , update in map before continue;
Inside Inner for loop ,
Use break instead of continue
Some tweaks
- If your array doesn't have duplicates then dont waste memory in
hashmaps. Loop on array.
coding exercises has large input to be read , use bufferedreader instead for faster throughput
use generics properly
I'm attempting to write a program that would read a file "data.txt" which has an undefined amount of numbers in random order, separated by line. It would add these numbers into an array and print out the numbers in one line, each separated by a comma "x, x1". Then on the next line it would print out (in the same format) the list of numbers which has been sorted from smallest to largest size.
Data type is integer.
Currently, I have coded for 3 methods which would allow the array to be sorted (I think they have no error).
I've created another method to read the file and am using a two-step process - once to figure out the number of lines in the file (I ask that this two-step process remain). This method seems to have trouble returning the "lineCount" and apparently I need to make this variable an array (which I find bizarre). How can I fix this code?
You may notice that my method for printing is empty; I have not figured out a way to print the array so that each number is separated by a comma. How do I code for this?
My code so far:
import java.util.*;
import java.io.*;
public class SortAndSearch {
public static void main(String[] args) {
readFile2Array();
printArray();
selectionSort();
printArray();
}
public static void printArray(int[] a) {
}
public static void selectionSort(int[] a) {
int minI = 0;
for (int k = 0; k < a.length - 1; ++k) {
minI = findMinIdx(a, k); // findMinIdx at k-th
swapElement(a, k, minI);// swapElement at k-th
}
}
public static int findMinIdx(int[] a, int k) {
int minIdx = k;
for (int i = k + 1; i < a.length; ++i)
if (a[i] < a[minIdx])
minIdx = i;
return minIdx;
}
public static void swapElement(int[] a, int i, int j) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int[] readFile2Array(String fileName) {
File dat = new File("data.txt");
int lineCount = 0;
int[] a = new int[lineCount];
int i;
try{ Scanner sc = new Scanner(dat);
while (sc.hasNextLine()){ //first read to count -> int lineCount;
lineCount++;
return lineCount; //I have trouble with this line
}
while (sc.hasNextLine()){ //second read to array -> hasNext(),
a[i] = sc.nextInt();
return a;
}
}
catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
}
}
public static int binarySearch(int[] arr, int val){
int minIdx, maxIdx, index = -1;
while(){ int middleIdx = (minIdx + maxIdx)/2;
if( arr[???] ==val){
index = middleIdx;
break } // update minIdx, maxIdx //if smaller then cut right, if larger then cut left
}
return index; }
}
The last method in the program would attempt to locate the element number of a user inputted number by using this (pseudo)code:
1. Let min = 0 and max = n-1 (where n is the array’s length)
2. If max < min, then stop: target is not present in array. return false.
3. Compute guess as the average of max and min, rounded down (so that it is an integer).
4. If array[guess] equals target, then stop. You found it! Return guess.
5. If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
6. Otherwise, the guess was too high. Set max = guess - 1.
7. Go back to step 2.
How would I code for this?
I would really appreciate any help in any area of this program!
Managed to fix the first part of the code:
readFile2Array method:
public static int[] readFile2Array(String fileName) {
try {
int lineCount = 0;
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNext()) { // first read to count -> int lineCount;
lineCount++; // second read to array -> hasNext(),
sc.nextLine();
}
sc.close();
sc = new Scanner(new File("data.txt"));
int[] x = new int[lineCount];
int n = 0;
while (sc.hasNext()) {
x[n] = Integer.parseInt(sc.nextLine());
n++;
}
sc.close();
return x;
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
}
return null;
}
Print array separated by comma:
public static void printArray(int[] a) {
try {
int lineCount = 0;
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNext()) {
lineCount++;
sc.nextLine();
}
sc.close();
for (int i = 0; i < a.length; ++i) {
System.out.print(a[i]);
if (i < lineCount-1) System.out.print(", ");
}
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
}
System.out.println();
}
Last method is still a mystery to me though!
I agree with VGR that you haven't actually asked a question, but by reading your code I guess that you were describing what you wanted to achieve...
There are some flaws in your readFile2Array-method, which might solve the problem:
1)
int lineCount = 0;
int[] a = new int[lineCount]; //The size of a will always be 0, so you can't add anything to it, even though you are trying to do this later. Consider using a List instead, as the size of the list can increase dynamically.
2)
while (sc.hasNextLine()){ //first read to count -> int lineCount;
lineCount++;
return lineCount; //I have trouble with this line
}
//The problem is the return type: You method signature states that you will return int[], but here you are trying to return an int.
//It will also just increase lineCount once and try to return this.
3)
//Your scanning will be at the 2nd line because of 2) and not going through the entire file again. To do this you need to create a new instance of Scanner. And the int[] a has a size of 0 at this point.
while (sc.hasNextLine()){ //second read to array -> hasNext(),
a[i] = sc.nextInt();
return a;
}
So in order to solve this you should refactor your code to something like:
public static List<Integer> readFile2Array(String fileName) {
File dat = new File("data.txt");
List<Integer> a = new ArrayList<>();
try{ Scanner sc = new Scanner(dat);
while (sc.hasNextLine()){
a.add(sc.nextInt());
}
sc.close(); //Always remember to close, when done :)
System.out.println("Added " + a.size() + " lines to the list.");
return a;
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
return new ArrayList<>();
}
}
What I changed:
removed the lineCount as this is implicit stored in the size of the list called a.
Changed the int[] a to a List as this always will allow adding elements by increasing its size when needed.
Removed i as was never used, only initialized.
Removed the first while-loop as we don't need to know the amount of lines that is going to be added.
Added a return-statement in the catch-closure. We need to return something (even an empty array or maybe the not-yet-finished array)
I hope this helps. :)
I'm glad you got that part working. :)
To print out the array, it will be best to use whatever data you have of the array. By calling a.length, you don't have to count the number of lines from the input again, which you are not guaranteed are still the same if the input has changed in the mean time.
So this piece of code should do the trick:
public static void printArray(int[] a) {
for (int i = 0; i < a.length; ++i) {
System.out.print(a[i]);
if (i < a.length-1) System.out.print(", ");
}
System.out.println();
}
I'm trying to loop through a text file for integers and store integers found into an array.
Using a try-catch to determine which words are integers and which are not using InputMismatchException, removing the non-int strings from the input stream. As well as a NoSuchElementException for blank lines in the file.
My main issue is storing the integers and printing those integers in the array, in my second method :o . It also appears my loop is also recording non-ints as null as well. They aren't suppose be stored into the array.
public static void main(String[] commandlineArgument) {
Integer[] array = ReadFile6.readFileReturnIntegers(commandlineArgument[0]);
ReadFile6.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
// connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
// If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
// if connected, read file
if (inputFile != null) {
// loop through file for integers and store in array
while (inputFile.hasNextLine()) {
for(int i = 0; i<array.length; i++)
{
try{
array[i] = inputFile.nextInt();
}
catch(InputMismatchException excep1)
{
String word = inputFile.next();
}
catch(NoSuchElementException excep2){
}
}
}
}
return array;
}
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
//prints number of integers from file
//prints each integer in array
}
}
The approach taken in the first method is a bit flawed, since you're incrementing the i variable whether or not an integer is read.
So for example, if the file looked like this:
4
Hello
5
e
7
The beginning of your array would look like
[4, null, 5, null, 7...]
So you will end up with an array of size 1000, which has nulls at unpredictable places in there.
A slightly better approach would be this:
Keep a separate count variable that says how many integers you actually read.
Add items to the array at index count and not at i (since i just says how many lines you've looked at, whereas count will tell you how many integers you've come across).
When you're finished reading them, either
pass the count variable to the method that prints the array (so it knows only to look at the first count items), or
just copy the entire array into a new array of size count.
Example incorporating this into your code:
if(inputFile != null) {
// the number of integers we've read so far
int count = 0;
// loop through file for integers and store in array
while(inputFile.hasNextLine()) {
for(int i = 0; i < array.length; i++) {
try {
array[count] = inputFile.nextInt();
count++;
} catch(InputMismatchException excep1) {
String word = inputFile.next();
} catch(NoSuchElementException excep2) {
}
}
}
}
Then to copy into a correctly sized array,
Integer[] newArray = new Integer[count];
for(int i = 0; i < count; i++) {
newArray[i] = array[i];
}
and just return newArray instead of array.
Your print method will then simply have the same signature and functionality you'd expect:
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
for(int i = 0; i < array.length; i++) {
// print the number at array[i], and whatever else you want to print
}
}
This is probably the better approach, as you can still keep all the method signatures the same, and don't need to mess around with returning multiple variables or changing global state.
Or alternatively, if you don't want to copy the relevant bits into a new array, then you could just pass the count variable somehow to your second method, and do something like
for(int i = 0; i < count; i++) {
System.out.println("\tindex = " + i + ", element = " + array[i]);
}
Key difference there is you're iterating up to count, and not up to array.length.
You would need to find a way to return that from your first method along with the array (or maybe set a static variable somewhere), and you would then need to change the signature of your second method to be
public static void printArrayAndIntegerCount(Integer[] array, int count, String filename) {
...
}
Assuming all you logic for reading integers from file are correct and also hoping this is kind of home work. Though the following implementation is not the right approach, it just solves your purpose. All we are doing here is iterating all the elements in the array until it reaches the null and keep writing them into a buffer.
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
StringBuilder sb = new StringBuilder();
int count = 0;
for(Integer i : array) {
if(i != null) {
count++;
sb.append("index = ").append(i).append(", element = ").append(array[i]).append("\n");
} else {
break;
}
}
System.out.println("number of integers in file \""+filename+"\" = "+count);
System.out.println(sb);
}
Replace your catch statement with:
catch(InputMismatchException excep1)
{
String word = inputFile.next();
i-=1;
}
You were incrementing the array counter if it found a word. I have run my own test and this worked for me to fix your issue.
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
String message = "";
int i = 0;
while(i < array.length && array[i]!=null){
message = message + "index = "+i+", element = "+array[i]+"\n";
i+=1;
}
System.out.println("number of integers in file \""+filename+"\" = "+i);
System.out.println(message);
}
I'm making this method remove() which takes a String word as argument, to delete from a global Array "words", but I keep getting a NullPointerException for some reason I cannot find, been stuck for hours.
Basically I check for if the word is in the first position, else if is in the last position, or else if it is in neither so I check all the array, and add the first half before the position of the word, and then add the second half after the position of the word in the array, as to skip it and "delete it". But I'm getting a NullPointerException in the for loop looking for the position of the word in the array. Code for the method is here:
public void remove(String a){
String[] temp_arr = new String[words.length-1]; // make array with 1 less length for deleted
if(words[0].equals(a)){ // if the word is the first in the array
for(int x=0, z=1; x<temp_arr.length; x++,z++)
temp_arr[x]=words[z];
words = temp_arr;
} else if(words[words.length-1].equals(a)){ // if the word is in the last position of the array
for(int x=0, z=0; x<temp_arr.length; x++,z++)
temp_arr[x] = words[z];
words = temp_arr;
} else{ // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop, in the if(words[k].equals(a))
int k=0;
for (; k<words.length; k++){ // find the position of the word to delete
if (words[k].equals(a)) {
break;
}
}
for (int i = 0; i < k-1; i++){ // add first part of array before the word
temp_arr[i] = words[i];
}
for(int c = k, b = k+1; c< temp_arr.length; c++,b++){
temp_arr[c] = words[b];
}
words = temp_arr; // assign the new values to global array
}
}
Also, if theres any suggestions for good coding practice would be appreciated, thanks!
** I can only use Arrays as my data structure for this method.
Modify the condition like this
a.equals(words[0])
because you know the string value a. But dont know what value will come from array. So even null value comes from the array it does allow the null pointer exception.
I run your code and find a few errors, I correct somethings without changing the core idea:
} else { // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop.
int k = -1;
for (int i = 0; i < words.length; i++) { // find the position of the word to delete
if (words[i].equals(a)) {
k=i;
break;
}
}
if(k<0)//if not exists
return;
for (int i = 0; i < k /*- 1*/; i++) { // add first part of array before the word
temp_arr[i] = words[i];
}
for (int i = k; i < temp_arr.length; i++) {
temp_arr[i] = words[i+1];
}
words = temp_arr; // assign the new values to global array
}
If the original array could't have null elements I would do like this:
public static String[] remove(String words[] , String a) {
int counter = 0;
for (int i = 0; i < words.length; i++) {
if( a.equals(words[i]) ){
words[i] = null;
counter++;
}
}
if(counter==0){
return words;
}
String[] words2 = new String[words.length - counter];
int i=0;
for (String string : words) {
if(string!=null){
words2[i++]=string;
}
}
return words2;
}
I would do that like this:
public void remove(String a) {
List<String> tmp = new ArrayList<String>();
for (String word : words) {
if ((word != null) && (word.equals(a))) {
continue;
}
tmp.add(word);
}
words = tmp.toArray(new String[]);
}
I have a question for you:
Why oh why are you using an array? You should always use a collection (eg a List) unless you absolutely have to use an array (which is rare indeed).
If it were a List, you wouldn't even need this method, because List has the remove() method that does all this for you!