println/print and spacing (beginning java) - java

My programming assignment was to print an array with 10 random integers and then have 4 lines with different outputs (every even element, reverse order, etc.)
The code itself works fine (as far as I can tell) but one problem I'm having is that I had to put a System.out.println(""); before every line in order for the lines to look correct.
Initially, when I had it System.out.println("[LINE 1]....") *for loop * System.out.print("arr[i] + ", ") *close for loop * it printed each integer on a separate line instead of all on one line. Am I missing something here?? Can anyone help?
Here's my code:
import java.util.*;
public class RandomInteger {
public static void main(String[] args){
Random random = new Random();
int arr[]=new int[10];
System.out.print("The array of random numbers: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(50);
System.out.print(arr[i] + ", ");
}
System.out.println("");
System.out.print("[LINE 1] Elements at an even index: ");
for (int i = 0; i < arr.length; i++) {
if(i%2==0){
System.out.print(arr[i]+" (at index "+i + "), ");
}
}
System.out.println("");
System.out.print("[LINE 2] Every even element:");
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0){
System.out.print(arr[i] + ", ");
}
}
System.out.println("");
System.out.print("[LINE 3] Elements in reverse order: ");
for(int i=arr.length-1;i>=0;i--){
System.out.print(arr[i] + ", ");
}
System.out.println("");
System.out.print("[LINE 4] First Element is: "+arr[0]+" and Last ELement is: "+arr[arr.length-1]);
}
}

All overloads of the println method append a newline following whatever you want to print; all overloads of the print method don't.
If all you want is a newline, then you don't even have to supply an argument -- call the no-argument println overload.
System.out.println();

Can you try with this exemple:
System.out.print("\n[LINE 2] Every even element:");
You have write \n because it is a simple way to introduce a newline although the right way isn't with system.out.print, the right way to this format is system.out.format like to c lenguage, but also used

I guess you want to remove the code System.out.println("").
use "\n"
You can change System.out.print("[LINE 1] Elements at an even index: ") to System.out.print("\n[LINE 1] Elements at an even index: ").

Related

Displaying a pyramid

I have this task to display a pyramid as follows:
I wrote the code but unfortunately, the digits are displayed with spaces and order.
public class DisplayPyramid {
//main method declaration. Program entry point which begins its execution
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Prompt the user to enter an integer (number of lines)
System.out.print("Enter the number of lines: ");
int numbers = input.nextInt(); //Read value from keyboard and assign it to numberOfLines
String padding = " ";
//Display pyramid
//for loop to produce each row
for (int rows = 0; rows < numbers ; rows++) {
for (int k = numbers - rows; k >= 1; k--){
System.out.print(k + " ");
}
for (int l = 2; l <= numbers - rows; l++){
System.out.print(" " + l);
}
//Advance to the next line at the end of each rows
System.out.print("\n");
}
} }
And this is my output:
Can you help me figure out what is wrong with code ?
Anyone's help will be much appreciated.
Consider the 1st pass of the outer loop which produces
If we color hint your code, which the first inner loop in red, the second inner loop in green
This will be their corresponding output for each pass
The last pass of the red loop print "1 " and the first pass of green loop print " 2". They combine and become "1 2", which has 2 spaces in between.
The solution as Osama A.R point out, just reverse the printing order of number and space for the green loop and make if follow the red loop pattern. That will make the sequence neat.
Your second for loop prints the spaces first and then the number, however, the spaces have already been added by the first for loop, so just update the second for loop to print the spaces after printing the number.
E.g. your second loop should be like this:
for (int l = 2; l <= numbers - rows; l++){
System.out.print(l + " ");
}

Bubble sorting issues in java

