Printing Odd and Even Elements of an Array [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to write a program that reads a sequence of integers and divide it into two sequences. The values on odd positions will be the first sequence and the values of even positions will be the second sequence. The program prints the elements of the first sequence and then the elements of the second sequence separated by a single space. The first input value specifies the number of elements.
Input: 7 1 2 4 5 6 8 9
Expected Output: 1 4 6 9 2 5 8
My Output: 2 0
package twosequences;
import java.util.Scanner;
public class TwoSequences {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] values = new int[n];
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
}
int odd = 0;
int even = 0;
int i = 1;
if (i % 2 == 0) {
even = values[i];
} else {
odd = values[i];
}
i++;
System.out.printf("%d %d%n", odd, even);
}
}
I'm not sure why I'm outputting 2 0. Any suggestions?

You need two different loops to iterate over even and odd elements respectively to obtain the desired output.
for (i = 0 ; i < n ; i += 2) {
even = values[i];
System.out.printf("%d ", even);
}
for (i = 1 ; i < n ; i += 2) {
odd = values[i];
System.out.printf("%d ", odd);
}
Hope this helps.

Print the even-numbered elements in one loop; then use another loop to print the odd-numbered elements.
System.out.print(values[0]); // print by itself to avoid prepending " ".
for (int i = 2; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
for (int i = 1; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
System.out.println();

you take the second element of an array (2), and only for that one you are checking if it's even or not.
The result goes true for first 'if', and
even = 2;
, the if statement ends and odd stays as declares (0), that' why u got result like that.
If you want output whith more than 2 integers, you need to change
, where n would be all scanned even numbers.
Try to put a counter in first for loop, like
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
if(values[i]%2==0) evenCounter++;
}
Now to count odds just count values.length - evenCounter.
Also you do not need to make simple arrays like int[], you can go with
List<Integer> list = new ArrayList<>();
You will be able to add elements in for loop withour knowing how many elements you will be implementing.
Hope some of those helps.

Related

Sum of a sequence by using for and while loop [duplicate]

This question already has answers here:
Sum numbers using loop
(2 answers)
java for loop sum and average of range
(3 answers)
Closed 2 years ago.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Last Number ");
int inputedNumber = Integer.valueOf(scanner.nextInt());
int result = 0;
int outcome = 0;
for(int i = 0; i < inputedNumber; i++) {
result += ;
}
/*/*while (outcome <= inputedNumber) {
result += inputedNumber;
outcome++;
}*/
System.out.println(result);
}
}
I have a problem to understand what is wrong here, because I would like to solve the task , originally it should be (Implement a program, which calculates the sum 1+2+3+...+n where n is given as user input.) but it gives me another answer, please , pin out for me in a both way , to understand what I went wrong , because everything so far make sense for me , but code doesn't work as it should to be
You can try the code below:
for(int i = 1; i <= inputedNumber; i++) {
result += i;
}
Note: you should start with i=1 based on your requirement:
1+2+3+..+n
You need to replace result += ; with result += i;
For the first case. This is not a valid Java code, you should put a value/variable after += operator.
for (int i = 0; i < inputedNumber; i++) {
result += ;
}
If you put the variable i after it, and use i<= inputedNumber. You will get the expected answer.
for (int i = 0; i <= inputedNumber; i++) {
result += i;
}
In the second case, you are actually doing n*(n+1)
while (outcome <= inputedNumber) {
result += inputedNumber;
outcome++;
}
This can be tested as input the value as 2:
The first iteration:
outcome -> 0
inputedNumber -> 2
result -> 2
The second iteration:
outcome -> 1
inputedNumber -> 2
result -> 4
The third iteration:
outcome -> 2
inputedNumber -> 2
result -> 6
The fix is similar to what I suggested before. You could take this as an exercise.

Counting integers in an array; How to eliminate duplicate output strings

