Trying to correct simple array program - java

I'm trying to get some practice with Java before starting a new programming class. To do this, I decided to remake so old Perl programs I made from an earlier class. The original Perl file entered numbers entered by the user into an array and would output the array in four ways: the numbers as entered, ascending order, descending order, and the just the largest and smallest numbers.
I looked through several examples here and elsewhere online to trouble-shoot and while the program compiles, the output is wrong. As is, the array is outputted a couple dozen times, only outputting the numbers as entered. I think I have the four loops set up wrong, but I'm still learning Java so there's likely something I missed. Here's the Java code as it is now:
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayOutPut {
static Scanner input = new Scanner(System.in);
static String convertToString(ArrayList<Integer> numbers) {
StringBuilder builder = new StringBuilder();
for (int i : numbers) {
builder.append(numbers);
builder.append(",");
}
builder.setLength(builder.length() - 1);
return builder.toString();
}
public static void main(String args[]) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
int userInput;
int Largest = 0, Smallest = 0;
System.out.print(
"This program takes a set of integers from the user, and then outputs the results to the screen in four ways:\n");
System.out.print(
"the order they were entered seperated by a comma and a space, in ascending order, in descending order, and as Largest:Smallest.\n\n");
// explain to the user what the program does, needs, etc.
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
while (userInput != -1) {
System.out.print("Please enter a number or -1 to end: ");
numbers.add(userInput);
userInput = input.nextInt();
}
// Prints the array contents as entered
String sort = convertToString(numbers);
System.out.println(sort);
// prints numbers ascending
for (int i = 0; i < numbers.size(); i++) {
System.out.println(sort);
}
// prints numbers descending, largest first
for (int i = numbers.size() - 1; i >= 0; i--) {
System.out.println(sort);
}
for (int i = 0; i < numbers.size(); i++) {
int number = numbers.get(i);
if (i < Smallest) {
Smallest = i;
}
if (i > Largest) {
Largest = i;
}
System.out.println(Largest + Smallest);
}
}
}
For additional reference, here's the original Perl program:
#!/usr/bin/perl
use Modern::Perl;
my (#numbers, $userInput);# declare the array and more than one variable at a time
print("\nThis program takes a set of integers from the user, and
\nthen outputs the results to the screen in four ways:
\nthe ordered they were entered seperated by a comma and a space,
\nin ascending order, in descending order, and as Largest:Smallest.\n\n"); # explain to the user what is does, needs, etc
print "Please enter a number or -1 to end: ";
chomp ($userInput = <>); #loop is primed
if ($userInput == -1) {
say "\nThere's no numbers to process.\n";
}
else{
while($userInput != -1) {
push (#numbers, $userInput);
#Push the variable $userInput into #numbers.
print "Please enter a number or -1 to end: ";
chomp ($userInput = <>);
}
}
#Don't declare the #numbers array again, otherwise that'll clear out the entered numbers.
$" = ", ";
print "#numbers\n";
my #upsorted = sort {$a <=> $b} #numbers;
#prints numbers ascending, smallest first.
#Don't use $a, $b, or any number as a variable because they're reserved.
$" = ", ";
print "#upsorted\n";
my #downsorted = sort {$b <=> $a} #numbers;
#prints numbers descending, largest first
$" = ", ";
print "#downsorted\n";
print "$downsorted[0]:$upsorted[0]\n";
#must be set off with a blank line above and below
##End of program
Okay, as a quick update, I've finally gotten the program to run after looking up comparators on tutorialspoint.com. Here's where the code is at now:
import java.util.*;
public class ArrayOutPut {
static String convertToString(ArrayList<Integer> numbers) {
StringBuilder builder = new StringBuilder();
for (int i : numbers){
builder.append(i);
builder.append(",");
}
builder.setLength(builder.length() - 1);
return builder.toString();
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
int userInput, largest = Integer.MIN_VALUE, smallest = Integer.MAX_VALUE;
System.out.println("This program takes a set of integers from the user, and then "
+ "outputs the results to the screen in four ways:");
System.out.println("the order they were entered seperated by a comma and a space, "
+ "in ascending order, in descending order, and as Largest:Smallest.");
System.out.println();
System.out.print("This program takes a set of integers from the user, and then outputs the results to the screen in four ways:\n");
System.out.print("the order they were entered seperated by a comma and a space, in ascending order, in descending order, and as Largest:Smallest.\n\n");
//explain to the user what the program does, needs, etc.
do {
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
if (userInput != -1) {
numbers.add(userInput);
largest = Math.max(largest, userInput);
smallest = Math.min(smallest, userInput);
}
} while (userInput != -1);
//Prints the array contents as entered
String sort = convertToString(numbers);
Comparator cmp = Collections.reverseOrder();
System.out.println(sort);
Collections.sort(numbers);
System.out.println(convertToString(numbers));
Collections.sort(numbers, Comparator.reverseOrder());
System.out.println(convertToString(numbers));
System.out.printf("Smallest = %d, Largest = %d%n", smallest, largest);
}
}
My only concern is that when I compiled, I got a note that says the program uses unchecked or unsafe operations, and that I should recompile with -Xlint:unchecked for details.

First, if using Java 8+, I would use a StringJoiner in convertToString1
static String convertToString(List<Integer> numbers) {
StringJoiner sj = new StringJoiner(",");
numbers.stream().map(String::valueOf).forEach(sj::add);
return sj.toString();
}
Second, you need to sort and call convertToString again to print the results. Prefer variables with lower case names. And you can eliminate the loops with built-in functions. Check that userInput isn't -1 before adding it to your List. And I would prefer a do-while. Something like,
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
int userInput, largest = Integer.MIN_VALUE, smallest = Integer.MAX_VALUE;
System.out.println("This program takes a set of integers from the user, and then "
+ "outputs the results to the screen in four ways:");
System.out.println("the order they were entered seperated by a comma and a space, "
+ "in ascending order, in descending order, and as Largest:Smallest.");
System.out.println();
// explain to the user what the program does, needs, etc.
do {
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
if (userInput != -1) {
numbers.add(userInput);
largest = Math.max(largest, userInput);
smallest = Math.min(smallest, userInput);
}
} while (userInput != -1);
// Prints the array contents as entered
String sort = convertToString(numbers);
System.out.println(sort);
Collections.sort(numbers);
System.out.println(convertToString(numbers));
Collections.sort(numbers, Comparator.reverseOrder());
System.out.println(convertToString(numbers));
System.out.printf("Smallest = %d, Largest = %d%n", smallest, largest);
}
Update
Based on your edit(s), you're using Java 7 (not Java 8+). In which case, your code (glad to hear it is working), can be "corrected" with a typed Comparator. Something like,
Comparator<Integer> cmp = Collections.<Integer> reverseOrder();
Which will give you an Integer based Comparator in reverse order. However, it's also possible to create a custom Comparator. Such as,
Comparator<Integer> cmp = new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
if (o1 == null) {
return (o2 == null) ? 0 : -1;
}
return o1.compareTo(o2);
}
};
And then you can use it (and reverse it) like
System.out.println(sort);
Collections.sort(numbers, cmp);
System.out.println(convertToString(numbers));
Collections.sort(numbers, cmp.reversed());
System.out.println(convertToString(numbers));
1And, please prefer the List interface over the ArrayList concrete type.

