ArrayList lottery game - excess array lists - java

I have been tinkering with this program for a while, but I still do not know what is wrong.
My problem is that if I want to get more than 1 ticket it gives me more array lists than expected. I cannot find a pattern as if I enter 2, I get 3, and if I enter 3, I get 6, and if I enter 4, I get back 10.
Input: Amount for how many tickets I want.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayListLottery {
public static void main(String[] args) {
int range = 49, amount = -1, number = 0, choice = -1;
// ArrayList<Integer> tickets = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> games = new ArrayList<ArrayList<Integer>>();
do {
System.out.println("Enter amount of lottery tickets you want");
Scanner in = new Scanner(System.in);
if (amount < 0) {
amount = in.nextInt();
}
while (amount != 0) {
System.out.println("Entered while block");
for (int i = 0; i < amount; i++) {
// Create an arraylist for how
// many tickets i want
ArrayList<Integer> tickets = new ArrayList<Integer>();
games.add(tickets);
for (int k = 0; k < 6; k++) { // Limit the size of a ticket to
// 6
if (tickets.size() < 6) {
number = (int) (range * Math.random()) + 1;
tickets.add(number);
Collections.sort(tickets);
} else {
break;
}
}// limit for loop to 6 end
}// arraylist creator end
amount--;
System.out.println("Amount is " + amount);
}//while loop end
for (List<Integer> i : games) { //print out each ticket
for (Integer n : i) {
System.out.print(n + " ");
}
System.out.println();
} //print out for-loop end
games.clear();
System.out.println("Type 0 to exit, otherwise pick any other number ");
choice = in.nextInt();
amount = choice;
} while (amount != 0);
System.out.println("Good luck!");
}
}

Fibonacci number of amount will be your size of games list.
It is happening because you have applied while as well as for loop for amount.
Replace your while loop with if statement.

You can put
amount--;
in the for loop which generate the arraylist.
Like this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayListLottery {
public static void main(String[] args) {
int range = 49, amount = -1, number = 0, choice = -1;
// ArrayList<Integer> tickets = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> games = new ArrayList<ArrayList<Integer>>();
do {
System.out.println("Enter amount of lottery tickets you want");
Scanner in = new Scanner(System.in);
if (amount < 0) {
amount = in.nextInt();
}
while (amount != 0) {
System.out.println("Entered while block");
for (int i = 0; i < amount; i++) {
// Create an arraylist for how
// many tickets i want
ArrayList<Integer> tickets = new ArrayList<Integer>();
games.add(tickets);
for (int k = 0; k < 6; k++) { // Limit the size of a ticket to
// 6
if (tickets.size() < 6) {
number = (int) (range * Math.random()) + 1;
tickets.add(number);
Collections.sort(tickets);
} else {
break;
}
}// limit for loop to 6 end
amount--;
}// arraylist creator end
System.out.println("Amount is " + amount);
}//while loop end
for (List<Integer> i : games) { //print out each ticket
for (Integer n : i) {
System.out.print(n + " ");
}
System.out.println();
} //print out for-loop end
games.clear();
System.out.println("Type 0 to exit, otherwise pick any other number ");
choice = in.nextInt();
amount = choice;
} while (amount != 0);
System.out.println("Good luck!");
}
}
Besides that, you can add a breakpoint to step over your program line by line which may make you find the bug quickly.

Related

Java 2D Seating Array for a Theater

import java.util.*;
/**
* Write a description of class TheaterApp here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class TheaterApp {
static int [][] seats = {
{10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10},
{10,10,20,20,20,20,10,10},
{20,20,30,30,30,30,20,20},
{30,30,40,40,40,40,30,30},
{30,40,40,50,50,40,40,40}};
/**
* Constructor for objects of class TheaterApp
*/
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print("Enter request, please (or 'help' or 'quit') ");
ans = input.next();
if (ans.equals("help")) {
System.out.println("Possible commands");
System.out.println("price <price>");
System.out.println("seat <row> <seat>");
System.out.println("left");
System.out.println("remaining <price>");
System.out.println("print");
System.out.println("quit");
System.out.println("help");
} else if (ans.equals("price")) {
int p = input.nextInt();
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
System.out.println("Next available seat at position: " + i + " " + j);
}
}
}
// Find the 'best' seat at the given price
} else if (ans.equals("seat")) {
int r = input.nextInt();
int c = input.nextInt();
int k;
int i;
int j;
for (int l = 0; l < 6; l++) {
k = 1;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if (k == input.nextInt()) {
// check if the seat has already been reserved
if (seats[i][j]== 0) {
System.out.println("That seat has already been reserved");
}
// if its not reserved then reserve it
else {
seats[i][j]= 0;
}
}
k++;
System.out.println(seats[i][j]);
}
}
}
// Reserve the given row and seat, if possible
} else if (ans.equals("left")) {
// Print the total available seats
} else if (ans.equals("remaining")) {
int p = input.nextInt();
// Print the total available seats at this price
} else if (ans.equals("print")) {
for (int r = 0; r < seats.length; ++r) {
for (int s = 0; s < seats[r].length; ++s) {
System.out.print(seats[r][s] + " ");
}
System.out.println();
}
} else if (!ans.equals("quit")) {
System.out.println("Come again?");
}
} while (!ans.equals("quit"));
System.out.println("Good bye");
}
}
This array represents theater seats and I have to mark sold seats by changing the price to 0. I also have to make sure seats are open when a user asks for a a certain spot, and when a user enters a price, find any seats that are open.
So I'm pretty sure I figured out the code for finding the best seat at any given price. I can't figure out how to do the remaining code.
I just need to find out how to print the total available seats and also how to print the total available seats when a certain price is entered.
Thanks.
You'd just use nested for loops, like you did before, except now you'd have some kind of a availableSeats counter you'll increment every time a seat meets a certain condition.
Like so:
int availableSeats = 0;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if(seats[i][j] == sometargetprice){
availableSeats++;
}
}
}
System.out.println("Total of " + availableSeats + " are available.");
Unless I'm not understanding the problem correctly.

