Program repeats entries in output - java

Program code works correctly, except the output repeats some of the
inputs. I can't seem to figure out why it repeats the first entry as well as the last entry.
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_ELEMENTS = 8; // Number of elements
int[] userVals = new int[NUM_ELEMENTS]; // User input
int i = 0; // Loop index
int greaterVal = 0; // Find greater #'s than 21
// Prompt user to populate array
System.out.println("Enter " + NUM_ELEMENTS + " integer values...");
for (i = 0; i < NUM_ELEMENTS; ++i) {
System.out.println("Value: ");
userVals[i] = scnr.nextInt();
}
// Determine #'s greater than 21
int greaterVal = userVals[0];
System.out.print("#'s greater than 21 are: ");
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] >= 21) {
greaterVal = userVals[i];
}
// Code is supposed to only display #'s greater than 21 once
System.out.print(" " + greaterVal + " ");
}
return;
}
}

for (i = 0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] >= 21) {
greaterVal = userVals[i];
}
// Code is supposed to only display #'s greater than 21 once
System.out.print(" " + greaterVal + " ");
}
formatting is very bad, and this fragment is not correct. You should print value at once, not save it for later.

This is because you have mention System.out.print(" " + greaterVal + " "); out side of condition if (userVals[i] >= 21), that why if current value in loop less then 21 and if previous value was greater then 21 value which is hold by greaterVal variable then it will print previous value again .
update your code
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] >= 21) {
greaterVal = userVals[i];
// Code is supposed to only display #'s greater than 21 once
System.out.print(" " + greaterVal + " ");
}
}
Also if you just need to print the greater then 21 values, then you don't need greaterVal variable, you just need this
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] >= 21) {
// Code is supposed to only display #'s greater than 21 once
System.out.print( " "+ userVals[i] + " ");
}
}

Related

How to show only occurrences of numbers user input in java?

I'm new to programing and trying to solve this problem, but have no idea what I did wrong.
The program is supposed to take user input until 0 is entered and after that, print out information of occurrences of numbers user input - and here is my problem.
The program I wrote shows occurrences of all numbers (up to max number that can be input), not only those that user wrote.
My code:
package numbers;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] occurences = new int[11];
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occurences[num]++;
num = scan.nextInt();
}
for (int i = 0; i < 11; i++) {
System.out.print("Value: " + i + " Occurences: " + occurences[i] + " ");
}
}
}
Use if statement to print only numbers with occurences higher than 0.
Side notes:
Array values initialization is not needed:
for (int i = 0; i < 11; i++) {
occurences[i] = 0;
}
Value at each index is already 0, check this question.
While loop condition, does not make much sense
while (num > 0 && num <= 11) {
occurences[num]++;
num = scan.nextInt();
}
Array size is 11, meaning indexes range from 0 to 10 inclusive. Since you allow input 11, you will get ArrayIndexOutOfBoundsException.
You can make use of map.
Map<Integer, Integer> occ = new HashMap<>();
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occ.put(num, occ.getOrDefault(num, 0)+1);
num = scan.nextInt();
}
for(int i : occ.keySet()){
System.out.print("Value: " + i + " Occurences: " + occ.get(i) + " ");
}

JOptionPane Looping

I have an issue. My lecturer wants me to make a loop, with an input of JOptionPane and an output of console. How can I use loop for JOptionPane and send an output through console.
Here's my code:
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
String a1 = JOptionPane.showInputDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++){
int a = Integer.parseInt(a1);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
I would try using a DO-WHILE loop with and an int[], example:
int size = 10;
int count = 0;
int[] yourNumbers = new int[size];
do {
yourNumbers[count] = Integer.parseInt(JOptionPane.showInputDialog(null,
"Your message here."));
count++;
} while (count < 10);
This way you can loop through and grab all the numbers. Then you can use a FOR-LOOP to cycle through and print what you need
System.out.println("Even Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 == 0) {
System.out.println(yourNumbers[i]);
}
}
System.out.println("Odd Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 != 0) {
System.out.println(yourNumbers[i]);
}
}
The problem with your current code is that you only ask the user one time to input a number but you actually seem to want 10 values. So you parse ten times the same value.
The solution is simple, put the dialog inside the loop (only changed the lines with comments):
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
// No return type, just a message
JOptionPane.showMessageDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++) {
// Dialog inside the loop, asking to
// input a number in every iteration
String value = JOptionPane.showInputDialog(null, "Type in "
+ (counter + 1) + ". value");
int a = Integer.parseInt(value);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);