Since you are already using data structures of the java.util package, I can suggest an easy way of sorting the elements in the ArrayList. Provided that numbers is the ArrayList holding all the numbers to work upon, do the following:
Display the numbers in the ArrayList numbers as they are
Make a TreeSet of numbers. A TreeSet automatically sorts its elements in ascending order NOTE: A TreeSet will only hold unique elements. So, if elements inside the list are repeated, they will get deleted. Only a single copy of each element will be stored in the Set.
Re-initialize numbers as the TreeSet made out of numbers. This is because a TreeSet can be displayed only in one order. Now, display the elements of numbers from first to last for ascending order and from last to first for descending order.
Finally, display the first and last elements of numbers as the smallest and largest numbers respectively.
Here's a code.
import java.util.*;
class MyClass{
public static void main(String[] args){
ArrayList<Integer> numbers <--- holds all the numbers
System.out.println("The numbers are:");
for(int i=0; i<numbers.size();i++)
System.out.print(numbers.get(i).intValue()+" ");
TreeSet<Integer> ts = new TreeSet<Integer>(numbers);
numbers = new ArrayList<Integer>(ts);
System.out.println("\nThe numbers in ascending order are:");
for(int i=0;i<numbers.size();i++)
System.out.print(numbers.get(i).intValue()+" ");
System.out.println("\nThe numbers in descending order are:");
for(int i=numbers.size()-1;i>=0;i--)
System.out.print(numbers.get(i).intValue()+" ");
System.out.println("\nThe smallest number is "+numbers.get(0).intValue());
System.out.println("The largest number is "+numbers.get(numbers.size()-1).intValue());
}
}
I tested it with an ArrayList having elements 1 2 5 6 7 and here's the output:
The numbers are:
7 5 6 1 2
The numbers in ascending order are:
1 2 5 6 7
The numbers in descending order are:
7 6 5 2 1
The smallest number is 1
The largest number is 7
I hope this helps.

