Store ints into array from a file and find primes JAVA - java

In this interactive program, you will find a menu with options to perform different functions on an array. This array is taken from a file called "data.txt". The file contains integers, one per line. Obviously, I have not included the entire code (it was too long). However, I was hoping that someone could help me with the problem of finding the prime numbers in the array Right now, the console prints the address of the array for the primes ([I#4a13ccea). Any suggestions are welcome. Part of my program is below. Thanks.
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Display the average of the list");
System.out.println("2. Display the number of occurences of a given element in the list");
System.out.println("3. Display the prime numbers in a list");
System.out.println("4. Display the information above in table form");
System.out.println("5. Save the information onto a file in table form");
System.out.println("6. Exit");
int option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
System.out.println("You've chosen to compute the average.");
infoMenu1(sc);
break;
case 2:
infoMenu2(sc, sc);
break;
case 3:
infoMenu3(sc);
break;
case 4:
infoMenu4(sc);
break;
case 5:
infoMenu5(sc);
break;
case 6:
System.exit(0);
default:
System.out.println("Unrecognized Option!\n");
}
}
}
private static void infoMenu3(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
int[] numbers = new int[100];
int i = 0;
while (sc.hasNextInt()) {
numbers[i] = sc.nextInt();
++i;
}
for (int j = 0; j < i; ++j) {
System.out.print("The numbers in the file are: " + numbers[j] + " ");
}
}
public static boolean prime(int x) {
boolean answer = true;
for (int i = 2; i <= x / 2; i = i + 1) {
if (i != x) {
if (i % x == 0) {
answer = false;
}
}
}
return answer;
}
public static int[] primes(int[] numbers) {
int primesCount = 0;
for (int i : numbers) {
if (prime(i)) {
primesCount = (primesCount + 1);
}
}
if (primesCount == 0) {
return null;
}
int[] result = new int[primesCount];
int index = 0;
for (int i : numbers) {
if (prime(i)) {
result[index] = i;
index = index + 1;
}
}
return result;
}
}

Loop through your array and print every element, or use the java.util.Arrays.toString(int[]) method if its format suits your needs.

Two marks
If you print an array like this, you will get the address of the array, not the inside.
System.out.println("The primes in the file are: " + primes(numbers));
Replace this line with a loop that iterates over primes(numbers)
The second is, in your public static boolean prime(int x) function you have this line
for (int i = 2; i <= x / 2; i = i + 1)
Although this works, to find a prime yo do not need to iterate until x / 2 . For performance benefits Square root of x would suit better.

Related

Decrement by a certain amount on java