I am writing a program that outputs how many times each integer is found in an array of integers. I have accomplished this, however, i have duplicate output strings.
This is the output:
>run:
>Please enter integers from 0 to 100:
1
2
3
4
4
5
0
// 1 occurs 1 time //
2 occurs 1 time //
3 occurs 1 time //
4 occurs 2 times //
4 occurs 2 times //
5 occurs 1 time //
BUILD SUCCESSFUL (total time: 14 seconds)
So as you can see, "4 occurs 2 times" prints twice since it is found twice in the array.
I just need some direction on how to eliminate the duplicates. Anything would be greatly appreciated.
import java.util.*;
public class WorkSpace3 {
public static void main(String[] args) {
int i = 0;
int count = 0;
int key = 0;
System.out.print("Please enter integers from 0 to 100: ");
int[] myList = new int[100];
Scanner s = new Scanner(System.in);
for (i = 0; i < myList.length; i++)
{
myList[i] = s.nextInt();
if (myList[i] == 0)
break;
}
while (key < myList.length && myList[key] != 0) {
for (i = 0; i < myList.length; i++)
{
{ if (myList[i] == myList[key])
{ count++; } }
}
if (count == 1)
System.out.println(myList[key] + " occurs " + count + " time ");
if (count > 1)
System.out.println(myList[key] + " occurs " + count + " times ");
key++;
count = 0;
}
}
}
A simple approach that is available to you is to mark the elements that you have counted with zeros. This approach is not universal; it is valid only because you use zero to mark the end of the input sequence by end-user.
You would have to slightly modify your code to use this approach: rather than looking for zero in the while loop, set up a variable to mark the length of the sequence. Set it to myList.length at the beginning, and then reset to i at the break. Now you can walk the list up to this max count, do the counting, and then set zeros into elements that you have already counted.
See the set element:
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Making a set element from array You remove the duplicates.
try this using Map
Map<Integer,Integer> counts=new HashMap<Integer,Integer>();
for (i = 0; i < myList.length; i++) {
if(counts.contains(myList[i]){
counts.put(myList[i],++counts.get(myList[i]);
}else{
counts.put(myList[i],1);
}

Negative Arrays and Error Messages

//MY TASK IS TWO MERGE TO ARRAYS INTO ASCENDING ORDER.Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int one[]= new int[10000];
int two[]= new int[10000];
int lengthShort=0;
int lengthLong=0;
int a =0;
int b =0;
System.out.println("Enter the values for the first array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<one.length && scan.hasNext(); i++){
one[i] = scan.nextInt();
a++;
if(one[i]<0){
one[i]=0;
break;
}
}
int length1 = a-1;
System.out.println("Enter the values for the second array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<two.length && scan.hasNext(); i++){
two[i] = scan.nextInt();
b++;
if(two[i]<0){
two[i]=0;
break;
}
}
int lengthTwo = b-1;
int mergeOne[] = new int[length1];
for (int i = 0; i<mergeOne.length; i++){
mergeOne[i]=one[i];
}
int mergeTwo[] = new int[lengthTwo];
for (int i = 0; i<mergeTwo.length; i++){
mergeTwo[i]=two[i];
}
System.out.println("First Array:");
for(int i=0; i<mergeOne.length; i++){
System.out.print(mergeOne[i] + " ");
}
System.out.println("\nSecond Array:");
for(int i=0; i<mergeTwo.length; i++){
System.out.print(mergeTwo[i] + " ");
}
if(mergeOne.length<=mergeTwo.length){
lengthLong = mergeTwo.length;
lengthShort = mergeOne.length;
}
else if(mergeOne.length>=mergeTwo.length){
lengthShort = mergeTwo.length;
lengthLong = mergeOne.length;
}
int merged[] = new int[length1 + lengthTwo];
for(int i = 0; i<lengthShort; i++){
if(i==0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i] = mergeOne[i];
merged[i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i] = mergeTwo[i];
merged[i+1]= mergeOne[i];
}
}
else if(i>0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i+i] = mergeOne[i];
merged[i+i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i+i] = mergeTwo[i];
merged[i+i+1]= mergeOne[i];
}
}
}
if(mergeOne.length<mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeTwo[k];
}
}
if(mergeOne.length>mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeOne[k];
}
}
for(int i = 0; i<merged.length; i++){
if((i+1)==merged.length)
break;
if(merged[i]>merged[i+1]){
int temp = merged[i+1];
merged[i+1]=merged[i];
merged[i]= temp;
}
}
System.out.println("\nMerged array in order is: ");
for(int i = 0; i<merged.length; i++){
System.out.print(merged[i] + " ");
}
}
}
//My code compiles in drjava but I have two issues:
1) It doesn't order the numbers in ascending order
2) When I run it through the site I have to submit this on it gives me the message as follows:
Runtime Error
Exception in thread "main" java.lang.NegativeArraySizeException
at Main.main(Main.java:281)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
You'll need to rethink your merge algorithm. Suppose you input arrays are
1 5 10 50 100 500
2 4 6 8 10 12 14 16
You'll need to repeatedly decide which element is smaller to put into the output. So after selecting N elements, your output will look like
1 2 4 5 6 8 10 10 12 14
And you will need to have indexes pointing at the place in the input arrays you'll need to look at next:
1 5 10 50 100 500
^^
2 4 6 8 10 12 14 16
^^
As you can see, the indexes could be at very different places in the input arrays. However, your code does a lot of this:
if(mergeOne[i]<=mergeTwo[i]){
which means it's only comparing elements from the input that are in the same location. This doesn't work, and trying to swap elements in the output after the fact isn't good enough to get the job done.
Basically, instead of having one index and comparing the elements of the two input arrays at the same index, you'll need two indexes. I'll let you take it from there, but I think you can figure it out.
(And I have no idea why you're getting NegativeArraySizeException.)

Junit Testing error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have an assignment on arrays I'm working on and one of the questions is to write a code for a histogram.
The method histogram takes a positive number n indicating the number of divisions in which the span of the data is divided, and returns an array of integers of length n, where each element of the array contains the count of the elements that fall into this
division.
For example, if the data is (0:5; 1:2; 2:4; 9:8; 5:1; 10:5), then its span is
10:0 (from 0:5 to 10:5).
histogram(4) would divide this range into four segments:
0.5—3.0, 3.0—5.5, 5.5—8.0, and 8.0—10.5.
Inspecting the data, we see that 3 values fall in the first segment, 1 value in the second, 0 values in the third, and 2 values in the fourth. Therefore, the returned value is an array of length 4 containing the values (3; 1; 0; 2) in that order.
Note that the sum of the elements in the returned array is equal to the number of
elements in the data array.
here is my code:
#Override
public int[] histogram(int divisions) {
int[] range = new int[divisions];
double segment = span() / divisions;
for (int i = 0; i < data.length; i++) {
if (data[i] <= (smallestElement() + segment)) {
range[0] += 1;
}
if (data[i] <= (smallestElement() + (2 * segment))) {
range[1] += 1;
}
if (data[i] <= (smallestElement() + (3 * segment))) {
range[2] += 1;
}
if (data[i] <= (smallestElement() + (4 * segment))) {
range[3] += 1;
}
}
return range;
}
and here is my Junit test for my method:
#Test
public void testHistogram() {
double[] data = new double[3];
data = new double[]{0.5, 1.2, 2.4, 9.8, 5.1, 10.5};
int[] dat = new int[4];
dat = new int[]{3, 1, 0, 2};
DoubleArrayStatisticalOutcomes x = new DoubleArrayStatisticalOutcomes(data);
assertArrayEquals(dat, x.histogram(4));
}
the test is not passing. can someone tell me what I did wrong ?
You are incrementing all the histogram bins for each value. In your for loop, if a value is less than smallestValue() + segment, all the conditional statements are executed, not just the smallest it matches.
This makes your histogram cumulative. There are four elements total in the first two bins.
Add a continue statement in each if or make if 2-4 into else ifs.
Your function also breaks down the moment you pass a value not equal to 4 as the tests are hardcoded. Try something like (untested):
double lowerBound = smallestElement();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < divisions; j++) {
if (data[i] <= (lowerBound + (j+1) * segment)) {
range[j] += 1;
continue;
}
}
}

