Odd and Even Numbers [duplicate] - java

This question already has an answer here:
Odds and Evens Applications
(1 answer)
Closed 8 years ago.
How can I display all the evens on one line and all the odds on the next line? need to display 25 integers.
public class OddsOrEvens
{
public static void main(String[] args)
{
int[] numbers = new int[25];
System.out.print ("EVENS & ODDS");
for(int i=0; i < 25; i++)
{
numbers [i] = (int) (Math.random()*99) + 1;
if(numbers[i]%2 == 0)
System.out.println(numbers[i] +" " );
else
System.out.println(numbers[i] +" " );
}
}
}

Instead of printing each number immediately, consider building up two strings (the first made up of the evens, and the second the odds). Then print the result strings when you're done. This should require just one loop.

In your providing code you print every number at time when it processed.if you want to print in one line so one possible solution is that you have store numbers in some array, or a string instead of display the number.
So in your code this line must change
System.out.println(numbers[i] +" ");
like this (if you want to store them in string variable)
even += numbers[i] +" ";
and later when loops end you can print out both line one by one.
Hope this will help you
//Snippet
if(numbers[i]%2 == 0)
even += numbers[i] +" ";
else
odd += numbers[i] +" ";
//after loops ends
System.out.println(even);
System.out.println(odd);

Just save all the evens in one array and all the odds in another and then print them seperately.

Well right now you are printing them all individually. what you could do is before the for loop declare a String for the odds and a String for the evens. and initialize them to "". then in the for loop instead of printing, just add the numbers[i] to the string and print them outside of the for loop

Alternatively ...
Read the javadoc for PrintStream, 'cos System.out is a PrintStream. Look at the different print methods available.

Create a string to hold them and just display them at once at the end:
public class OddsOrEvens
{
public static void main(String[] args)
{
int[] numbers = new int[25];
String evens = "";
String odds = "";
System.out.print ("EVENS & ODDS");
for(int i = 0; i < 25; i++)
{
numbers [i] = (int) (Math.random() * 99) + 1;
if(numbers[i] % 2 == 0)
evens += numbers[i] + " "; // save it to evens string
else
odds += numbers[i] + " "; // save it to odds string
}
// now print them
System.out.println("Evens: " + evens);
System.out.println("Odds: " + odds);
}
}

Related

How to sum integer inputs in Java, and display the results in an array at the end of the program?