Related

How to store and read scanner input in an array/arraylist?

I'm trying to write a program that print out the third largest number stored in an ArrayList. I tried sorting it then reversing the list to the and using get() method to get the index of third highest number. But it doesn't take into account how if there duplicates in the first 3 slots.
How do iterate through the arraylist to get the third highes value?
What I have done so far.
import java.util.*;
public class third {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(); //creating an array object
Scanner scan = new Scanner(System.in); // scanner to read user input
// print statement to get input
System.out.print("Enter any amount of numbers: ");
int i = 0;
while (scan.hasNextInt()) {// while there is an hasnext has an int
numbers.add(scan.nextInt()); //adding input(numbers) to an arraylist
i++; //increment by 1
}
scan.close(); // close the scanner if the user doesnt enter a number.
System.out.println("you entered: " + numbers);
System.out.println("The largest number you entered is: " + Collections.max(numbers));//print largest number
System.out.println("The smallest number you entered is: " + Collections.min(numbers));//print smallest number
Collections.sort(numbers); //sorting the numbers from lowest to highest
System.out.println("Sorted: " + numbers); //print sorted numbers
Collections.reverse(numbers); //reverse the order to use to get the third highest value
System.out.println("Highest to lowest: " + numbers);
System.out.println("Third highest number is:" + numbers.get(2));//get the third index of the sorted ArrayList
}
}
There is a need of a loop at the last to discard the duplicates and find exact third largest number. As i have done.
import java.util.*;
public class third {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(); //creating an array object
Scanner scan = new Scanner(System.in); // scanner to read user input
// print statement to get input
System.out.print("Enter any amount of numbers: ");
int i = 0;
while (scan.hasNextInt()) {// while there is an hasnext has an int
numbers.add(scan.nextInt()); //adding input(numbers) to an arraylist
i++; //increment by 1
}
scan.close(); // close the scanner if the user doesnt enter a number.
System.out.println("you entered: " + numbers);
System.out.println("The largest number you entered is: " + Collections.max(numbers));//print largest number
System.out.println("The smallest number you entered is: " + Collections.min(numbers));//print smallest number
Collections.sort(numbers); //sorting the numbers from lowest to highest
System.out.println("Sorted: " + numbers); //print sorted numbers
Collections.reverse(numbers); //reverse the order to use to get the third
highest value
System.out.println("Highest to lowest: " + numbers);
int counter=0; // To find distinct number
for(int i=numbers.size()-1 ; i>=0 ; i--){ // Another loop to by pass
//duplicates
if(numbers.get(i)!=numbers.get(i-1)){
counter++;
}
if(counter==2){ // third highest
System.out.println("Third highest number is:" + numbers.get(i));//get
//third index of the sorted ArrayList
break;
}
}
}
Pass the arraylist values to the hashmap. Or else store the values in the hashmap. Hashmap contains No Duplicates. after that reverse the collection and do as u did.
In order to find the third largest element, simply create a SortedSet from your list of numbers. If the set contains at least three elements then the third last element is the one you want. In order to get the third last element, convert the SortedSet to an array. See below code. Note that SortedSet is an interface that is implemented by class TreeSet.
SortedSet<Integer> ss = new TreeSet<>(numbers);
if (ss.size() > 2) {
System.out.println("Third highest number is:" + ss.toArray(new Integer[0])[ss.size() - 3]);//get the third index of the sorted ArrayList
}
You use SortedSet to sorting and deleted duplicates, so instead of Collections.sort(numbers); you can use (draft, not checking):
SortedSet<Integer> numbersSet = new TreeSet<>(numbers );
numbers = new ArrayList<>(numbersSet);
Collections.reverse(numbers);
Collections.reverse(numbers); //reverse the order to use to get the third highest value
System.out.println("Highest to lowest: " + numbers);
System.out.println("Third highest number is:" + numbers.length() > 2? numbers.get(2): "not found");//get the third index of the sorted ArrayList

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