Random numbers in java does not work properly [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 want to create a lottery program that creates four random numbers, each between 0 and 9 (inclusive). This program asks user to guess four numbers and compares each user guesses to four random numbers and displays the won message as:
No matches 0 points
Any one digit matching 5 points
Any two digits matching 100 points
Any three digits matching 2,000 points
All four digits matching 1,000,000 points
My program runs but it has some logic errors. For example,the output should be:
Random numbers:2 3 3 4
Guess numbers: 1 2 5 7-->1 matching digit
Guess numbers: 3 5 7 3-->2 matching digits
Guess numbers: 3 3 3 1-->2 matching digits
Guess numbers: 3 3 3 3-->2 matching digits
public class Lottery
{
public static void main(String[] args) {
final int LIMIT=10;
int totalCount=0;
int totalPoint;
Random random=new Random(); //creating object of random class
Scanner input=new Scanner(System.in);//creating object of scanner class
//declaring two arrays
int[] guessNumber= new int[4];
int[] randomNumber=new int[4];
for(int i=0;i<4;i++)
{
randomNumber[i]=random.nextInt(LIMIT);//returns value between 0 to 9(inclusive)
}
for(int i=0;i<4;i++)
{
System.out.println("Enter your first guess number from 0 to 9:");
guessNumber[i]=input.nextInt();
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (randomNumber[i] == guessNumber[j])
{
++totalCount;
break;
}
}
}
if(totalCount == 1)
{
totalPoint=5;
}
else if(totalCount == 2)
{
totalPoint=100;
}
else if(totalCount == 3)
{
totalPoint=2000;
}
else if(totalCount == 4)
{
totalPoint=100000;
}
else
{
totalPoint=0;
}
//dispalying points
System.out.println("You have earned " +totalPoint+ "points!!");
}
}
Looks to me like the problem is that once you've matched a particular digit, you ought to be removing it from circulation so that multiple guesses of the same value don't count as matches. One solution is to use an ArrayList for the randomNumber's and remove them when there's a match. If you replace what's between your // declaring two arrays comment and your totalPoint assignment with the following it seems to do what you requested in terms of your example.
int guess;
ArrayList<Integer> randomNumber = new ArrayList<Integer>();
for (int i = 0; i < 4; i++) {
randomNumber.add(random.nextInt(LIMIT));
}
for (int i = 0; i < 4; i++) {
System.out.print("Enter your guess number from 0 to 9: ");
guess = input.nextInt();
for (int j = 0; j < randomNumber.size(); ++j) {
if (randomNumber.get(j) == guess) {
++totalCount;
randomNumber.remove(j);
break;
}
}
}
input.close();
Note that I've chosen to process each guess as it's read rather than store them in an array and process them later.
It looks like your overall logic is fine.
If I understand correctly, you just want a different output.
Use something like this for your output.
String guessNumbers = "";
String randomNumbers = "";
for (int i = 0; i < 4; i++){
randomNumbers += randomNumber[i]+" ";
guessNumbers += guessNumber[i]+" ";
}
System.out.println("Random numbers: "+randomNumbers);
System.out.println("Guess numbers: "+guessNumbers+" --> # of matching digits "+totalCount);
System.out.println("You have earned " +totalPoint+ " points!!");
This is what it now prints:
Random numbers: 2 9 7 4
Guess numbers: 7 4 5 2 --> # of matching digits 3
You have earned 2000 points!!

Categories

Resources