i'm trying to create a program where the number that the user has input would decrease by a certain amount. something that would like this:
Update by (Increment/Decrement):decrement
Enter starting number:15
Enter update number:3
Enter end number:3
loop#1 value=15
loop#2 value=12
the end number is where the loop would stop and the update number is how much the starting number should decrement by. so far this is the code I have and I'm stuck on how to keep the loop going until the end number.
package jaba;
import java.util.Scanner;
public class loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String Decrement = scan.nextLine();
System.out.print("Enter starting number:");
String number = scan.nextLine();
System.out.print("Enter update number:");
String upnumber = scan.nextLine();
System.out.print("Enter end number:");
String endnumber = scan.nextLine();
int i,j;
i = 15;
j = 1;
do {
System.out.println("loop#" +j+ "\tvalue="+i);
j++;
}while(i<15);
i = i-3;
System.out.println("loop#" +j+ "\tvalue="+i);
};
}
how about something like this:
public class loop {
public enum Operation {INCREMENT, DECREMENT, INVALID}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String operationString = scan.nextLine();
System.out.print("Enter starting number:");
String numberString = scan.nextLine();
System.out.print("Enter update number:");
String upnumberString = scan.nextLine();
System.out.print("Enter end number:");
String endnumberString = scan.nextLine();
// Determine and parse stuff
int startNumber = Integer.parseInt(numberString);
int updateNumber = Integer.parseInt(upnumberString);
int endNumber = Integer.parseInt(endnumberString);
// Parse operation, but assume invalid operation
Operation operation = Operation.INVALID;
if (operationString.equalsIgnoreCase("increment")) {
operation = Operation.INCREMENT;
} else if (operationString.equalsIgnoreCase("decrement")) {
operation = Operation.DECREMENT;
}
// now do the "meat" of the assignment
int loopNumber = 0; // we'll keep the loop number as a separate counter
switch (operation) {
case INCREMENT:
for (int i = startNumber; i < endNumber; i = i + updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i);
}
break;
case DECREMENT:
for (int i = startNumber; i > endNumber; i = i - updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i)
}
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
}
private static void performAssignmentPrinting(int loopNumber, int value) {
System.out.println("loop#" + loopNumber + "\tvalue=" + value);
}
}
or the do/while version:
// now do the "meat" of the assignment
int currentNumber = startNumber;
int loopNumber = 0; // we'll keep the loop number as a separate counter
do {
loopNumber++;
switch (operation) {
case INCREMENT:
currentNumber += updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case DECREMENT:
currentNumber -= updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
} while (currentNumber != endNumber);
you have i = i-3; out of loop.
Move decrementation of i into loop:
do {
System.out.println("loop#" + j + "\tvalue=" + i);
j++;
i = i - 3;
} while (i > endnumber);
For loop is the solution for your program. for(a ; b ; c) {...}
Google how a for loop works. And try to understand how the 3 parts a,b,c works.
Pseudo:
// if decrease mode
// for (i = upperbound ; i >= lowerbound ; i-= decrement)
// print i
// if increase mode
// for (i = lowerbound ; i <= upperbound ; i+= increment)
// print i
Update: This is sufficient to get you started and add more validation on your journey.

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

Java: How to use binary search with an array

For this java program, I'm trying to use a binary search for the array I have created in the Class Numbers, however, when I enter the 4th choice, the program just ends. The method binSearch is in Class Numbers. I can enter the required the size of the array, generate random numbers, search for specific numbers, and display them. However, when I want to use a binary search, the program ends as previously said. What is the reason why the program ends and what needs to be done to fix that certain method?
public class Numbers {
int[] array;
private int sizeOfArray;
public Numbers() {
sizeOfArray = 0;
array= new int [sizeOfArray];
}
public Numbers(int sizeOfArray) {
this.sizeOfArray = sizeOfArray;
array= new int [sizeOfArray];
}
public void generateNumbers() {
Random randomNumber = new Random();
int theNumber = 0;
for (int i = 0; i < sizeOfArray; i++) {
theNumber = randomNumber.nextInt(50);
array[i] = theNumber;
}
}
public int count(int num) {
int theNumbers = 0;
for (int i = 0; i < sizeOfArray; i++) {
if (array[i] == num) {
theNumbers++;
}
}
return theNumbers;
} // end count method
public String toString() {
String myArray = "";
for (int i = 0; i < sizeOfArray; i++) {
myArray += array[i] + " ";
}
return myArray;
}
public int binSearch(int[] array, int key) {
int low = 0;
int high = sizeOfArray - 1;
//int middle = (low + high + 1) /2;
int location = -1;
while (high >= low) {
int middle1 = (low + high) / 2;
if (array[middle1] == key ) {
//return true;
}
if (array[middle1] < key) {
low = middle1 + 1;
}
if (array[middle1] > key) {
high = middle1 - 1;
}
}
//return false;
return location;
}
}
and here is the main menu:
boolean isDone = false;
String input = null;
Numbers theNumber = new Numbers();
Scanner scanner = new Scanner (System.in);
try {
while (isDone == false) {
/*Menu options */
System.out.println("Enter 1 to create array size");
System.out.println("Enter 2 to generate random numbers");
System.out.println("Enter 3 to search and display number of occurrences");
System.out.println("Enter 4 to binary search to find whether specific number exists");
System.out.println("Enter 5 to display the array");
System.out.println("Enter 6 to quit the program");
input = scanner.nextLine();
switch (input) {
case "1":
int intNumber1 = 0;
System.out.println("Enter required size:");
intNumber1 = Integer.valueOf(scanner.nextLine());
theNumber = new Numbers(intNumber1);
System.out.println("Array has been generated.");
break;
case "2":
//theNumber = new Numbers();
theNumber.generateNumbers();
System.out.println("Numbers have been generated and stored.");
break;
case "3":
int intNumber2 = 0;
System.out.println("Enter number to search for: ");
intNumber2 = Integer.valueOf(scanner.nextLine());
System.out.println("Number of occurences of " + intNumber2 + " in the array is " + theNumber.count(intNumber2) + ".");
break;
case "4":
int key = 0;
theNumber.binSearch(null, key);
System.out.println("Array is sorted: ");
break;
case "5":
int theNumbers = 0;
if (theNumbers == 0)
{
System.out.println("No array has not been generated yet.");
}
else
{
System.out.println("The numbers are: ");
}
System.out.println(theNumber.toString());
break;
case "6":
isDone = true;
System.out.println("Bye... See you again");
scanner.close();
break;
default:
System.out.println("These are invalid choices...please reenter.");
break;
}
}
}
catch (Exception exception)
{
System.out.println("This is an invalid choice...please reenter.");
scanner.nextLine();
return;
}

Java Array homework [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to stack overflow and I'm trying to help a friend with their programming homework.
So far we have this
package range;
import java.util.Arrays;
import java.util.Scanner;
public class Range
{
static int[] series = new int[100];
static int seriesLength = 0;
public static void main(String[] args)
{
Scanner t = new Scanner(System.in);
boolean run = true;
while(run)
{
int option;
System.out.println("1. Loading a range of up to 100 numbers");
System.out.println("2. Showing the range of given(loaded) numbers");
System.out.println("3. Determination of the middle value of the series");
System.out.println("4. Determination of the biggest element of the series");
System.out.println("5. Determination of the smallest element of the series\n");
System.out.println("Enter the number of the option you want (1-5), or 0 to end");
option = t.nextInt();
switch(option)
{
case 1:
{
System.out.println("Please input a number from 1 -100");
seriesLength = t.nextInt();
System.out.println(seriesLength);
if((seriesLength < 1) || (seriesLength > 100))
{
System.out.println("Invalid input, series must be between 1 and 100.\nPress any key to try again.\n");
break;
}
for(int i = 0; i < seriesLength; i++)
{
series[i] = i+1;
}
break;
}
case 2:
{
System.out.println(seriesLength);
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
showSeries(series, seriesLength);
break;
}
case 3:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
middleNum(series, seriesLength);
break;
}
case 4:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
biggestNum(series, seriesLength);
break;
}
case 5:
{
if(seriesLength == 0)
{
System.out.println("You must first load a series of numbers\n");
break;
}
smallestNum(series, seriesLength);
break;
}
case 0:
{
System.out.println("BYE, DOBRO DOBRO.");
run = false;
break;
}
default:
{
System.out.println("Invalid input");
break;
}
}
}
}
public static void showSeries(int[] input, int range)
{
for(int i = 0; i < range; i++)
{
System.out.println(input[i]);
}
}
public static void biggestNum(int[] input, int range)
{
Arrays.sort(input);
System.out.println(input[0]);
}
public static void middleNum(int[] input, int range)
{
int Middle = input.length / 2;
if ((input.length % 2) > 0)
{
System.out.println(input[Middle]);
}
else
{
System.out.println((input[Middle-1] + input[Middle]) / 2.0);
}
}
public static void smallestNum(int[] input, int range)
{
Arrays.sort(input);
for(int i = 0; i < range; i++)
{
System.out.println(input[i]);
}
}
}
The task was to write a program which works with an array of numbers using a menu
with few options. But also the task of each option needs to be a separate method and the main method needs to only show the menu and call for each method depending on the number(option) chosen. Also needs to check users errors, example if option 2 is chosen before option 1 or the chosen option doesn't exist and etc.
I'm confused on how to proceed as I'm no expert in java. How would this be done considering that the only things can be used are defined by the task
Maybe you want something more like this, Where the show series method actually sets the array, so the other methods can use the array
static int[] series = new int[100];
static int seriesLength = 0;
...
// Get the input for range
public static void showSeries(int range)
{
seriesLength = range;
series = new int[seriesLength];
for (int i = 0; i < series.legnth; i++) {
series[i] = i;
System.out.print(series[i] + " ");
}
}
Because this first method needs to be the first one called before anything, the array will be set. Then the other methods shouldn't have to take any arguments, as the array is already set, and they can just use the static array.