java arraylist question where is wrong with my code

Question 1. (Arrays.java) Write a program that prompts the user to enter in an integer number representing the number of elements (between 2 and 12, use a while loop for input validation) in an arraylist. Create the appropriately-sized array list and prompt the user to enter in values for each element using a for loop. When the array is full, display the following:
The values from the array on a single line (comma separated).
The values from the array on a single line (comma separated) in
reverse order.
The values from the array that have odd numbered values.
The values from the array that have odd numbered indexes. Do not use
an if statement here.
The maximum from the array and the position (index) where it occurs.
here is my code. not sure where goes wrong the for loop doesn't run
import java.util.Scanner;
import java.util.ArrayList;
public class a5q2{
public static void main(String[] args){
Scanner keyb = new Scanner(System.in);
int num = 0;
do {
System.out.println("Enter a number 2 to 12");
num = keyb.nextInt();
} while(num<2||num>12);
ArrayList<Integer>list= new ArrayList<Integer>(num);
//user input
for(int i =0;i<list.size();i++) {
System.out.println("Enter a Value(list): ");
int value=keyb.nextInt();
list.add(value);
}
//display list
System.out.println(list);
//reverse order
for(int i =list.size() - 1;i>=0;i--) {
System.out.println(list.get(i)+",");
}
//all odd value
for(int i =0;i<list.size();i++) {
if(list.get(i)%2==1)
System.out.println(list.get(i)+",");
}
//odd indices
for(int i =0;i<list.size();i+=2) {
System.out.println(list.get(i)+",");
}
}
}
The problem is that the constructor public ArrayList(int initialCapacity):
Constructs an empty list with the specified initial capacity.
(Emphasis mine)
So your loop:
for(int i =0;i<list.size();i++){
System.out.println("Enter a Value(list): ");
int value=keyb.nextInt();
list.add(value);
}
Will never execute as the size is zero.
You can test this by printing out the size before the loop:
System.out.println(list.size());
To fix this, simply loop until num:
for(int i =0;i<num;i++){
System.out.println("Enter a Value(list): ");
int value=keyb.nextInt();
list.add(value);
}

Sorting Arrays. The first element is length of array