I am trying to create a "calculator", except it needs to print each element that was used to compose the sum total. This printing of the array elements needs to happen at the end of the program, when the user inputs 0 twice in a row.
Upon entering an input, the integer values will be stored in an array. Once the end of the program has been reached, the contents of this array will be printed. However, if the end of the program has not been reached, the program continues while the user adds consecutive inputs.
Currently, the program will only print one element at a time, instead of every element that was used to calculate the total. I've spent hours trying to debug, and any guidance would be greatly appreciated!
import java.util.*;
public class AddingMachine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean justStarting = true;
int total = 0;
int subtotal = 0;
int input;
int last = 1;
int MAXIMUM_NUMBER_OF_INPUTS = 100;
while (true) {
input = scanner.nextInt();
if (input == 0) {
if (last == 0) {
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
subtotal += input;
last = input;
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; i++) {
numbers[i] = last;
}
System.out.println(Arrays.toString(numbers));
}
}
When summing the input in your loop, you could store the users input into a List of integers. Once you need to reprint them, you can iterate over the List and print the elements you stored.
Example:
List<Integer> storedUserInput = new ArrayList<>();
while (true) {
input = scanner.nextInt();
storedUserInput.add(input);
if (input == 0) {
if (last == 0) {
for(Integer i : storedUserInput){
System.out.print(i + " + ");
}
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
}
Within the while loop, the array is re-initialized each time:
int[] numbers = new int[args.length];
so any previously entered value is lost. Also, the purpose of the for loop within the while is not clear.
Also, unless using an array is a requirement, you really don't need an array. You could just use a StringBuffer and append the entered values.

How do I change a string array into an int array? [duplicate]

This question already has answers here:
How to convert string array to int array in java [duplicate]
(6 answers)
Closed 6 years ago.
I am making a code that stores sport scores and matches through user input however I have used a string array to store both string and int value - while this did not seem to be a problem at first I have realized that validation becomes tedious as you can equally store a string in the "score" section even though it is incorrect.
I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem.
The user input looks like this;
Home_Team : Away_Team : Home_ Score : Away Score
I want to be able to add all the Away/Home scores to produce an output like so;
Total Home score: x
Total Away Score: x
Here is my for loop so far,
for (int i = 0; i < counter; i++) { // A loop to control the Array
String[] words = football_list[i].split(":"); // Splits the input
if (words.length == 4) {
System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["+ words[3].trim() + "]");
}else{
System.out.println("Your input was not valid.");
matches--;
invalid++;
The logic for my new code will be "If Element[] does not contain an int value print "Invalid input"
"I wish to additionally record the amount of points scored from each team but I cannot add together two strings to get a int value, that's my problem."
To make an integer from a String, use this :
int x = Integer.parseInt( some_string );
Java Split String Into Array Of Integers Example
public class Test {
public static void main(String[] args) {
String sampleString = "101,203,405";
String[] stringArray = sampleString.split(",");
int[] intArray = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
String numberAsString = stringArray[i];
intArray[i] = Integer.parseInt(numberAsString);
}
System.out.println("Number of integers: " + intArray.length);
System.out.println("The integers are:");
for (int number : intArray) {
System.out.println(number);
}
}
}
Here is the output of the code:
Number of integers: 3
The integers are:
101
203
405

Rearranging numbers using variable.charAt(). Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:

I have looked on other such answers with this error and I can't seem to figure out my code specifically. I am using Java, and I am trying to make a program where I enter a number as an input, and as an output I should get:
example input: 1234
The original number is 1234
The number in reverse is 4 3 2 1
I have this code written:
import java.util.Scanner; //Needed for Scanner class
public class CoeQuiz3
{
public static void main(String[] args)
{
//establish variables
String ogNumber;
int ogNumberInt;
Scanner keyboard = new Scanner(System.in); //establish scanner
System.out.println("Enter a positive integer greater than 0.");
ogNumber = keyboard.nextLine();
ogNumber = checknumber(ogNumber);
ogNumberInt = Integer.parseInt(ogNumber);
//print the original number
System.out.println("The original number is " + ogNumber);
//print the reverse number
int ogNumberLength = ogNumber.length();
int digitposition, ogDigit;
String reverseStatement = "The number reversed is ";
for (digitposition = ogNumberLength; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
System.out.println(reverseStatement);
it compiles and runs, but every time it gives me the error:
The original number is 1234
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of
range: 4
at java.lang.String.charAt(String.java:658)
at CoeQuiz3.main(CoeQuiz3.java:30)
It should work logically - what is the problem? This problem still occurs if I replace >= with >.
You are trying to access one past the highest available character index in your string. Try this loop instead:
for (int i=ogNumber.length()-1; i >=0; i--) {
char chr = ogNumber.charAt(i);
reverseStatement += chr;
}
System.out.println(reverseStatement);
But a nicer way to do this is to use the StringBuffer.reverse() method:
String ogNumberReversed = new StringBuffer(ogNumber).reverse();
for (int i=0; i < ogNumberReversed.length(); ++i) {
char chr = ogNumberReversed.charAt(i);
reverseStatement += chr;
}
System.out.println(reverseStatement);
Alternative solution:
int number = 1234;
String strReversed = new StringBuilder(String.valueOf(number)).reverse().toString().replace("", " ").trim();
System.out.println(strReversed); // 4 3 2 1
Ideone example
See this piece of code
for (digitposition = ogNumberLength; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
The first parameter of the loop digitposition = ogNumberLength
specifies that the loop should access the char at the position equal to length of the string, and in case of string, the length is equal to the number of characters (for e.g. length of string "HAPPY" would be 5 not 4). But the index of the last element of the String array is one less than the length of the string (as arrays are zero indexed).
So in practice if you have entered the number "1234":
length of string is = 4
position of last element array = 3
So your code is trying to access the element number 4 in an array of last index 3, hence the exception.
You should instead write the following (notice the -1 in the 1st parameter)
for (digitposition = ogNumberLength - 1; digitposition >= 0;
digitposition--)
{
ogDigit = ogNumber.charAt(digitposition);
reverseStatement += ogDigit + " ";
}
This would solve your problem, however if reversing only numbers is your sole objective then I would suggest use the following method as using strings is much more resource intensive
import java.util.Scanner;
class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
System.out.println("Reverse of entered number is "+reverse);
}
}
Cheers!!!
Please change your for-loop as follows:
for (digitposition = ogNumberLength-1; digitposition >= 0; digitposition--){
ogDigit = Character.getNumericValue(ogNumber.charAt(digitposition));
reverseStatement += ogDigit + " ";
}
and see the results.
There are two things which have been added:
The for loop counter should start from ogNumberLength-1 not
ogNumberLength. This was the reason for
java.lang.StringIndexOutOfBoundsException
There is a need to convert the ASCII value of char to number. That is why
Character.getNumericValue() has been used.
Hope, it helps!

Finding the middle element of an array

Java newbie here.
I have the following code from which I would want it to return the middle elements of the array. How do I go about that? I don't want to just manually return the elements at position 5 and 6, which are the median elements here. I would it in a way that would work for any array type, even or odd.
/**
* Created by root on 2/11/15.
*/
import java.util.Scanner;
import java.util.Arrays;
public class test {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Create a string array to store the names
String arrayOfNames[] = new String[10];
System.out.print("Enter 10 names\n");
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("\n" + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
//show name one by one
Arrays.sort(arrayOfNames);
System.out.print("Names ");
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("" + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Write a method like :
void printMiddleofArray(String[] arrayOfNames) {
if (arrayOfNames.length %2 ==0)
{
System.out.println(arrayOfNames[arrayOfNames.length /2]);
System.out.println(arrayOfNames[(arrayOfNames.length /2)-1]);
} else {
System.out.println(arrayOfNames[(arrayOfNames.length /2)-1]);
}
}
Here is another solution step by step. It is less elegant of course, but tailored for beginners. It uses the modulus operator to check for even or odd lengths, adjusts for using zero indexed arrays, then makes a decision based on the outcome.
In main() declare a String and initialize it with a call to this method, with your names array passed in as a parameter. Then in the next line, print the String.
public String returnMiddleElement( String[] input ){
/* Initialize result variable */
String result = "";
/* Determine if the array is odd or even */
int value = input.length % 2;
/* Obtain the middle index */
int middleIndex = input.length/2;
/* Adjust for the zero index of arrays */
int evenMid = middleIndex - 1;
if( value == 0 ){
/* The array is even, so obtain the two middle elements */
result += input[evenMid] + "\n" + input[(evenMid+1)];
}
else{
/* The array is odd, so obtain the single middle element */
result += input[middleIndex];
}
return result;
}

Printing text with spacing recursively

This is an assignment for school. I am having trouble understanding how I can print the following recursively:
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
This ALSO written by call number 4.
This ALSO written by call number 3.
This ALSO written by call number 2.
This ALSO written by call number 1.
I'm not sure if I am supposed to be illustrating a loop vs. recursion or if there is a way to print all of this recursively. Additionally, how would I go about reversing the recursion call so it starts from 4 as per the example output?
This is my current output.
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
This ALSO written by call number 1.
This ALSO written by call number 2.
This ALSO written by call number 3.
This ALSO written by call number 4.
There is no spacing implemented in the for loop yet b/c I'm not sure if that part is also supposed to be recursive.
My code:
public class Recursion {
public static void main(String[] args) {
for (int i = 2; i < 5; i++) {
System.out.println("This was written by call number " + i + ".");
}
recurse(4);
}
public static void recurse(int n) {
String temp = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (n < 2) {
System.out.println("This ALSO written by call number " + n + ".");
}
else {
recurse(n - 1);
System.out.println(temp + "This ALSO written by call number " + n + ".");
}
}
A simpler solution.
public static void main(String[] args) {
recurse(1);
}
public static void recurse (int n) {
if (n==5) return;
String temp="";
for (int i=0;i<n;i++) temp += " ";
if (n!=1) {
System.out.println(temp + "This was written by call number " + n + ".");
}
recurse(n+1);
temp=" ";
for (int i=0;i<n;i++) temp += " ";
System.out.println(temp + "This ALSO was written by call number " + n + ".");
}
The key to writing most recursive programs (especially the ones you're given as assignments) is to look for a larger problem that contains a similar but smaller occurrence of the same problem.
In your case, the "larger problem" would be to print the 6 lines that start and end with "call number 2". That is, print lines for call numbers 2 through 4. The way to do this is: print the first line that says "call number 2", solve the problem to print the 4 lines for call numbers 3 through 4, and print the last line that says "call number 2". The part in the middle is the smaller occurrence of the same problem. That's going to be the recursive call.
Since your larger problem is going to start with "call number 2", and your smaller problem is going to start with the call number that's one higher, I'd recommend arranging things so that you call recurse(n+1) instead of recurse(n-1). If you do that, you'll need a second parameter so that you know when to stop recursing--something like recurse(n+1, last).
Hopefully this will be enough to get you thinking on the right track.
Try this:
public static void main(String[] args) {
recurse(1, true, 1);
}
public static void recurse(int n, boolean loop, int add) {
String temp = "";
String out = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (add > 0) {
out = temp + "This was written by call number ";
} else {
out = temp + "This ALSO written by call number ";
}
if (n == 1 && !loop) {
System.out.println(out + n + ".");
return;
} else if (n == 1) {
recurse(n+add, false, add);
} else if (n == 5) {
add = add - 2 * add;
recurse(n+add, false, add);
} else {
System.out.println(out + n + ".");
recurse(n+add, false, add);
}
}
Here is quite a straightforward solution. Also pay attention how you can easily get the indent string (via substring). The recursion is as simple as it gets: print the number, enter the function with a larger number if below the max, then follow back.
class R{
static final String spaces=" ";
public static void main(String[] args) {
rec3(1,4);
}
private static void rec3(int i, int max) {
if (i>1) System.out.printf("%sThis was written by call number: %d%n", spaces.substring(0, i-1), i);
if (i<max) rec3(i+1, max);
System.out.printf("%sThis was ALSO written by call number: %d%n", spaces.substring(0, i-1), i);
}
}
Thanks to everyone for the help. I ended up modifying the solution from #JoseLuis a little bit.
public class Recursion {
public static void main(String[] args) {
recurse(1, 5);
}
public static void recurse(int n, int max) {
String temp = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (n == max) {
return;
}
if (n != 1) {
System.out.println(temp + "This was written by call number " + n + ".");
}
recurse(n + 1, max);
System.out.println(temp + "This ALSO was written by call number " + n + ".");
}
}

Categories