So I currently am having, this issue when I run my program it repeats the second display line. ("unsorted line")
I also am having trouble with the alignment when I run the program
What I need this program to do:
Generate 10 random integer numbers between 1 and 100, and place each random number in a different element of a single-dimension array starting with the first number generated.
Locate the largest of the 10 numbers and display its value.
Display the array's contents in the order the numbers are initially inserted. This is called an unsorted list.
Using the bubble sort, now sort the array from smallest integer to the largest. The bubble sort must be in its own method; it cannot be in the main method.
This is what I currently have programmed.. I just need help on adjustments when its ran.
import java.util.Arrays;
public class Chpt7_Project2 {
//Ashley Snyder
public static void main(String[] args) {
//create an array of 10 integers
int[] list = new int[10];
//initialize array of 10 random integers between 0 and 100
for (int i = 0; i < list.length; i++) {
list[i] = (int) (Math.random() * 100 + 1);
}
//Find the maximum of the list of random numbers generated
int maximum = -1;
int minimum = 999;
for (int i = 0; i < list.length; i++) {
if (maximum < list[i])
maximum = list[i];
if (minimum > list[i])
minimum = list[i];
}
//Display the maximum from the randTen array
System.out.println("The largest value is: " + maximum);
//Display the unsorted list of numbers from the randTen array
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + "The unsorted list is: ");
}
//Display the sorted array numbers
bubbleSort(list);
System.out.println("The sorted list is: " + Arrays.toString(list) + " ");
}
public static void bubbleSort(int[] list) {
//Sort randomly generated integers in randArray from lowest to highest
int temp;
for (int i = list.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
You're really close to making this work. Please notice that System.out.print("The unsorted list is: " + list[i]); is inside a loop. That means that "The unsorted list is" will print 10 times. You probably want to move the label part of the output before the loop while keeping the list[i] inside the loop. Then don't forget to put a System.out.println after the loop finishes. You will then see that each item is pushed together. To fix that just put list[i] + " " as part of the print.
It appears that your are a bit confused about two separate items. First is writing (printing) to the console. System.out.print("whatever"); and System.out.println("something");. The first one will write a line of text to the console but will not go to the next line. The second one writes and then goes (advances) to the next line.
Secondly, and really importantly is for. Whenever you see for (...) { whatever }; think that something (the whatever) is going to be repeated. The number of times that it will repeat is mostly / usually determined by the part in parenthesis. The thing that is repeated is between the braces {}.
I think this is what you want:
//Display the unsorted list of numbers from the randTen array
System.out.print("The unsorted list is: ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.println();
Please notice that the first System.out.print does not output to a new line, nor does the second one. The second System.output.print is repeated 10 times. Finally, System.out.println() starts a new line of output.

Print sum of unique values of an integer array in Java

I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;

How to print integer arrays horizontally?

This block of code is supposed to sort the numbers in ascending order but it outputs vertically, how can I output them horizontally?
Example Output:
1st array: 1 2 3
2nd array: 3 4 5
3rd array: 3 4 6
int[] i1 = new int[]{3, 2, 1};
Arrays.sort(i1);
System.out.print("1st array : ");
for(int index=0; index < i1.length ; index++)
System.out.print(" " + i1[index]);
int[] i2 = new int[]{5, 4, 3};
Arrays.sort(i2);
System.out.println("2nd array : ");
for(int index=0; index < i2.length ; index++)
System.out.print(" " + i1[index]);
int[] i3 = new int[]{6, 3, 4};
Arrays.sort(i3);
System.out.print("3nd array : ");
for(int index=0; index < i3.length ; index++)
System.out.println(" " + i3[index]);
It is because you are using System.out.println. It means that it goes to the next line, it works like if you add a line break at the final of the String. Change it for System.out.print to print all your code in a line.
For example, using System.out.println:
Code
System.out.println("Hello");
System.out.println("World");
Output
Hello
World
Now using System.out.print:
Code
System.out.print("Hello");
System.out.print("World");
Output
HelloWorld
Finally using System.out.print and String with \n:
Code
String string = "Hello\nWorld";
System.out.print(string);
Output
Hello
World
Look that using \n and System.out.println have the same behaviour.
You should use System.out.print instead of System.out.println. The last one appends a line break at the end of the argument. The line break character(s) is(are) the one(s) that make a new line appears on your output.
Use StringBuilder to create a new "row" or System.out.print() to print to the same line
Something like this:
System.out.print("1st array : ");
for(int index=0; index < i1.length ; index++)
System.out.print(" " + i1[index]);

Enhanced For Loop Exception [duplicate]

This question already has answers here:
Enhanced 'for' loop causes an ArrayIndexOutOfBoundsException
(2 answers)
Closed 5 years ago.
Created the below code whilst playing with loops. The code below stores the Fibonacci values into an array and then prints them using for loops.
int [] numbers;
numbers = new int[25];
numbers[0] = 1;
numbers[1] = 1;
System.out.println("Initializing the array values");
for(int i = 2; i < numbers.length; i++)
{
numbers[i] = numbers[i-1] + numbers[i-2];
}
System.out.println("Printing out Fibonacci values");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + ", ");
}
The above code works fine. The first time I threw it together though, I used an enhanced for loop to print out the values (the second for loop in the code). This compiles fine, but when I run it I get the following;
Initializing the array values
Printing out Fibonacci values
1, 1, 2, 3, 8, 34, 377, 17711, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 34
at ArrayDemo.main(ArrayDemo.java:21)
I don't get what went wrong. Changing the second loop shouldn't change the values (you'll notice the fibonacci values are wrong (ie missing values)). And I don't get why a simple enhanced for loop would skip indexes. Now, this isn't really a big deal because this isn't for a project or anything, it just bugs me that I can't figure out why it's doing it. Any clues?
The enhanced for loop just looked like this;
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
i here is the elements in the array, not the indexes. It could be bigger than numbers.length.
For example, if numbers = {1,2,3,9} then i will be 1, 2, 3, 9. But its length is 4, so when you loop on the elements inside it, you're trying to do numbers[9] which exceeds its size.
You probably want to System.out.print(i + ", ");
for(int i = 0; i <= numbers.length; i++) should be
for(int i = 0; i < numbers.length; i++)
In java, arrays are 0 based indexing. It means that your first element should be accessed at the index 0 and obviously the last at the length of your array minus 1.
int tab[] = new int[3]; //tab of length 3
tab[0] = 11;
tab[1] = 24;
tab[2] = 5;
Here you access the last element by calling tab[2] or tab[tab.length-1], which is equivalent.
Apologies, that was just a mistake in the code I put up in the
question.
The problem is that you should do : System.out.print(i + ", ");
You should read this and this about enhanced for loop.
The for statement also has another form designed for iteration through
Collections and arrays This form is sometimes referred to as the
enhanced for statement, and can be used to make your loops more
compact and easy to read. To demonstrate, consider the following
array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array.
So item holds the current value from the numbers array and not the current index. That's why you get an IOOBE.
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
should be
for(int i : numbers)
{
System.out.print(i + ", ");
}
You don't need to use indexes in enhanced for-loop.

Categories

Resources