Question :
Sorted?) Write the following method that returns true if the list is already sorted in increasing order. public static boolean isSorted(int[] list) Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list.
My try:
import java.util.Scanner;
public class Problem6_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number. for the length of the list: ");
int listLength = input.nextInt();
int[] number = new int[listLength];
for(int i = 0; i < number.length; i++) {
System.out.println("Enter a value: ");
number[i] = input.nextInt();
}
if (isSorted(number)) {
System.out.println("The list is sorted!");
} else {
System.out.println("The list is NOT sorted!");
}
}
public static boolean isSorted(int[] list) {
for(int i = 0; i < list.length; i++) {
if (list[i] > list[i + 1]) {
return false;
} else {
return true;
}
}
return false;
}
}
But there's one problem. In the question it prompts the user to enter list and the first element is length of that list. This means that we need to prompt the user only one time. So please explain how is this possible that first element becomes the size of an array??
The Scanner class uses whitespace, any white space, as the delimiter between tokens by default. This means that if the user pressed return between entering numbers then you need to handle that case and ask the user for another number, or the end user would just be on a new line and not know what to do. If the user doesn't press return between entering the numbers but separates them with a space, for example:
1 2 3 4 5
then the scanner would separate that in to 5 separate tokens that would be returned one at once when you call nextInt().
If you run your program and enter something like:
4 2 1 3 4
It should out put four questions asking you to enter inout (that you have already given to it) but then perform the function you want anyway and print "The list is NOT sorted!".
PS. the program doesn't quite work as I imagine you want it to because you as it only checks if the first two values are in ascending order and then returns. Instead you should check to see if the first two are correct, set a flag to keep track of them if they are and then carry on with the loop without exiting. Or only return in the case where the list isn't sorted and if you get to the end of checking the array and you haven't exited it must be sorted and therefore you should return true (as in the code example below). The return statements force your method isSorted to exit as soon as it hits that line, without going through the whole loop. You should also check for going off the end of the array before trying to access i+1. Something like
import java.util.Scanner;
public class ScannerClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number. for the length of the list: ");
int listLength = input.nextInt();
int[] number = new int[listLength];
for(int i = 0; i < number.length; i++) {
System.out.println("Enter a value: ");
number[i] = input.nextInt();
}
if (isSorted(number)) {
System.out.println("The list is sorted!");
} else {
System.out.println("The list is NOT sorted!");
}
}
public static boolean isSorted(int[] list) {
for(int i = 0; i < list.length - 1; i++) {
if (list[i] > list[i + 1]) {
return false
}
}
return true;
}
}

Java: Storing numbers in vector, transfer to array, then take primes from array and store in another vector

I'm going to post the question and then the code that I currently have done. I feel like I'm pretty close to getting it but I'm stuck at one part I just can't seem to figure out. Here goes:
The question: Create a Vector that stores N numbers. Input N non-negative numbers through the console into the Array. Then create another Vector that stores only M prime numbers from the N numbers.
My code so far:
import java.util.*;
public class VectorPrimes {
public static Vector<Integer> inputVc = new Vector<Integer>();
public static Vector<Integer> primeVc = new Vector<Integer>(inputVc);
public static boolean isPrime(int n) {
boolean prime = true;
for (int i = 2; i * i <= n; i+= 2) {
if (n % i == 0) {
prime = false;
break;
}
}
return prime;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out
.println("This program will take input of positive numbers and output"
+ " prime numbers, if any, from the input numbers.");
System.out
.println("Input a positive number to check for prime numbers: ");
boolean looping = true;
while (looping) {
System.out
.println("Input '0' to finish inputting numbers and print the primes.");
String userin = scan.nextLine();
int input = Integer.parseInt(userin);
if (input != 0) {
System.out.println("Enter next number: ");
inputVc.add(input);
} else if (input == 0) {
//Integer[] inputArray = inputVc.toArray(new Integer[inputVc.size()]);
looping = false;
System.out.println(inputVc);
System.out.print(primeVc);
System.exit(0);
}
}
}
}
I'm sure it's not the best way to do it, but that's what I have so far. To be clear, I'm having trouble getting the inputted numbers from the input vector (inputVc) to go into the array (inputArray) and then storing the prime numbers in the prime vector (primeVc) and printing them. I have tried 3 or 4 different ways but I can't get anything to store in the primeVc vector, it just keeps printing blank.
I'm not asking for the code, what I'm trying to figure out is strictly how to get the prime numbers inputted into the primeVc vector and then print it. Of course the inputVc numbers need to be run through the isPrime method and then added to the primeVc vector if true, but I'm pretty sure that's where I'm having my problem.
What do you guys see?? I'm definitely missing something and cannot for the life of me figure it out.
Do something like:
//...
if (input != 0) {
System.out.println("Enter next number: ");
inputVc.add(input);
if (isPrime(input))
primeVc.add(input);
}
//...
Also you can create while(true) loop and simply break it when you will get 0.
first you have to call your functon isPrimethen if returned value is true then add it to your second list
and other thing, your function isPrime won't work, your initial value of 'i' is 2, then you are incrementing it by 2, so it will return value true for each odd number

Categories

Resources