Why isn't my Java number input code working?

I have been trying to figure out why isn't my code working. If I don't do it through a method and put this code in the main method then it keeps repeating. I want to ask the user for a new number every time. And then see if the number is odd or even. If odd then increase the odd count add all the numbers that the user enters. The user should be asked to enter values until the number 0 is entered.
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("Enter number");
int oddnumbers = 0;
do {
int count = 0;
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
You should probably have the reading of a number "i = sc.nextInt();" inside the loop, and the variable count outside, like this:
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int oddnumbers = 0;
int count = 0;
int i=0;
do {
System.out.println("Enter number");
i = sc.nextInt();
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}
This code gives the answer to tour spec/question
Reason for not working: You should take input inside do while loop and then check for odd.
public int numbers() {
Scanner sc = new Scanner(System.in);
int num = 0;
int oddSum = 0;
do {
System.out.println("Enter number");
num = sc.nextInt();
if(num == 0) {
break;
} else if (num % 2 != 0) {
oddSum += num;
}
} while (num != 0);
sc.close();
return oddSum;
}
public static void main(String[] args) {
Test n = new Test();
System.out.println(n.numbers());
}

Why is my program terminating after it takes 3 inputs?

This program is an attempt at making a similar game to Battleships on the command line. If my program takes 3 inputs that are "HITS" it terminates. Why is this? My suspicion is that there is something wrong with my logic in the if/else statements.
The reason I have 3 lists is because I want to let the user know that they have hit 3 consecutive numbers and that they have sunk a ship in the game. Also, I am aware of the potential problem that can occur when the random method generates the same number in more than one list.
Apologies if the code is not written very nicely. I am still a beginner.
Main
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static int numOfHits = 0;
public static int numOfGuesses = 0;
public static int userInput;
public static int number;
public static void main(String[] args) {
Game a = new Game();
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> hitlist = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> list3 = new ArrayList<Integer>();
int temp = a.numGenerator();
list.add(temp);
list.add(temp+ 1);
list.add(temp + 2);
int temp2 = a.numGenerator();
list2.add(temp2);
list2.add(temp2 + 1);
list2.add(temp2 + 2);
int temp3 = a.numGenerator();
list3.add(temp3);
list3.add(temp3 + 1);
list3.add(temp3 + 2);
System.out.println(list + " " + list2 + " " + list3);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to BattleShips! In this version; the game is on a long 30 cell row and there are 3 different sub rows to kill. Input your guesses.");
while(!input.hasNextInt()) {
System.out.println("That is not an integer. Please try again.");
input.next();
}
while(list.isEmpty() == false && list2.isEmpty() == false && list3.isEmpty() == false) {
while(!input.hasNextInt()) {
System.out.println("That is not an integer or the number is too large to be stored as an integer. Please try again.");
input.next();
}
userInput = input.nextInt();
while(hitlist.contains(userInput)) {
System.out.println("You have already hit that one! Try again.");
userInput = input.nextInt();
}
while(true) {
if(list.contains(userInput)) {
numOfGuesses++;
numOfHits++;
int index = list.indexOf(userInput);
hitlist.add(userInput);
list.remove(index);
System.out.println("HIT!");
userInput = -100;
break;
}
if(list2.contains(userInput) && !list.contains(userInput)) {
numOfGuesses++;
numOfHits++;
int index = list2.indexOf(userInput);
hitlist.add(userInput);
list2.remove(index);
System.out.println("HIT!");
break;
}
if(list3.contains(userInput)) {
numOfGuesses++;
numOfHits++;
int index = list2.indexOf(userInput);
hitlist.add(userInput);
list3.remove(index);
System.out.println("HIT!");
break;
}
else {
numOfGuesses++;
System.out.println("MISS!");
}
}
if(numOfHits == 9) {
System.out.println("Congratulations! You have beaten the game.");
System.out.println("You took " + numOfGuesses + " guesses");
System.exit(0);
}
}
}
}
Game
import java.util.ArrayList;
public class Game {
private double randomNumber;
public int numGenerator() {
randomNumber = Math.random() * 30 + 1;
return (int) randomNumber;
}
}
The bug
I do not get a compiler error. It is a logic error. Here is an example:
[15, 16, 17] [8, 9, 10] [28, 29, 30] // NUMBERS GENERATED FROM MATH.RANDOM
Welcome to BattleShips! In this version; the game is on a long 30 cell row and there are 3 different sub rows to kill. Input your guesses.
15
HIT!
15
You have already hit that one! Try again.
16
HIT!
17
HIT!
//AFTER THIS LINE IT TERMINATES. I WANT THE USER TO KEEP MAKING GUESSES UNTIL 9 NUMBERS ARE HIT.
The problem is in your while condition:
while(list.isEmpty() == false && list2.isEmpty() == false && list3.isEmpty() == false)
It checks till any one of the lists is not empty.
Change it to:
while(list.isEmpty() == false || list2.isEmpty() == false || list3.isEmpty() == false) {
This will check till all of the lists are not empty.

printing distinct numbers java

I am having a hard time with this code. The code is finished but the output is wrong.
My code prints Enter ten numbers: 1 2 3 5 6 6 8 7 4 1
It should print
The distinct numbers are:
1 2 3 5 6 8 7 4
but it doesn't. It prints:
10 10 10 10 10 7
How can I fix it?
Here is my code:
import java.util.*;
public class homework1 {
public static void main(String[] args){
// input from user
Scanner input = new Scanner(System.in);
int [] numbers = new int[10];
boolean[] distinct = new boolean[10];
System.out.println("Enter ten numbers");
for (int i=0; i<numbers.length; i++){
System.out.println("Number " + (i + 1) +": ");
numbers [i] = input.nextInt();
distinct[i] = true;
for(int j = 0;j<10; j++){
if(numbers[i] == numbers[j] && i != j) {
distinct[i] = false;
}
}
}
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=distinct.length;
count++;
}
}
System.out.println("The number of distinct number is: "+numbers[count]);
System.out.println("The distinct numbers are: ");
for(int i= 0; i < 10; i++) {
if(distinct[i]) {
System.out.print(numbers[i] + " ");
}
}
System.out.println();
}
}
This line:
numbers[count]=distinct.length;
Is setting your outputs to be the length of the array (Which in this case is hard coded to 10. Try:
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=numbers[j];
count++;
}
}
Which will set your output to be the distinct number.
Plug: Check out Code Review
This will solve your problem.
If you use HashMap, you will have less code.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> distinctNumbers = new HashMap<Integer, String>();
// input from user
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers");
for (int i = 0; i < 10; i++) {
System.out.println("Number " + (i + 1) + ": ");
Integer numberEntered = input.nextInt();
distinctNumbers.put(numberEntered, null);
}
System.out.println("The number of distinct number is: " + distinctNumbers.size());
System.out.println("The distinct numbers are: ");
Set<Integer> keys = distinctNumbers.keySet();
for (Iterator<Integer> iterator = keys.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.print(" "+ integer);
}
}
}
Remove line numbers[count] = distinct.length; This make your output are all 10
Then, I change your code a little to make it run right:
...
int count = 0;
for (int j = 0; j < 10; j++) {
if (distinct[j]) {
//numbers[count] = distinct.length; //remove it, it nonsense
count++;
}
}
// distinct number should be count, not number[count]
System.out.println("The number of distinct number is: " + count);
....
public static void main(String[] args) {
int arr[] = {1,3,5,4,7,3,4,7};
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++) {
if(frequency.containsKey(arr[i])){
int value = frequency.get(arr[i]);
frequency.put(arr[i], value + 1);
}
else {
frequency.put(arr[i], 1);
}
}
for(Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
System.out.println(entry.getKey());
}
}
package Chapter7;
import java.util.Scanner;
public class Exercise7_5 {
public static void main(String[] args) {
// Print distinct numbers
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers: ");
for (int i = 0, j = 0; i < 10; i++) {
if (storeDistinctNumbers(j,input.nextInt(), numbers))
j++;
}
for (int i = 0; numbers[i] != 0 ; i++)
System.out.print(numbers[i] + " ");
}
public static boolean storeDistinctNumbers(int j, int num, int[] numbers) {
for (int e: numbers) {
if (e == num)
return false;
}
numbers[j] = num;
return true;
}
}

My programs print statement is wrong

When i run my program and choose a number between 0 and 100, it prints my answer wrong.
Java console
----jGRASP exec: java TestScores
How many tests do you have? 3
Enter grade for Test 1: 80
Enter grade for Test 2: 80
Enter grade for Test 3: 80
The average is: 26.666666666666668The average is: 53.333333333333336The average is: 80.0
----jGRASP: operation complete.
import java.util.Scanner;
public class TestScores {
public static void main(String[] args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index] > 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
average = totGrades / grade.length;
System.out.print("The average is: " + average);
}
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}
You print the average inside the loop that calculates the average.
Print it only outside the loop.
You should calculate sum in loop and then (after the loop) divide it by the number of elements.
I move the statement which calculates the sum from inside the loop to the outside, that works.
My new code is.
import java.util.Scanner;
public class TestScores
{
public static void main(String[]args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++)
{
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}
You can close my post.

Categories

Resources