Check if array elements are filled in java - java

I'm working on a simple reservation system with 10 elements (seats). I want to check if elements from 1 to 5 has been set. If Yes, then set the elements from 6 to 10 (Vice-Versa).
An element should not be assigned a value more than once. My code so far.
boolean[] seats = new boolean[10];
Scanner input = new Scanner(System.in);
System.out.print("Choose FirstClass(1) / Economy(2): ");
int flightClass = input.nextInt();
for (int j = 0; j < seats.length; j++) {
System.out.println("\nEnter Seat Number: ");
int enterSeat = input.nextInt();
if (flightClass == 1) {
if (enterSeat >= 0 && enterSeat <= 5) {
System.out.println("You're in the First Class.");
seats[enterSeat] = true;
System.out.printf("You're Seat Number is %d\n", enterSeat);
}
} else if (flightClass == 2) {
if (enterSeat >= 6 && enterSeat <= 10) {
System.out.println("You're in the Economy.");
seats[enterSeat] = true;
System.out.printf("You're Seat Number is %d\n", enterSeat);
}
}
My Question: How do I check if elements from 1 to 5 has been set, and if they have, set the elements from 6 to 10, and vice versa?
For example:
Enter seat no. to book:
1
Enter seat no. to book:
2
Enter seat no. to book:
3
Enter seat no. to book:
4
Enter seat no. to book:
5
All the first class seats(1-5) has been set. Now the remaining seats are from 6 - 10.
Enter seat no. to book:
6 so on...

Arrays in Java1 are indexed from zero, not from one. Therefore, your code that checks >=1 and <=10 should be changed to >=0 and <=9, or use2
seats[enterSeat-1]
instead of
seats[enterSeat]
To find the next available element from among the elements of a sub-array, you can use this loop:
int firstFree = -1;
for (int j = 0 ; j != 5 ; i++) {
if (!seat[j]) {
firstFreeSeat = j;
break;
}
}
if (firstFreeSeat == -1) {
System.out.printl("Sorry!");
}
1 As well as C, C++, C#, Objective C, and many other languages
2 This is something you may want to do if you expect the user to enter numbers one through ten rather than zero through nine - a more natural choice for seat numbering.

Related

Decreasing number pyramid, nested for loop, user input, java

Write a program to produce the following output for any given integer number between
1 and 9 inclusive.
Enter an integer value [1..9]: 6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I have done the top half but I can not figure out the bottom with the repeating user input.
package lab7;
import java.util.Scanner;
public class problem5 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
while (input <= 9) {
for (int i = 1; i <= input; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
break;
}
}
}
Expected result: included at the top; actual result so far (input of 5):
1
12
123
1234
12345
You're pretty close. You have a for loop that covers the first half of the output you want. You can add a second for loop to handle the second half of the output.
This is pretty similar to the first loop, but has a few small differences:
instead of the loop variable starting at 1 and increasing, this one starts at input and decreases each time through (i-- instead of i++)
instead of printing any of the loop variables (i or j), it prints the input value ("6" in your example)
for (int i = input; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(input);
}
System.out.println();
}
If I run that code locally – so your for loop, then this for loop, then the break statement – this is the output:
Input an integer between 1 and 9
6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I would prefer a more efficient algorithm, your current approach is O(n2); consider the digits '1' - '9'; if we store them in a String then we can take a simple substring of that String for each line at the top (for example, "123456789".substring(0, 3) -> "123") that can be used to generate the top through successive calls to substring. We can use a similar approach to build the bottom; use an array of all possible rows and iteratively call substring. Finally, don't forget to validate that input is between one and nine inclusive. Something like,
Scanner scan = new Scanner(System.in);
String digits = "123456789";
String[] btm = { "1", "22", "333", "4444", "55555",
"666666", "7777777", "88888888", "999999999" };
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
if (input < 1 || input > 9) {
System.err.printf("Invalid input: %d%n", input);
System.exit(1);
}
for (int i = 0; i < input; i++) {
System.out.println(digits.substring(0, i + 1));
}
for (int i = input - 1; i >= 0; i--) {
System.out.println(btm[input - 1].substring(0, i + 1));
}

Counting numbers of even numbers and odd numbers in java array

