I have this question about how to write a method to fill an array with integers. I did this method, but I got confused on how to print it. Should I start with for loop in each method? And how should I print them on one line with a space between each number like this:[1 2 3 4 5 6 7 ... 50]?
public class Numbers {
public int[] numbers;
public Numbers() {
numbers = new int[50];
}
public void numSequence() { // filling the array with sequence of integers.
for(int i = 0; i < 50; i++) {
numbers[i] = i;
}
}
public void printArray() { // printing the array
// do I need for loop here
for(int i = 0; i < 50; i++) {
System.out.print(i+1);
}
}
public static void main(String[] args){
Numbers d = new Numbers();
d.numSequence();
d.printArray();
}
}
Your printArray method is not printing the array. It's printing the indices of the for loop. So first of all, print the actual array values.
Also with that print, you can add your own spaces after each letter.
E.g.
public void printArray() { // printing the array
System.out.print("["); // not in loop
for(int i = 0; i < numbers.length; i++) { // loop through numbers array
System.out.print(numbers[i]); // print the element in the array
if (i != numbers.length - 1) { // not the last element, so print a space
System.out.print(" ");
}
}
System.out.print("]"); // not in loop
}
But then you will run into an issue. Because when you created your numbers array, you started at 0, not 1. Now, you could fix this by adding 1 to the numbers array like you did in your question. But that's bad practice, since you could have just created your array properly in the first place. So change your numSequence method to this:
public void numSequence() { // filling the array with sequence of integers.
for(int i = 1; i <= 50; i++) { // starts at 1, and <= 50 so it adds 50 too
numbers[i] = i;
}
}
Not necessary to create a class to do this kind of stuff. The example code in Java 8 is something like:
Stream<Integer> stream = Stream.iterate(1, t-> t + 1);
System.out.println(Arrays.toString(stream.limit(50).toArray()));
If you insist on using the printArray method, please take a look at the implementation of Arrays#toString. Basically you have to use StringBuilder to concatenate the array items.
I am not going in detail ,i will just patch up your code,
public class Numbers {
public int[] numbers;
public Numbers() {
numbers = new int[50];
}
public void numSequence() { // filling the array with sequence of integers.
for(int i = 0; i < 50; i++) {
//Add i+1 here o when we print we get 1 2 3 ....50
numbers[i] = i+1;
}
}
public void printArray() { // printing the array
// Use numbers.length instead of 50.
for(int i = 0; i < numbers.length; i++) {
//Print the values inside the array numbers
System.out.print(numbers[i]+" ");
}
}
public static void main(String[] args){
Numbers d = new Numbers();
d.numSequence();
d.printArray();
}
}
Tip : You can make the Program more scalable by using this method instead of yours and access it as d.numSequence(100) this will print 1 2 3 ...100
public void numSequence(int theNumberLimit) {
for(int i = 0; i < theNumberLimit; i++) {
numbers[i] = i+1;
}
}
Thank you hope this helps
Related
I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}
I have to display this random number generated array for class both vertically and horizontally. This is what I have so far...
public class chapterEightHW {
// Global Scanner/Array/RandomGenerator
private static final Scanner keyboard = new Scanner(System.in);
private static int[] array = new int[10];
private static int SecureRandom generator = new SecureRandom();
// Initialize Array
public static void initializeArray() {
for (int i = 0; i < array.length; i++) { // initialize Array
array[i] = 10 + generator.nextInt(99);
}
}
// Display Array Horizontally with space betweeen #'s
public static int displayArrayHoriz() {
System.out.printf("%s%n%n", Arrays.toString(array)); // display array
}
// Display Array Vertically
public static int displayArrayVert() {
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
System.out.println(array[3]);
System.out.println(array[4]);
System.out.println(array[5]);
System.out.println(array[6]);
System.out.println(array[7]);
System.out.println(array[8]);
System.out.println(array[9]);
}
Is there at better way to display the vertical version of the array other than 10 print statements?
You could use a loop like:
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Alternatively, you could iterate through the array and build a string using StringBuilder:
StringBuilder str = new StringBuilder();
for (int i = 0; i < array.length; i++) {
str.append(array[i] + "\n");
}
System.out.println(str.toString());
You can use a for each loop since you only need the value and not the index.
for(int x: array) {
System.out.println(x);
}
You could also use a Stream.
java.util.Arrays.stream(array).forEach(System.out::println);
You can make a for loop to print through the array elements the same exact way you initialized the array; in fact, you can even do it in the same for loop you made earlier.
for (int i = 0; i < array.length; i++) { // initialize Array
array[i] = 10 + generator.nextInt(99);
System.out.println(array[i]); // prints out array element right after it is initialized
}
While running this code I am getting ArrayIndexOutOfBoundsException.
public class Evensum {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
//Insert your code here
for(j=0; j<=num; j++) {
if(num%2==0) {
even[j]=num;
sum=sum+num;
args[j]= Integer.toString(num);
}
evennums=String.join(",", args);
}
System.out.println(evennums);
System.out.println(sum);
}
}
for (j=0; j<=num; j++)
This is wrong. It should be:
for (j = 0; j < num; j++)
Why? Assume num is 5. Before this line you initialized even to 5. The indices of even would be 0, 1, 2, 3, 4.
Now, with j<=num, you are trying to access the index 5, which does not exist and hence the exception.
args[j]= Integer.toString(num);
This line will raise another exception. I am assuming you're only passing one parameter from the command line which is args[0]. This means the args array is of size 1 and you cannot add more elements to it.
Also, it is not a good practice to add/modify elements to the args array. You should create a new array for this.
Please find the much simpler version of the Code by avoiding the Integer.toString and String.join to pass on the Arguments. Simple Integer Arraylist and adding the elements to will do the Trick.
package com.umapathy.java.learning.programs;
import java.util.ArrayList;
import java.util.List;
public class EvenSum
{
public static void main(String[] args)
{
int num = 20; //Initialize the user-defined value for the loop execution
int sum = 0 ; //Initialize the Sum Value as 0
List<Integer> evenlist = new ArrayList<Integer>(); //Define an integer
Array list
for (int i=2; i<=num; i++) //Begin the loop from the value of 2
{
if(i%2==0) //Logic to find whether a given number is Even Number or not
{
sum = sum + i; // If the logic returns true, Calculate the Sum Value
evenlist.add(i); // Add the Integer to the previous defined Integer
// Arraylist by calling add method
}
}
System.out.println(evenlist); // Print the Output outside the loops
System.out.println(sum);
}
}
Output Generated as follows:--
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 110
package javaApp;
public class EvenSum {
public static void main(String[] args) {
int num = 20;
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
for(j=1; j<=num; j++) {
if(j%2==0) {
sum=sum+j;
evennums=evennums+","+j;
}
}
evennums=evennums.replaceFirst(",","");
System.out.println(evennums);
System.out.println(sum);
}
}
Why initialized the even array size if its actual length is unknown in initially. It's better to go with ArrayList in this case which have characteristic to grow dynamically.
Try in this way
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
List<Integer> evens = new ArrayList<Integer>();
int sum = 0;
for (int j = 0; j <= num; j++) {
if (j % 2 == 0) {
sum += j;
evens.add(j);
}
}
System.out.println("Even Numbers List : "+evens);
System.out.println("Total Sum : "+sum);
// If you want an array of int instead of ArrayList you can convert ArrayList into int[] with following two lines
int evenArray[] = even.stream().mapToInt(x->x).toArray();
System.out.println("Even Numbers Array : "+evenArray);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Args: "+args[0]);
int num = Integer.parseInt(args[0]);
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
//Insert your code here
for(j=0; j<=num; j++) {
if(j%2==0) {
//even[j]=num;
sum=sum+j;
if(j!=0) evennums=evennums+","+j;
}
}
evennums=evennums.substring(1);
System.out.println(evennums);
System.out.println(sum);
}
At time of running in eclipse follow below steps:
Right click on class--> Run AS --> Run Configuration
Go to Arguments tab and pass value as 10
Click Run
Output:
2,4,6,8,10
30
Trying to make a HIT(x). when Hit called it decreases the elements( which are greater than x) of array by one and then print the array. and x is also an array which contains some element. For example. AR[7 4 5 3] and x= [4 2 5] then output is [5 3 4 2]. I am trying but not getting the relevant output. my code terminates only after taking the array element.
import java.util.Scanner;
public class Kom1 {
static int[] array;
public void hit(int x) {
for (int i = 0; i < array.length; i++) {
if (array[i] > x) {
array[i] --;
}
}
printArray();
}
public void printArray() {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int maxElements = scanner.nextInt();
array = new int[maxElements];
for (int i = 0; i < maxElements; i++) {
array[i] = scanner.nextInt();
}
}
}
Your algorithm should be like this
for(int i=0;i<x.length;i++){
for(int j=0;j<array.length;j++){
if(array[j]>x[i]){
array[j]--;
}
}
}
Things you missed
x is a array of elements. but you are using as single integer value
you haven't define or get x
your main method don't have a calling methods for processing
I have basically finished this piece of code, but when I print out the numbers from the array in the lottery class, I get a bunch of seeming gibberish. How can I fix the problem?
import java.util.Scanner;
public class Hw5pr2
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int[] rand = new int[5];
System.out.println("please enter 5 number");
for (int a = 0; a<rand.length; a++)
{
rand[a] = kb.nextInt();
}
Lottery k = new Lottery();
System.out.print("your number are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(rand[a]+",");
}
System.out.print("The Winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()+",");
}
System.out.println("you have " + k.RanInput(rand) + " matching number!!");
}
}
import java.util.Random;
public class Lottery
{
private int[] lotteryNumbers = new int[5];
public Lottery()
{
Random rand = new Random();
for (int a = 0; a<lotteryNumbers.length; a++)
{
lotteryNumbers[a] = rand.nextInt(9)+1;
}
}
public int RanInput(int[] Inran)
{
int b = 0;
for (int a = 0; a<lotteryNumbers.length; a++)
{
if (lotteryNumbers[a] == Inran[a])
{
b++;
}
}
return b;
}
public int[] getArray()
{
return lotteryNumbers;
}
}
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()+","); //k.getArray() which returns you an entire array
}
You are trying to print the entire array. That's why it may show you the reference instead. You can store the array in a temp array and print the contents of that array.
You may try doing something like this:
int[] winningNum = k.getArray();
for (int a = 0; a < winningNum.length; a++)
System.out.print(winningNum[a] + ",");
try something like
System.out.print("The Winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()[a]+",");
}
note here
for (int a = 0; a<lotteryNumbers.length; a++)
{
if (lotteryNumbers[a] == Inran[a])
{
b++;
}
}
return b;
this is always return lotteryNumbers.length-1; beacause always two arrays are same
When you print out the array, to the best of my knowledge, it calls the toString method.
This returns a hash of the object, not the values it contains. You can call the static method toString from the Arrays class also to print the string values of the array.
System.out.print(Arrays.toString(k.getArray())+",");
or use a for loop
for (int a = 0; a < k.getArray().length; a++)
{
System.out.print(k.getArray()[a]+",");
}
A few things to note:
As others have mentioned, if you want to print the elements of an array, a simple way to do it is with a for loop. Your code won't work the way you want it to unless you access each element of k's lotteryNumbers array separately:
System.out.print("The winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()[a]); //make sure to include the [a]
if(a != rand.length - 1) //added to help make prints more readable
System.out.print(", ");
}
Secondly, your RanInput function won't behave the way you want it to, assuming you wanted to see how many of the user's numbers match the lottery numbers. Currently, it just checks if the nth number inputted matches the nth lotto number chosen, which is unlikely to be true. Instead, you should do something like this:
public int RanInput(int[] Inran)
{
int count = 0;
for (int i = 0; i<lotteryNumbers.length; i++)
{
for(int j = 0; j < lotteryNumbers.length; j++) {
if (lotteryNumbers[j] == Inran[i])
{
count++;
}
}
}
return count;
}
It compares each of the inputted numbers with each of the lotto numbers. There are more efficient ways to do this than the code above, but I think it should be good enough for now.
I don't think the code you use to generate the lottery numbers account for duplicates (e.g. the numbers might be 1, 2, 2, 1, 3) so you should fix that.
Finally, here's some error checking you should implement if you want to be thorough:
make sure the user inputs exactly 5 numbers
all positive integers
are below some upper bound (say, 100)