Array java help needed - java

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;
}
}

Related

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);

How to make this programm to count the odd and even numbers in an array?(eclipse)

Thanks for the answers guys, didn't expect getting answers so fast.
Ok so in this code at the final stage it is meant to count how many odd and evens numbers there are in the array length you decide.
If you for example type in 10 it prints out 10 random numbers between the intervall of 0-999 and then it seperates the odd and even numbers
In the last stage it's meant to calculate how many odd and even numbers there are like ''out of the 10 numbers 4 of them were even numbers and 6 were odd numbers''
Right now in the last stage it just prints out numbers randomly and doesen't calculate how many odd and even numbers there are. I don't know how to fix it.
I have ran out of ideas about it so hopefully someone here can make it work properly.
import java.util.Scanner;
public class Uppgift4 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length;
while (true)
{
System.out.print(" \n\nHow many numbers do you want in the intervall 0-999?(turn off with -1 or 1000):");
length = scan.nextInt();
if (length>999)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
if (length<0)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
System.out.println("\n Here are the random numbers:");
int [] ar1 = new int[length];
for(int i = 0; i < length; i++) {
ar1[i] = (int)(Math.random() * 1000);
{
System.out.print(" "+ar1[i]);
}
}
System.out.println(" \n");
System.out.println(" Here are the numbers divided between even and odd numbers:");
System.out.print(" ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.print("- ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 != 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.println(" \n");
System.out.print(" Of the above numbers "+ length + " so ");
System.out.print("where ");
for(int evennumbers = 1 ; evennumbers < length ; evennumbers++)
{
if(ar1[evennumbers] % 2 == 0)
{
System.out.print(evennumbers+" ");
}
}
System.out.print(" of the numbers even and odd numbers were ");
for(int oddnumbers = 1 ; oddnumbers < length ; oddnumbers++)
{
if(ar1[oddnumbers] % 2 != 0)
{
System.out.print(oddnumbers+" ");
}
}
}
}
You need to count the number of even and odd number:
int even = 0;
int odd = 0;
// Loop through the final array
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
even++;
} else {
odd++;
}
}
Even simpler:
for(int i = 0 ; i < length ; i++)
{
odd += (ar1[i] % 2)
}
even = length - odd;
just make two global variables to count the odd and even and put them into the condition where you are checking for odd and even.
code
Why not just make use of bitwise AND and remove those conditionals like so:
int odd = 0;
int even = 0;
for(int i=0;i<length;i++){
odd+=ar1[i]&1;
even+=((ar1[i]+1)&1);
}
you can use this way , very simple
public static void main(String []args){
Integer[] arr = new Integer[] { 1,2,3,4,5};
int oddCount =0; int evenCount=0;
for ( int i=0; i< arr.length ;i++){
if( ( arr[i] % 2) == 0 )
evenCount++;
if( arr[i] % 2 != 0 )
oddCount++;
}
System.out.println( "oddCount in Array :" + oddCount + " EvenCount in Array : " + evenCount);
}

For loop printing an unexpected number of times

public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.print("Please enter five numbers. \na=");
array[0] = input.nextInt();
System.out.print("\nb=");
array[1] = input.nextInt();
System.out.print("\nc=");
array[2] = input.nextInt();
System.out.print("\nd=");
array[3] = input.nextInt();
System.out.print("\ne=");
array[4] = input.nextInt();
boolean totalIsZero = false;
for (int i=0;i<array.length ;i++) {
for (int j=1;i>j ;j++ ) {
if ((array[i] + array[j])==0) {
System.out.println("The numbers " + array[i] + " and " + array[j] + " have a total sum equal to 0.");
totalIsZero = true;
}
}
}
if (!totalIsZero) {
System.out.print("None of the numbers have a total sum of 0 with each other. ");
}
}
Here is some simple code I just wrote. Its task is to check if the sum between every two numbers in an array (consisting of five numbers) is equal to zero.
The problem I have is that when there are two pairs of numbers, both equal to 0, at the end of the program there is a message for one of the pairs only, not for both, as I expected.
How can I fix that, so the user can read that there are two pairs of numbers equal to 0?
Not sure if this will work perfectly because I haven't tested it and I haven't used java in a while, but just create the array the same way you do it in your post, but try the rest for the actual bulk of the function.
// various input calls above^ to create array
int count = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = i + 1; j < array.length; j++)
{
if(array[i] + array[j] == 0)
{
System.out.println("The numbers " + array[i] + " and " +
array[j] +
" have a sum equal to zero.");
count++;
}
}
}
if(count == 0)
{
System.out.println("No sum between any numbers is equal to 0");
}

Java output in lines of ten

I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}

Find the Last Digit In An Array

I need to find the last digit in a array and see if it is equal to zero. Here is the code I'm using;
import java.util.Scanner;
public class NrOccurrence
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the integers between 1 and 100: ");
int[] numbers = new int[100], times = new int[100];
boolean zero = false;
while (zero == false)
{
for (int a = 0; a <= numbers.length; a++)
{
numbers[a] = scan.nextInt();
times[a]++;
if (numbers.equals(0))
{
zero = true;
}
}
}
for (int b = 0; b <= numbers.length; b++)
{
System.out.println(numbers[b] + " occurs " + times[b] + " times");
}
scan.close();
}
}
Create a method like this:
private boolean isLastItemZero(int[] numbers)
{
boolean isLastItemZero = false;
if ((numbers != null) && (numbers.length > 0))
{
isLastItemZero = numbers[numbers.length - 1] == 0;
}
return isLastItemZero;
}
And call it once you're done reading in all of the numbers from the user.
First of all for (int a = 0; a <= numbers.length; a++) will give youIndexOutOfBoundsException .Java uses 0 bases indexing which means that an array of size n has indices up to and including n-1. Change it tofor (int a = 0; a < numbers.length; a++) . Same thing here for (int b = 0; b <= numbers.length; b++)
Second i am not sure what you are trying to check here :
if (numbers.equals(0))
{
zero = true;
}
but you could simply do :
if(numbers[i] == 0);
Now if you wanna check if the last element in the array is 0you can simply do:
if(numbers[numbers.length - 1] == 0)
//do something
By definition, if the remainder of a number divided by 10 is 0, then the last digit must be 0. So you just need;
if(numbers[i] % 10 == 0) { zero = true; }
Hope this helps.

Categories