I have a program that reads a list of integers, and then display the number of even numbers and odd numbers. We assume that the input ends with 0. Here is the sample run of the program.
Input numbers: 1 2 3 4 5 6 7 8 9 0
Odd: 5 Even: 4
However, my result is
Odd: 5 and Even: 5.
The problem is that 0 is counted as an even number. This is my code
public class Q75 {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner (System.in);
double [] numbers = new double[10];
System.out.print("Enter numbers: ");
for(int i = 0;i<numbers.length;i++){
numbers[i] = input.nextDouble();
}
int Evens = 0;
int Odd = 0;
for(int i = 0;i<numbers.length;i++){
if(numbers[i]%2 == 0){
Evens++;
}else{
Odd++;
}
}
System.out.println("The number of odd numbers: " + Odd);
System.out.println("The number of even numbers: " + Evens);
}
}
There are two options
A) Adding another branch in your if statements i.e.
if(number[i] > 0) {
if(number[i] % 2 >0)
Odd++;
else
Evens++;
}
NB: changing the else branch to else if(number[i] >0), you can do without the outer if condition.
B) Since the list of number ends with 0 you can put this as a condition in your for loop i.e.
for(int i =0; i < numbers.length && numbers[i] > 0 ; i++)
Also as a rule of thumb variable names in java start with a small letter
Just don't check the last element: Use i < numbers.length - 1
for(int i = 0;i < numbers.length - 1; i++) {
//
}

How to get do-while statement to loop infinitely with nested if statment