Finding the Last 10 Elements in a Array

Hey guys so I have to find the last 10 elements in my array in my .txt file filled with unsorted primes. The problem I'm having is the code I'm using to get the last 10 elements is just returning the same number instead of the last ten digits. If anyone can help me figure it out that would be great.
Also i have looked through some other code to figure it out, but i had no luck. If you do answer please don't just answer with a link to someone else code. Thanks
Heres my code so far:
public class BubbleSort {
static long BubbleSortCount = 0;
public static void main(String[] args) throws IOException {
System.out.print("This program compares the bubble, selection, merge sorts.\n"
+ "The data set is 78498 unsorted integers (prime numbers less than 1,000,000)\n\n");
File file = new File("primes1.txt");
Scanner infile = new Scanner(file);
ArrayList<Integer> Primes1 = new ArrayList<Integer>();
int temp;
long startTime, endTime;
int n;
while (infile.hasNextInt()) {
n = infile.nextInt();
Primes1.add(n);
}
// bubble
System.out.print("BUBBLE SORT\n");
System.out.println("\nPrimes Read : " + Primes1.size());
startTime = System.currentTimeMillis();
Primes1 = Bubble(Primes1);
endTime = System.currentTimeMillis();
System.out.println("Elapsed Seconds = "
+ (double) ((endTime - startTime) / 1000.0));
System.out.println("iterations = " + BubbleSortCount++);
System.out.print("First 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(i) + " ");
}
System.out.println();
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
}
// Bubble sort Method
public static ArrayList<Integer> Bubble(ArrayList<Integer> Primes1) {
int temp;
for (int i = 0; i < Primes1.size() - 1; i++) {
for (int j = 0; j < Primes1.size() - 1; j++) {
BubbleSortCount++;
if (Primes1.get(j) > Primes1.get(j + 1)) {
temp = Primes1.get(j);
Primes1.set(j, Primes1.get(j + 1));
Primes1.set(j + 1, temp);
}
}
}
return Primes1;
}
}
Here are the numbers in my .txt file.
7
2
47
13
11
59
17
41
37
23
29
31
19
53
43
241
251
257
263
269
271
277
281
283
293
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
With the 1 it will always take the same number, should be fixed
System.out.print(Primes1.get(Primes1.size() - i) + " ");
Change:
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
To:
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - (i+1)) + " ");
}
Or:
for (int i = 1; i <= 10; i++) {
System.out.print(Primes1.get(Primes1.size() - i) + " ");
}
The reason you get the same number is that you never use the index in the for-loop to get the 10 last.
This:
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
must be changed to use the loop index variable. This should do it:
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 10 + i) + " ");
}
Another way would be to use the sublist method from the List interface to produce a new list with the 10 last elements, like this:
List<Integer> last10list = Primes1.subList(Primes1.size() - 11, Primes1.size());

I'm trying to create an error message if the data entered in an array is less than zero, input validation

