Error when trying to display an array in alphabetic order - java

I'm making a hotel booking system to be displayed through the console. The system should allow the user to select up to 10 room numbers (1-10) and give the customers name that is being booked in. Below I have put a method to keep all the rooms empty when the program is run.
private static void initialise(String hotelRef[]) {
for (int x = 1; x < 11; x++) {
hotelRef[x] = "EMPTY";
}
}
I can book rooms and view them but when i try to sort the array to be displayed in alphabetical order, it terminates the program with an error. (nullpointerexception in main thread).
Arrays.sort(hotel);
for (int x = 1; x < 11; x++) {
System.out.println(Arrays.toString(hotel));
}
Above is what I am currently trying but it doesn't reach the first line. Any idea on how I can display the array in order? Any help is greatly appreciated.
P.s forgot to mention the array is initialised at the start of the main method. The code above is in another method.
My main method:
public static void main(String[] args) {
String[] hotel = new String[11];
initialise(hotel);
Menu(hotel);
}

here is your Problem:
for (int x = 1; x < 11; x++) {
You use natural numbers for indexing within the array, But in Java indexes start with 0. Therefore the first element in your array is not initialized.
In turn when Arrays.sort(hotel) tries to invoke the equals() method on the element hotel[0] it raises a NullPointerException.
Solution:
Get used to zero based indexing.

First Your loop start from 1 to 11, so always the first valus is null :
[null, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY]
--^^------------------------------------------------------------------------
Second when you change your array you should to return it.
Your program should be like this :
public static void main(String[] args) {
String[] hotel = new String[11];
hotel = initialise(hotel);
Menu(hotel);
}
private static String[] initialise(String hotelRef[]) {
for (int x = 0; x < hotelRef.length; x++) {
hotelRef[x] = "EMPTY";
}
return hotelRef;
}
private static void Menu(String[] hotel) {
Arrays.sort(hotel);
for (int x = 0; x < hotel.length; x++) {
System.out.println(Arrays.toString(hotel));
}
}
Note
When you use the lenght don't use the length like this x < 11 this can make a problem if you change the size, so to avoid all this use arrayName.length instead like hotel.length

Array indexes are starting at 0 but your loop is starting at index 1. So hotel[0] is null.

Just, a problem on the for loop.
You have to start with 0 not 1 :
private static void initialise(String hotelRef[]) {
for (int x = 0; x < 10; x++) {
hotelRef[x] = "EMPTY";
}
}
Because, when you instantiate the hotel array like this :
String[] Hotel = new String[10]
you have 10 rooms starting with 0 to 9

Related

Arrays and For-loop - Incorrect output while printing Random elements

I am pretty new in this world, and I must say sometimes things that looks easy are pretty harsh.
I am stuck with a task that entails dealing with an array and for-loops.
I should iterate over the array and for every iteration step print a different random string. My current code is not working correctly, the only thing I'm getting a random item and the same index printed multiple times.
My output right now:
relax
2
2
2
2
How can I fix that and get a correct randomized output?
My code:
public static void main(String[] args) {
int i;
String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
java.util.Random randomGenerator = new java.util.Random();
int x = Cofee.length;
int y = randomGenerator.nextInt(x);
String frase = Cofee[y] ;
System.out.println(frase);
for(i = 0; i < Cofee.length; i++)
System.out.println(y);
}
You assign a value to y once, and you print y repeatedly. The value of y doesn't change. To do that, you would need to call randomGenerator.nextInt(x) for each iteration of the loop!
However, if you want to randomize and print the array, use:
public static void main(String[] args)
{
String[] coffee = {"pick it","drink it","relax","put it in a cup",};
// this wraps the array,
// so modifications to the list are also applied to the array
List<String> coffeeList = Arrays.asList(coffee);
Collections.shuffle(coffeeList);
for(String value : coffee)
System.out.println(value);
}
As an aside, don't use String coffee[], but use String[] coffee. Although Java allows putting the array type after the variable name, it is considered bad form.
Or use a list directly:
public static void main(String[] args)
{
List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
Collections.shuffle(coffeeList);
for(String value : coffeeList)
System.out.println(value);
}
For that, you can implement a shuffling algorithm.
It's not so scaring as it might sound at first. One of the famous classic shuffling algorithms, Fisher–Yates shuffle is relatively easy to grasp.
The core idea: iterate over the given array from 0 to the very last index, and for each index swap the element that corresponds to the randomly generated index between 0 and the current index (i) with the element under the current index.
Also, I would advise creating a separate array representing indices and shuffle it in order to preserve the array of string its initial state (you can omit this part and change the code accordingly if you don't need this).
That's how it might be implemented:
public static final Random RANDOM = new Random(); // we need an instance for random to generate indices
A Fisher–Yates shuffle implementation:
public static void shuffle(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
swap(arr, i, j); // swapping elements `i` and `j`
}
}
Helper-method for swapping elements:
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Usage-example:
String[] coffee = {"pick it","drink it","relax","put it in a cup"};
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
shuffle(indices);
for (int i = 0; i < coffee.length; i++) {
String next = coffee[indices[i]];
System.out.println(next);
}
Output:
drink it
pick it
put it in a cup
relax

How to return the largest integer in an Array that has 10 random integers in it?

So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help.
Here's the complete question:
Write a program in which the main method creates an array with
10 slots of type int. Assign to each slot a randomly-generated
integer. Call a function, passing it the array. The called
function should RETURN the largest integer in the array to
your main method. Your main method should display the number
returned. Use a Random object to generate integers. Create it
with
Random r = new Random(7);
Generate a random integer with
x = r.nextInt();
So, here's what I have so far:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}
I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.
I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.
Any help is really appreciated because I really want to understand what's going on here. Thank you!
Here is how to generate Random ints
public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;
}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number
Here is how to make method and get max number from list.
static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}
return max;//Return Max Number.
}
Ask if anything is not clear.
This is how we make method which return int.
You can do it by using a simple for loop for the Array.
First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this
a < count[i]
and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable
Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps
What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
for (int i = 0; i < count.length; i++)
{
int x = r.nextInt(); // You need to generate a new random variable each time
count[i] = x;
}
}
Note that this code is not optimal but it is the smallest change from the code you already have.
To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:
int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
{
if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
largest = count[i]; // The current value is larger than any value we have seen so far,
// we therefore set our largest variable to the largest value in the array (that we currently know of)
}
}
Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.
Your code should be something like this. read the comments to understand it
public class Assignment {
public static int findMax(int[] arr) { // Defiine a function to find the largest integer in the array
int max = arr[0]; // Assume first element is the largest element in the array
for (int counter = 1; counter < arr.length; counter++) // Iterate through the array
{
if (arr[counter] > max) // if element is larger than my previous found max
{
max = arr[counter]; // then save the element as max
}
}
return max; // return the maximum value at the end of the array
}
public static void main(String[] args) {
int numberofslots =10;
int[] myIntArray = new int[numberofslots]; // creates an array with 10 slots of type int
Random r = new Random(7);
for (int i = 0; i < myIntArray.length; i++) // Iterate through the array 10 times
{
int x = r.nextInt();
myIntArray[i] = x; // Generate random number and add it as the i th element of the array.
}
int result = findMax(myIntArray); // calling the function for finding the largest value
System.out.println(result); // display the largest value
}
}
Hope you could understand the code by reading comments..
This can be done in one simple for loop no need to have 2 loops
public static void main(String[] args) {
Integer[] randomArray = new Integer[10];
randomArray[0] = (int)(Math.random()*100);
int largestNum = randomArray[0];
for(int i=1; i<10 ;i++){
randomArray[i] = (int)(Math.random()*100);
if(randomArray[i]>largestNum){
largestNum = randomArray[i];
}
}
System.out.println(Arrays.asList(randomArray));
System.out.println("Largest Number :: "+largestNum);
}
Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value.
OR you can sort the array and return. Good luck!
Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)
public int largestValue(){
int largestNum;
int[] nums = new int[10];
for (int n = 0; n < nums.length; n++){
int x = (int) (Math.random() * 7);
nums[n] = x;
largestNum = nums[0];
if (largestNum < nums[n]){
largestNum = nums[n];
}
}
return largestNum;
}

