I have an assignment to write a code that ask you for 10 seats (some are taken and some are empty) and you need to get a seat, check if it is available and if not find the closest seat that is empty.
Some times my code works, but most of the time it doesn't. Can someone help me?
import java.util.Scanner;
public class Main {
static Scanner reader = new Scanner(System. in );
public static void main(String[] args) {
int mult = 1;
int[] manage = new int[10];
System.out.println(" 0- empty 1-taken ");
for (int i = 0; i < 10; i++) {
System.out.println("enter the " + (i + 1) + " place");
manage[i] = reader.nextInt();
}
int a = 0, check = 0;
System.out.println("What the place you want to seat in?: ");
a = (reader.nextInt()) + 1;
System.out.println("checking...");
while (check != 5) {
if (manage[a] == 0) {
System.out.println(" your seat is in the " + a + " place");
check = 5;
} else if (manage[a - mult] == 0) {
System.out.println(" your seat is in the " + ((a - mult) + 1) + " place");
check = 5;
} else if (manage[a + mult] == 0) {
System.out.println(" your seat is in the " + ((a + mult) + 1) + " place");
check = 5;
} else {
mult++;
}
}
}
}
I think what you want for this line is
a = (reader.nextInt()) - 1;
instead of
a = (reader.nextInt()) + 1;
Since you are always displaying the 'actual index + 1' for all your outputs, i.e.
The user deals with 1 - 10 and not 0 - 9?
Note: manage[a - mult] and manage[a + mult] can throw ArrayIndexOutOfBoundsException if the value is < 0 or the value is >= array length.
Note #2: In the else clause, once mult is >= array length, you can break out of the loop. If you do not add that in, the loop will keep repeating if all the seats are taken right from the start.
So, add a check before accessing that array index, as shown here:
if (manage[a] == 0) {
System.out.println("Your seat is in the " + a + " place");
check = 5;
} else if ( a - mult >= 0 && manage[a - mult] == 0) {
System.out.println("Your seat is in the " + ((a - mult) + 1)
+ " place");
check = 5;
} else if (a + mult < manage.length && manage[a + mult] == 0) {
System.out.println("Your seat is in the " + ((a + mult) + 1)
+ " place");
check = 5;
} else {
mult++;
// Check is necessary here, infinite loop if all seats are taken!
if(mult >= manage.length) {
System.out.println("All seats taken!");
break;
}
}
Input/Output (after making the change):
0 - Empty 1 - Taken
Enter the 1 place: 0
Enter the 2 place: 0
Enter the 3 place: 1
Enter the 4 place: 1
Enter the 5 place: 1
Enter the 6 place: 1
Enter the 7 place: 1
Enter the 8 place: 1
Enter the 9 place: 1
Enter the 10 place: 1
What is the place you want to sit in?: 10
checking...
Your seat is in the 2 place
0 - Empty 1 - Taken
Enter the 1 place: 1
Enter the 2 place: 1
Enter the 3 place: 1
Enter the 4 place: 1
Enter the 5 place: 0
Enter the 6 place: 1
Enter the 7 place: 1
Enter the 8 place: 1
Enter the 9 place: 0
Enter the 10 place: 1
What is the place you want to sit in?: 1
checking...
Your seat is in the 5 place
In the above example, user enters 10, but your program checks for array index 9.Array index 9 is taken, so you check array index 8 (9-1), which is empty, and tells the user that seat #9 is his seat.
Related
I am a bit confused on how I would take the randomly generated number in a range from my program, store that into an array, and read and print out from the array how many times that the number was generated.
For the random import I am using java.util.concurrent.ThreadLocalRandom;
public static void main(String[] args) {
char quitOption = 'q';
char continueOption = 'c';
char input;
int[] myArray;
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
if (input == continueOption || input == 'C') {
roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} else if (input == quitOption || input == 'Q') {
System.exit(0);
}
} while (continueOption == 'c' || continueOption == 'C');
}
I would use a HashMap<Integer, Integer> lets call it rollMap.
Each time you roll you get int currentRoll = randomRoll().
If I were you, I would then say:
if(rollMap.containsKey(currentRoll)){
rollMap.put(currentRoll, rollMap.get(currentRoll) + 1);
}else{
rollMap.put(currentRoll, 1);
}
You can then get how many times each number was rolled by saying:
System.out.println(rollMap.get(<rollid>));
You must figure out how to overcome two problems:
Figure out how many rolls there will be, as Array's are fixed sized
Count how many time a number is rolled
You could use a List, and then use built in methods such as Collections.frequency, or if you are confined to an Array, check to make sure that adding another number will not be out of bounds, (And if it will be then copying it to a new Array) and then iterating over the Array and counting how many times each number occurs.
However, we know the range of numbers that will occur. So why not initialize an Array with six elements, and let 0 be 1, 1 be 2, and so on. Then every time that number is rolled, we increment the index of the respective number. So something like:
int roll = ThreadLocalRandom.current().nextInt(1, 6);
arr[roll -1]++;
So if a two is rolled, we will add one to the 1th index:
[0, 1, 0, 0, 0, 0]
And so on. Then when you need to count the index its a simple loop:
for(int i = 0; i < arr.length; i++) {
System.out.println(i + 1 + " occurs: " + arr[i] + " times");
}
Also you are over complicating your loop. It can be simplified to:
char input;
int[] myArray = new int[6];
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
myArray[roll -1]++;
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} while (input == 'c' || input == 'C');
for(int i = 0; i < myArray.length; i++ ) {
System.out.println(i + 1 + " occurs: " + myArray[i] + " times");
}
Sample run:
Roll is 4
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
q
1 occurs: 3 times
2 occurs: 0 times
3 occurs: 2 times
4 occurs: 1 times
5 occurs: 0 times
6 occurs: 0 times
I have this HW assignment that I'm stuck in:
I need to write the sequence from 1 until N given seed.
for example:
if user inputs 4 v then I need to write every line from the first sequence until the 4th and then write down how many have reached 1 in the end and count the number of numbers.
example:
1 4 2 1 (4)
2 1 (2)
3 10 5 16 8 4 2 1 (8)
4 2 1 (3)
s.o.p :The first 4 hailstone sequences reached 1.
if user inputs 7 c then I only need to write the sentence The first 4 hailstone sequences reached 1.
so far I've written the code for the v part,
the part that works:
public class Collatz {
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
String str = String.valueOf(args[1]);
int counter = 1;
if (str.equals("v")) {
while (n != 1)
{
System.out.print(n + " ");
// If n is odd
if ((n & 1) == 1) {
n = 3 * n + 1;
}
// If even
else{
n = n / 2;
}
counter++;
}
// Print 1 at the end
System.out.print(n + " (" + counter + ")");
}
}
}
I have tried putting a for loop to print from 1 to n in order to print like my example but it doesn't, my attempt:
` for (int i = 1; i < n; i = i+1){
while (i!= 1) {
System.out.print(i + " ");
// If n is odd
if ((i & 1) == 1)
i = 3 * i + 1;
// If even
else
i = i / 2;
}
// Print 1 at the end
System.out.print(i); `
no go. please help me debug this.
Solved it:
add: before the while
for (i = 1; i <= n; i = i+1){
hail = i; // we need to make sure i isn't run over
int counter = 1;
do
{
System.out.println("Enter either limit, abundant, deficient, perfect, or prime = value:");
condition = scan.next();
String equals = scan.next();
num = scan.next();
value=Integer.parseInt(num);
if (Type.isInteger(condition) || !Type.isInteger(num) || value<0)
System.out.println("Please enter in condition = value format");
else
break;
}while(stop);
System.out.println("N" + "\t" + "Abundant" + " " + "Deficient" + " " + "Perfect" + " " + "Prime");
sigma = 0; //sets sigma=0
n=1;
while (stop)
{
for (f = 1; f <= n/2; f++)
{
if (n % f == 0)
sigma = sigma + f;
}
System.out.print(n + "\t");
if (sigma>n)
acount++;
if (sigma == 1)
p++; //prime counter
if (sigma<n)
dcount++; //deficient counter
if (sigma == n)
pcount++; //perfect counter
System.out.print(acount + " " + "\t" + " " + dcount + "\t" + " " + pcount + "\t" + " " + p); //prints abundant column
System.out.println();
if (condition.equals("limit"))
{
if(n<value)
n++;
else
break;
}
if(condition.equals("abundant"))
{
if(acount<value)
n++;
else
break;
}
if (condition.equals("deficient"))
{
if (dcount<value)
n++;
else
break;
}
if (condition.equals("perfect"))
{
if (pcount<=value)
n++;
else
break;
}
if (condition.equals("prime"))
{
if (p<value)
n++;
else
break;
}
}
}
}
Essentially, the code is supposed to print out 5 columns: n, abundant, deficient, perfect, and prime. And each row will have a column of numbers under it. The user is supposed to type in specifications in a 'condition = value' format. So if they type in limit = 10 then it will print 10 rows. And if they input abundant = 10 then it will continue to print rows until the value of abundant reaches 10. The problem I am encountering is that my program will infinity loop when I input certain values and I am not sure what the cause is. For example, if I input deficient = 2 it will work fine but if I input deficient = 10 then it will start an infinite loop. However, when I input perfect = 10 it will only print out 1 row. Like my title says I am a beginner and I can't figure out what is causing the error. Any suggestions?
Try initializing the value of sigma inside the loop:
while (stop)
{
sigma = 0;
...
}
Since sigma is never reset to zero, it just keeps growing for every number. So you will quickly stop finding deficient numbers or perfect numbers, and everything will be be abundant. That's why the abundant keyword works, but deficient does not.
I have a class question that I cannot seem to understand the logic for.
Modify the program below to print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like * that number of times, as shown below.
Histogram showing total number of dice rolls for each possible value.
Dice roll histogram:
2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
I do not understand what in the world this histogram is displaying. Its driving me insane and I cannot move forward with my logic if I do not understand what I am doing. I know this question has been asked before but it looks like they all have a specific number of dice roles they are going off of. I am not given a number and this is what is throwing me off. I know this is really a stupid question. But can anyone possibly explain to me what they mean by "Histogram showing total number of dice rolls for each possible value" what is defining this possible value? I am at a total loss... Any help is appreciated. Here is the code I have written so far.
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
int numOnes = 0; // Tracks number of 1's found
int numTwos = 0; // Tracks number of 2's found
int numThrees = 0; // Tracks number of 3's found
int numFours = 0; // Tracks number of 4's found
int numFives = 0; // Tracks number of 5's found
int numSixes = 0; // Tracks number of 6's found
int numSevens = 0; // Tracks number of 7's found
int numEights = 0; // Tracks number of 8's found
int numNines = 0; // Tracks number of 9's found
int numTens = 0; // Tracks number of 10's found
int numElevens = 0; // Tracks number of 11's found
int numTwelves = 0; // Tracks number of 12's found
int die1 = 0; // Dice values
int die2 = 0; // Dice values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// Count number of sixes and sevens
if (rollTotal == 1) {
numOnes = numOnes + 1;
}
if (rollTotal == 2) {
numTwos = numTwos + 1;
}
if (rollTotal == 3) {
numThrees = numThrees + 1;
}
if (rollTotal == 4) {
numFours = numFours + 1;
}
if (rollTotal == 5) {
numFives = numFives + 1;
}
if (rollTotal == 6) {
numSixes = numSixes + 1;
}
if (rollTotal == 7) {
numSevens = numSevens + 1;
}
if (rollTotal == 8) {
numEights = numEights + 1;
}
if (rollTotal == 9) {
numNines = numNines + 1;
}
if (rollTotal == 10) {
numTens = numTens + 1;
}
if (rollTotal == 11) {
numElevens = numElevens + 1;
}
else if (rollTotal == 12) {
numTwelves = numTwelves + 1;
}
System.out.println("Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Prints a histogram of the number of dice rolls
System.out.println("\nDice roll histogram:");
System.out.println("1's: " + numOnes);
System.out.println("2's: " + numTwos);
System.out.println("3's: " + numThrees);
System.out.println("4's: " + numFours);
System.out.println("5's: " + numFives);
System.out.println("6's: " + numSixes);
System.out.println("7's: " + numSevens);
System.out.println("8's: " + numEights);
System.out.println("9's: " + numNines);
System.out.println("10's: " + numTens);
System.out.println("11's: " + numElevens);
System.out.println("12's: " + numTwelves);
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
You can see where I entered the entry for histograms. I basically thought that I needed to edit my value given from the integers such as "numOnes" to asterisk but now I'm not certain... any help is appreciated!
EDITED CODE -
System.out.println("\nDice roll histogram:");
System.out.print("2's: ");
for(i = 0; i < numTwos; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("3's: ");
for (i = 0; i < numThrees; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("4's: " );
for (i = 0; i < numFours; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("5's: ");
for (i = 0; i < numFives; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("6's: ");
for (i = 0; i < numSixes; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("7's: ");
for (i = 0; i < numSevens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("8's: ");
for (i = 0; i < numEights; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("9's: ");
for (i = 0; i < numNines; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("10's: ");
for (i = 0; i < numTens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("11's: ");
for (i = 0; i < numElevens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("12's: ");
for (i = 0; i < numTwelves; i++);{
System.out.print("*");
}
System.out.println("");
}
OUTPUTS -
Enter number of rolls:
5
Roll 1 is 8 (2+6)
Roll 2 is 9 (6+3)
Roll 3 is 9 (5+4)
Roll 4 is 6 (4+2)
Roll 5 is 9 (6+3)
Dice roll histogram:
2's:
3's: *
4's: *
5's: *
6's: *
7's: *
8's: *
9's: *
10's: *
11's: *
12's: *
I can enter a larger number of rolls and I will get an asterisk for the 2's and it will increase like I need but it will not increase the rest of the numbers and they all only get one asterisk. What is keeping my code from properly increasing the amount of *'s? Iv been fighting with this for hours :/
"I do not understand what in the world this histogram is displaying."
Well, as you said:
"Histogram showing total number of dice rolls for each possible value"
The histogram:
2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
is a record of the rolls of a pair of six sided dice. The possible values of totaling a pair of dice range from 2 to 12. If you rolled them 100 times they might give these results.
This histogram shows that the value 6 was most frequently rolled (19 times) and 4 the least frequently rolled (3 times). If you counted up every * you'd know how many times the dice have been rolled.
You may think that a histogram must look like this:
But turn that sideways:
and imagine that the blue bars are *'s, the 100 - 150 label is a 2, and the 150 - 200 label is a 3, well then it starts to look like your histogram.
Either form is a histogram. They let you compare quantities (how many) of things that fall in different categories (kinds) of things.
A graphic chart is difficult to output from a program that is text based so instead it's asking you to display what is basicly ascii art:
If this was in a text file, and not program output, this could also be considered a form of tally. You can easily add new *'s as you receive new data. It's the same trick as this:
Hope that makes more sense.
SPOILER ALERT: If that helped and you'd like to take a crack at modifying the program yourself read no further. Otherwise...
This
System.out.println("\nDice roll histogram:");
System.out.println(" 1's: " + nManyStars(numOnes));
System.out.println(" 2's: " + nManyStars(numTwos));
System.out.println(" 3's: " + nManyStars(numThrees));
System.out.println(" 4's: " + nManyStars(numFours));
System.out.println(" 5's: " + nManyStars(numFives));
System.out.println(" 6's: " + nManyStars(numSixes));
System.out.println(" 7's: " + nManyStars(numSevens));
System.out.println(" 8's: " + nManyStars(numEights));
System.out.println(" 9's: " + nManyStars(numNines));
System.out.println("10's: " + nManyStars(numTens));
System.out.println("11's: " + nManyStars(numElevens));
System.out.println("12's: " + nManyStars(numTwelves));
and this
static String nManyStarsOld(int n) {
String result = "";
for (int i = 0; i < n; i++) {
result += "*";
}
return result;
}
should, if dropped in the right places, get your program to stop printing what it prints now which is this:
Enter number of rolls:
20
Roll 1 is 5 (2+3)
Roll 2 is 10 (4+6)
Roll 3 is 7 (5+2)
Roll 4 is 7 (5+2)
Roll 5 is 5 (1+4)
Roll 6 is 11 (6+5)
Roll 7 is 8 (3+5)
Roll 8 is 8 (2+6)
Roll 9 is 7 (1+6)
Roll 10 is 8 (3+5)
Roll 11 is 12 (6+6)
Roll 12 is 6 (2+4)
Roll 13 is 8 (6+2)
Roll 14 is 8 (4+4)
Roll 15 is 7 (1+6)
Roll 16 is 4 (2+2)
Roll 17 is 6 (5+1)
Roll 18 is 7 (6+1)
Roll 19 is 6 (1+5)
Roll 20 is 5 (1+4)
Dice roll histogram:
1's: 0
2's: 0
3's: 0
4's: 1
5's: 3
6's: 3
7's: 5
8's: 5
9's: 0
10's: 1
11's: 1
12's: 1
And instead, get it to print this:
Dice roll histogram:
1's:
2's:
3's:
4's: *
5's: ***
6's: ***
7's: *****
8's: *****
9's:
10's: *
11's: *
12's: *
Next time you post a question please include the current output along with the expected output.
If you feel like being a smarty pants there is actually a one line version of nManyStars():
static String nManyStars(int n) {
return new String(new char[n]).replace("\0", "*");
}
Inspired by this: https://stackoverflow.com/a/4903603/1493294
Also, if you have at least Java 11 you can trade in nManyStars(n) for "*".repeat(n)
Hope it helps
Iv got it all working. Thank you #CandiedOrange and #MadProgrammer for the help and guidance! Found that my histogram code was messed up with my for statements having a ; in an incorrect spot causing my for statement to not apply the * based on its process of running through the for statement and it was just printing a * as a normal print function. All is well. Thanks for all the help!
My content data in Notepad is 1 to 25. How can I display the data that is marked in red below. The other values can be ignored.
change
int i = sc.nextInt();
System.out.println(i + " ");
to
int i = sc.nextInt();
if(i%10 <= 5) {
System.out.println(i + " ");
}
Idea is that i%10 will give the unit digit of a number. So if it is <= 5 print that number.