Why am I getting nullpointer Exception in this Program?

I am new to Java , can anyone explain why i am getting a Null pointer Exception ?
Additionally can anyone explain other reliable input methods besides Scanner.
The Error
Exception in thread "main" java.lang.NullPointerException
at Theater.main(Theater.java:18)
import java.util.Scanner;
public class Theater
{
public static void main(String[] args) throws Exception
{
int Screen;
Screens[] X = new Screens[5];
Scanner input = new Scanner(System.in);
do
{
System.out.println();
System.out.println(" '0' to exit");
System.out.println(" '1-5' for Booking Seats");
System.out.println(" '10' for Displaying Seating Status");
System.out.println("Enter Screen Number : ");
Screen = input.nextInt();
if(Screen >= 1 && Screen <= 4)
X[Screen-1].bookSeat();
else if(Screen == 0)
{
System.out.println("Thank You for Booking Seats in PVR Cinemas.");
System.in.read();
System.exit(0);
}
}while(true);
}
}
class Screens
{
private
int[] Gold = new int[3];
int[] Platinum = new int[3];
int[] Diamond = new int[3];
int g,d,p;
Scanner input = new Scanner(System.in);
final int MAX=3;
public Screens()
{
for( int i=0;i<3;i++)
{
Gold[i] = 0;
Platinum[i] = 0;
Diamond[i] = 0;
g = d = p = 0;
}
}
public void bookSeat()
{
int n=0,choice,i;
System.out.println("\t\tMenu");
System.out.println("1.Gold \tAvailable Seats : "+(3-g));
System.out.println("2.Platinum \tAvailable Seats : "+(3-p));
System.out.println("3.Diamond \tAvailable Seats : "+(3-d));
System.out.println("4.Return to Main Menu");
System.out.println("Your Choice : ");
choice = input.nextInt();
if(choice>=1 && choice<=3)
{
System.out.print("How many Seats ? : ");
n = input.nextInt();
if( n<=0 )
{
System.out.println("Please Check your Input.");
return;
}
else if( n>=MAX )
{
System.out.println("The Maximum Number of Seats is : "+MAX);
}
}
switch(choice)
{
case 1:
if(g+n >3)
{
System.out.println("Housefull!");
break;
}
else
{
int total = 0;
System.out.print("Seat Numbers are : ");
for(i=0;i<n;i++)
{
Gold[g++] = 1;
System.out.print("\t"+g);
}
total = 100 * n;
System.out.println("Total Money to be paid : "+total);
}
break;
case 2:
if(p+n >3)
{
System.out.println("Housefull!");
break;
}
else
{
int total = 0;
System.out.print("Seat Numbers are : ");
for(i=0;i<n;i++)
{
Platinum[p++] = 1;
System.out.print("\t"+p);
}
total = 125 * n;
System.out.println("Total Money to be paid : "+total);
}
break;
case 3:
if(d+n >3)
{
System.out.println("Housefull!");
break;
}
else
{
int total = 0;
System.out.print("Seat Numbers are : ");
for(i=0;i<n;i++)
{
Diamond[d++] = 1;
System.out.print("\t"+d);
}
total = 150 * n;
System.out.println("Total Money to be paid : "+total);
}
break;
case 4:
break;
default:
System.out.println("Sorry, That's an invalid Choice!");
}
return;
}
public void viewSeats()
{
int i;
System.out.println("Gold Category : ");
for(i=0;i<3;i++)
System.out.print("\t "+Gold[i]);
System.out.println("Platinum Category : ");
for(i=0;i<3;i++)
System.out.print("\t "+Platinum[i]);
System.out.println("Diamond Category : ");
for(i=0;i<3;i++)
System.out.print("\t "+Diamond[i]);
}
}
You need to populate your Scrrens array. In other words you have only initialized your Scrren array but never initialized its elements.If you don't initialize its elements they get default values which in this case is null. Guess what happens when you invoke somemethod on null. Boom NPE you get.
Screens[] X = new Screens[5];
x[0] = new Screen();
Although you initialize the array X you do not initailize its members so when doing X[Screen-1] you are using a null object (even if the index is in the bounderies).
Because your array X doesn't have any elements in it, so by default every element is initialized to null. So basically you are trying to do this null.bookseat() which results in a NullPointerException.
It is also important to note that if Screen is ever 5 (which is allowed by your condition <= 5) then you will get an ArrayIndexOutOfBoundsException because your array only have indices 0,1,2,3,4 (5 total)
Your array X is being created, but the elements are not initialized, they are still null. I think you are expecting to have your array initialized like this:
Screens[] X = new Screens[5];
for (int x = 0; x < 5; x++) {
X[x] = new Screens();
}
You get a NullPointerException because you have declared an array to hold 5 screen objects but you have never initialized the 5 slots with an actual Screen object
Thus when you try to use the
X[Screen-1].bookSeat();
you are referencing a null element in the array and of course you cannot call a method of a null object
You could add a check before using the object and initialize the screen
if(Screen >= 1 && Screen <= 4) {
if (X[Screen-1] == null)
X[Screen-1] = new Screens();
X[Screen-1].bookSeat();
}
also there is something weird in your usage. Arrays start at zero index but you use the zero as a value to exit from the program, so the element at index zero is never used.
Because after Screens[] X = new Screens[5]; all 5 elements of array X are null!!
One more way to populate your Screens array
Screens[] X = { new Screens(), new Screens(), new Screens(),new Screens(), new Screens() };
you may find using List from Collections more useful.

Categories