Adding integer elements to list JAVA

I am trying to separate digits from an Integer and then put them into an array.
All elements, except for the first, are printing as 0. Could someone explain why this is it happening?
public class Doom{
public static void main(String[] args){
int number = 1234;
int[] list = new int[5];
while (number > 0) {
int x = 0;
int fork = (number%10);
System.out.println(fork);
list[x] = fork;
x++;
number = number / 10;
}
for (int x : list){
System.out.println(x);
}
}
}
The problem is that you are declaring x inside the loop, so it gets reset to 0 each time. You want to move the int x = 0; line to be above the while (number > 0) { line, outside of the loop. Then it will be initialized to 0 only once, and each pass through the loop can assign it a new value with the x++ line.
You keep redeclaring x in your loop, causing only the first index to have meaningful data. Move it to the outside of your loop.
There are quite a few errors in your program. Biggest one is that you are inializing x to 0 and then incrementing it by 1 within the while loop. It will keep storing your digits at the same location (0th place). Compare the following snippet and try to learn your mistakes:
public class Doom{
public static void main(String[] args){
int number = 1234;
int[] list = new int[String.valueOf(number).length()];
int x = 0;
while (number > 0) {
int fork = (number%10);
System.out.println(fork);
list[x] = fork;
x++;
number = number / 10;
}
for (int y : list){
System.out.println(y);
}
}
}
You are reinitializing x to 0 every time. Declare it outside of the while loop.

Loop for printing array values in two columns

I've been trying to make the following for loops to print the original and modified values of an array in two columns, separated by \t\t. Here is my code:
public class Main {
public static void main(String[] args) {
int jay[] = {1,2,3,4,5,6};
System.out.println("Original\tAfter");
for(int y: jay) {
System.out.println(y);
}
multiplyByTen(jay);
for(int z: jay) {
System.out.println("\t"+ z);
}
}
public static void multiplyByTen(int x[]) {
for(int counter = 0; counter<x.length;counter++) {
x[counter] *= 10;
}
}
}
This is the result so far:
Original After
1
2
3
4
5
6
10
20
30
40
50
60
So my question is how to align the value 10 to 1, and 20 to 2 and so on?
This is the solution of your problem, but i don't know if this is exuctly what you want, but it gives you the wished result
public class Main {
public static void main(String[] args){
int jay[] = {1,2,3,4,5,6};
int jay2[] = jay.clone();
multiplyByTen(jay);
for(int i = 0; i < jay.length;i++) {
System.out.println(jay2[i]"\t"+ jay[i]);
}
}
public static void multiplyByTen(int x[]){
for(int counter = 0; counter<x.length;counter++) {
x[counter] *= 10;
}
}
}
This example is from thenewboston java series, I just modified it a bit to see if I can print an original and after arrays side by side.
There is no way to print it side by side with your current construct because array gets manipulated and changed when passed into the method. One of the only ways would be making a copy of the original and print both original and after in the same line.
If your multiplyByTen method accepts a single int value you can do it as:
for(int y : jay)
System.out.println(y + "\t" + mutiplyByTen(y));
If your multiplyByTen method returns an int array, you can do it as:
int[] arr = mutiplyByTen(jay);
for(int x=0; x<jay.length; x++)
System.out.println(jay[x] + "\t" + arr[x]);
But with the current method signature, you need to make another copy of the original array.
My solution using a single array:
public class Main
{
public static void main(String[] args)
{
int jay[] = { 1, 2, 3, 4, 5, 6 };
System.out.println("Original\tAfter");
multiplyByTen(jay);
// To verify values in the original array (you can remove this loop)
for (int z : jay)
{
System.out.println(z);
}
}
public static void multiplyByTen(int x[])
{
for (int counter = 0; counter < x.length; counter++)
{
System.out.print(x[counter] + "\t\t");
x[counter] *= 10;
System.out.println(x[counter]);
}
}
}
OUTPUT
Original After
1 10
2 20
3 30
4 40
5 50
6 60
If you were to use a enhanced loop inside the multiplyByTen(int x[]) method, you would only be changing the local value and not the value in the array. So, if you were to print out the values in the original array, they would remain the same as the original. This way, the values in the array are permanently modified. So, printing the values after the method will show the multiplied values.
Lastly, I would not use print() or println() methods for this. I would use printf() to print out a formatted output. You will find that tabbing will eventually result in misaligned columns (when the number of digits gets larger). You would not run into this issue when using printf().
Keep it simple.
Why not simply do
for(int y : jay) {
System.out.println(y + "\t" + y*10);
}
It is far better to use Arrays.copyOf(...) when you think of using .clone()1:
int jay[] = {1,2,3,4,5,6};
int jay2[] = Arrays.copyOf(jay,jay.length);
System.out.println("Original\tAfter");
multiplyByTen(jay2);
for (int i = 0; i < jay.length; i++) {
System.out.println(jay[i]+"\t\t"+jay2[i]);
}
This way, you print table rows and not columns.
1Why you should never use .clone() for defensive copying.

Why is my java program printing zero every time?

I am required to take an array of size x (which contains numbers starting at x and then descending down to 1), and then, with a new array of size y (which may or may not be the same size as x), print out random numbers from array x into array y. I wrote the program and it runs fine, but for some reason in the list of random numbers outputted, the number 0 will show up. Does anybody know why this is happening? Here is my code:
import java.util.Random;
public class Prog1A
{
public static void main(String[] args)
{
System.out.println("Program 1A, Christopher Moussa, masc1574");
Random randGen = new Random();
int[] arr_1 = new int[8];
for (int i = arr_1.length - 1; i >= 0; i--)
{
arr_1[i] = arr_1[i];
}
int[] arr_2 = new int[6];
for (int i = 1; i <= arr_2.length; i++)
{
System.out.print(randGen.nextInt(arr_1.length) + " ");
}
}
}
Any feedback will be greatly appreciated, thank you.
Well you aren't doing anything with this loop. You're essentially assigning a variable to itself right throughout the array. Also, I dislike the way you wrote your loop condition, but my preference isn't the issue here.
for (int i = arr_1.length - 1; i >= 0; i--)
{
arr_1[i] = arr_1[i]; //This code does nothing
}
Then you create arr_2[] but you never assign anything to the variables.
I went ahead and edited your code, and I'll explain a few things.
import java.util.Random;
public class Prog1A
{
public static void main(String[] args)
{
Random randGen = new Random();
int[] arr_1 = new int[8];
int[] arr_2 = new int[6];
System.out.println("Program 1A, Christopher Moussa, masc1574");
//Assigns a random number to each member of arr_1
for (int i = 0; i < arr_1.length; ++i)
{
arr_1[i] = randGen.nextInt(arr_1.length);
}
//Copies arr_1 values to arr_2
for (int i = 0; i < arr_2.length; ++i) //Counting up [0 to 5]
{
arr_2[i] = arr_1[i];
}
for (int i = 0; i < arr_2.length; ++i)
{
System.out.print(arr_2[i] + " ");
}
}
}
Always (if possible) declare all variables at the start of a function/class/program. It keeps code a lot cleaner and helps you to identify possible errors that may occur.
Keep your loop parameters consistent. Start from 0 and go up always, or start from the last value and go down. It eliminates the possibility of an error again. I prefer starting from 0 always but it is up to you, as long as it is clean and it works.
Unless you initialize an array, it is going to be empty. If you try to print from it you'll most likely see zeros.
Just add one to your result, The length of your array is 8. With your current code your are returning a random number between 0 and 7. The nextInt method will never return the upper limit of the integer value supplied. You can test this out yourself by exchanging the arr_1.length for a different number like 10 for example and then remove the + 1. You will notice that it will only return the number 9 at the most and 0 will be the lowest number returned.
System.out.print((randGen.nextInt(arr_1.length) + 1) + " ");

Categories

Resources