This method allows the user to input the rainfall for every month of the year. I'm trying to prevent data less than zero from being stored in the array. I'm using a do-while loop, but I can't seem to figure out how to check if the input is less than zero. Thanks for your help guys, cheers!
public static double[] getRainFall()
{
double[] rainfallMonths = new double[12];
double[] rainfall = new double[12];
do
{
for(int x = 0; x < rainfallMonths.length; x++)
{
System.out.print("What is the rainfall for month #" + (x + 1) + ": ");
rainfallMonths[x] = keyboard.nextDouble();
rainfall[x] = rainfallMonths[x];
if(rainfallMonths < 0)
{
System.out.println("Input is Invalid");
}
}
}while(rainfallMonths < 0);
for(int count = 0; count < rainfallMonths.length; count++)
{
System.out.println("Rainfall Month #" + (count + 1) + ": " + rainfall[count]);
}
return rainfall;
}
Your logic is a little off, not to mention that you're trying to compare an array to an int...
First, the logic...
do
for x = 0 to rainfallMonths.length -1 do
... get input...
while value < 0
The problem here is, you've already assigned the input to all the elements of the array in the for-next loop, but then you are trying to validate the value that was input outside of the for-next which is likely never to return a valid result...and it's too late...
Instead, you want to reverse the logic...
for x = 0 to rainfallMonths.length -1 do
do
value = get input from user
while value < 0
rainfallMonths[x] = value
Next, rainfallMonths is a reference to an array, this isn't actually what you want to be checking against, you need to be checking against one it's values or elements, for example...
while (rainfallMonths[x] < 0);
And if none of that made sense...
public static double[] getRainFall()
{
double[] rainfallMonths = new double[12];
double[] rainfall = new double[12];
for(int x = 0; x < rainfallMonths.length; x++)
{
double input = 0;
System.out.print("What is the rainfall for month #" + (x + 1) + ": ");
do {
rainfallMonths[x] = keyboard.nextDouble();
rainfall[x] = rainfallMonths[x];
if(input < 0)
{
System.out.println("Input is Invalid");
}
} while (rainfallMonths[x] < 0);
}
for(int count = 0; count < rainfallMonths.length; count++)
{
System.out.println("Rainfall Month #" + (count + 1) + ": " + rainfall[count]);
}
return rainfall;
}
You might want to take a refresher on Arrays which should help ;)
double temp = -1;
for(int x = 0; x < rainfallMonths.length; x++)
{
System.out.print("What is the rainfall for month #" + (x + 1) + ": ");
temp = keyboard.nextDouble();
if(temp < 0)
{
System.out.println("Input is Invalid");
x--; //if you want the user to maybe try to repeat this month again?
}
else
{
rainfallMonths[x] = keyboard.nextDouble();
rainfall[x] = rainfallMonths[x];
}
}

Array java help needed

I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.
public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("enter integers between 1 and 100: ");
int[] num = new int[100];
int data = input.nextInt();
while ((data = input.nextInt()) != 0) {
num[data]++;
}
for (int i = 1; i < 100; ++i) {
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
}
You need two separate loops: the first to gather the information, and the second to print the results:
int data = 0;
while ((data = input.nextInt()) != 0)
{
num[data]++;
}
for (int i = 0; i < 100; ++i)
{
if (num[i] != 0) { /* print num[i] */ }
}
Just loop over the num array after your while loop to print the counts.
for (int index = 0; index < num.length; index++) {
if (num[index] != 0)
System.out.println(data + " occurs " + num[data] + " time(s).");
}
You are printing an output every time an integer is read. Your program is behaving as expected.
To get what you want, you need to scan all the input before you produce any output.
Try this instead:
while (data != 0){
data = input.nextInt();
num[data]++;
}
for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.
while (input.hasNextInt()){
num[input.nextInt()]++;
}
it's so simple
int data = 0;
int[] num = new int[100];
int i = 0;
while (i < num.length) {
if ((data = input.nextInt()) == 0)
break;
num[i] = data;
i++;
}
for (i = 0; i < 100; ++i) {
int times = 0;
if (num[i] != 0) {
for (int j = 0; j < 100; j++) {
if (num[j] == 0) {
break;
} else if (num[i] == num[j]) {
times++;
}
}
System.out.println(num[i] + " occurs " + times + " times ");
} else {
break;
}
}

Categories