I am having a user enter in a multiple of 3 between 3 and 24 inclusive. The output then prints out the number less 3 until it reaches 0. Ex the user picks 15. The output prints out 15,12,9,6,3,0. The problem is if the user picks the number 17 it rounds it down to 15 and proceeds to do the rest of the code. How do I make it repeat the input infinitely if they do not enter in a multiple of 3? My code is as follows.
do{
System.out.print("Enter a multiple of 3: ");
//We use the variable n to hold the multiple of 3, like the heading says to do.
n = input.nextInt();
if (n % 3 !=0 || n >= 25) {
System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive.");
n = input.nextInt();
}
/**
* X = n /3, this gives us the base number of the multiple of 3 to use and figure out the
* values of n->0 by 3's.
*/
for(x = n / 3; x <= 8 && x >=0; x--){
int three = 3 * x;
System.out.printf(three + "\t");
}
}while(x >= 0);
As you can see I just put another input section within the if statement, however I do not wish to do this. I am trying to figure out a way for the if statement to keep looping. Is it my parameters I set up on my if statement? Or is there a specific command to make the if statement repeat if the criteria of the statement is not met? Also I am using Java.
You can use a separate loop to initialize n. (I'm not sure what your outer loop is for, so I deleted it.)
int n;
while (true) {
System.out.print("Enter a multiple of 3: ");
n = input.nextInt();
// Validate input.
if (n % 3 == 0 && n < 25 && n > 0) {
// Input is good.
break;
}
// Input is bad. Continue looping.
System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive.");
}
for (x = n / 3; x <= 8; x--) {
int three = 3 * x;
System.out.printf(three + "\t");
}
The if--break pattern is necessary because you need to check the looping condition in the middle of the loop, rather than the beginning or end.
If you don't like the while(true) { ... break; ... } then you can use a do { ... } while (flag); loop instead. A do/while loop is common when you want to do something 1 or more times - specifically at least once and you aren't sure how many times.
For example
boolean keepGoing = true;
do {
System.out.println("Enter a multiple of 3 between 3 and 24: ");
n = input.nextInt();
keepGoing = (n < 3 || 24 < n || n % 3 != 0);
} while (keepGoing);
System.out.println("You entered: " + n);
Or this variation
boolean done = true;
do {
System.out.println("Enter a multiple of 3 between 3 and 24: ");
n = input.nextInt();
done = (3 <= n && n <= 24 && n % 3 == 0);
} while (!done);
System.out.println("You entered: " + n);

Taking input from user in a combined way

im working on a question where the input is given in the below format:
5
7
121
123
7
121
###
4
3
3
2
5
Explanation of the input:
The first number is N, here in example N=5 (N>1 and N<100000). the next are N lines with different numbers ranging from 1 to 100. then comes ###. then the next number is K, here in example K=4. the next are K lines with different values ranging from 1 to 100. the '###' is used to separate N and K inputs.
my question here is how do i take the input from the user using the '###'. and later how can i differentiate between N and K. Kindly help.
please find my code below. but im not able to figure the format to write this type of input. kindly help.
int n=0,N=0,k=0,y=0,K=0;
System.out.println("Enter 'N': ");
n=in.nextInt();
if(n>=1 && n<=100000) {
N=n;
}
int[] a1 = new int[N];
int[] x = new int[N];
System.out.println("Enter values of N: ");
for (int i=0;i<a1.length;i++) {
x[i] = in.nextInt();
}
for (int i=0;i<a1.length;i++) {
if(x[i]>=1 && x[i]<=5000) {
a1[i] = x[i];
}
}
System.out.println("Enter 'K': ");
k=in.nextInt();
if(k>=1 && k<=100) {
K=k;
}
int[] a2 = new int[K];
System.out.println("Enter values of K: ");
for (int i=0;i<a2.length;i++) {
a2[i] = in.nextInt();
}
You should be able to simply use in.skip("###") before reading k to skip the line with the separator.

In java, How would I check input validation for an array used to input grades (can't be negative, can't be over 100)

So far I've tried to create a while loop that only kicks out if the entered array value is a "correct" one (between 0 and 100). Wich means that the loop should repeat if the value entered is a negative number or something random like a char.
My code so far only works if all grades entered are incorrect. If I enter a 0, 100, and -2 it still goes through, even though -2 should cause the loop to repeat. What do I need to modify to only allow values that are between 0 and 100 to be entered into the array?
Code so far:
//Input validation for grades
int g = 0;
while(g >= 0)
{
System.out.print("Please Enter the Students' Grades: ");
for (int c = 0; c < studentGrades.length; c++)
{
studentGrades[c] = input2.nextInt();
if (studentGrades[c] >= 0 && studentGrades[c] <= 100)
{
g = -1;
}
}
}
In this code snippet:
studentGrades[c] >= 0 && studentGrades[c] <= 100
... you are saying that if the entered grade is greater than or equal to 0 and it is less than or equal to 100, set g to -1 (and exit the loop).
So essentially, every time a valid grade is entered, your loop will exit. You've done the opposite of what you wanted. Try adding a ! before your condition to negate it.
This should do
outer:
while(g >= 0) {
System.out.print("Please Enter the Students' Grades: ");
for (int c = 0; c < studentGrades.length; c++) {
studentGrades[c] = input2.nextInt();
System.out.println(" input is "+studentGrades[c]);
if (studentGrades[c] <= 0 || studentGrades[c] >= 100) {
break outer;
}
}
}
Put a check before you add the next into the array. If it's out of bounds, ask for another value.
You need to flip the logic around, currently your g flag starts as "invalid" (meaning that if g doesn't change, the loop continues), and when you find a valid grade you mark g as valid.
Instead, at the top of the while loop set g to -1, and then set it back to 0 if any of the grades provided are invalid, for example:
int g = 0;
while(g >= 0) {
g = -1;
System.out.print("Please Enter the Students' Grades: ");
for (int c = 0; c < studentGrades.length; c++) {
studentGrades[c] = input2.nextInt();
if (studentGrades[c] < 0 || studentGrades[c] > 100) {
g = 0;
}
}
}
I think this what you are trying to achieve (also you can enhnace it)
int[] values = new int[5]; //modify this according to your size
int index = 0;
do {
int value;
do {
System.out.println("Enter value " + (index + 1) + ": ");
value = input.nextInt();
} while (value < 0 || value > 100); //make sure each value is valid
values[index++] = value; //add value to the array
} while(index < values.length); //make sure you get all the values
If for loop is not required then I think it looks better that way.
Move your while loop inside the for loop, because I guess you want to validate your input grade for each index: -
And your condition should be g < 0. Also, you have used reverse condition in your if. You were setting g = -1 for correct input. You need to change your condition in if.
for (int c = 0; c < studentGrades.length; c++) {
g = -1; // Set to invalid to get your while run first time.
while(g < 0) {
System.out.print("Please Enter the Students' Grades: ");
studentGrades[c] = input2.nextInt();
// Check invalid grade -> negative or more than 100
if (studentGrades[c] < 0 || studentGrades[c] > 100) {
g = -1;
} else {
// Break while if correct grade has been entered. Continue with next index
break;
}
}
}
This code looks like it will loop until it gets studentGrades.length values, no matter what, and if the while loop repeats, it will repeat forever because g is not reinitialized.
I assume this must be a homework problem, so I'll leave the actual coding to fix the bug to you as an exercise.

Categories

Resources