Flag variable with user input to quit - java

I have a program that is supposed to simulate a game of poker in java. I have a method class called Poker and a check class called CheckPoker which calls the methods in the method class. I haven't even been able to check if the algorithmic part works because while asking if the user would like to switch out any cards. The loop should quit after 5 cards have been entered or if the user enters "1" but in running the program, the for loop doesn't quit until 5 card values have been entered and then throws a "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 56" error. I have tried a for loop, a while loop, a do-while loop, but none have seemed to work thus far.
import java.util.*;
public class Poker {
private String[] deck = {
"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA",
"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ", "CQ","CK","CA",
"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ", "HQ","HK","HA",
"S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ", "SQ","SK","SA"};
private List<String> hand = new ArrayList<>();
public Poker(){
Collections.shuffle(Arrays.asList(deck));
}
public void playGame(){
System.out.print("The first five cards are: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
}
System.out.println(" ");
int k = 0;
String j;
List<String> discard = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.next();
if(!j.equals("1")){
j = in.next();
discard.add(j);
k++;
}else{
break;
}
}
List deckList = Arrays.asList(deck);
String[] discard1 = discard.toArray(new String[0]);
for(int l = 0; l<k; l++){
int m = deckList.indexOf(discard1[l]);
String n = deck[m];
deck[m] = deck[l+5];
deck[l+5] = n;
}
System.out.print("Your new hand is: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
hand.add(deck[i]);
}
System.out.println(" ");
}

Try the code below. It seems you were grabbing two cards per iteration and not capturing them all in the ArrayList.
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.nextLine();
if(j.equals("1") {
break;
}
discard.add(j);
k++;
}

Related

Java loop ignoring first input each loop

I am a beginner and have a simple piece of code that works - it is designed to ask a user for seven numbers and store them in an array then print out what they entered
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
What I want to do is add an error trap to make sure the number is not greater than 49 - I have added the following code and there are no errors and it runs fine but I have to add two numbers for each loop as it only stores the second input - can anyone help tell me why?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
if ( in .nextInt() > 49) {
System.out.println("please enter a number less than 49");
inputs[i] = in .nextInt();
} else
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
when you do in.nextInt() it give you the "next" integer in the input, so you are doing this twice for each loop cycle, once in the if statement and the other in the if or else body. so you need invoke that function only once. something like this:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [] inputs = new int [7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++)
{
int current_input = in.nextInt()
if ( current_input > 49)
{
System.out.println("please enter a number less than 49");
inputs [i] = in.nextInt();
}
else
inputs [i] = current_input;
}
System.out.println("You have entered the numbers:");
for (int i : inputs)
{
System.out.println(i);
}
}
I don't test the code but you have the idea.
here you have another problem still, and is that when the user types a number over 49, the second time you ask the number to the user, you don't test again that it's below 49 so the user can enter any number.

For loop: populate array from user input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was setting up a small app that asks a user to determine the array size and then populate it. The used "for" loop skips the index 0; but I'm uncertain why.
If you run this code with 1 as the array size it skips over the user inputting the first word.
The issue is certainly on the for-loop but it is so simple that I don't see it.
Thanks!
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int arrayDimesion;
Scanner sc = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
arrayDimesion = sc.nextInt();
String[] wordArray = new String[arrayDimesion];
//Populate with user input
for (int i=0; i<arrayDimesion; i++) {
System.out.println("Please enter a word");
wordArray[i] = sc.nextLine();
}
//Print all entered Strings
System.out.println("This are the words you entered: ");
for(int i = 0; i < wordArray.length; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
int r = (int)(Math.random() * wordArray.length);
System.out.println("The random word is: " + wordArray[r]);
}
}
Change your
arrayDimesion = sc.nextInt();
to
arrayDimesion = Integer.parseInt(sc.nextLine());
Reason: sc.nextInt() doesn't consume the newline character that you give after taking arrayDimesion input. This later on gets consumed in the next sc.nextLine() call.
PS: It might throw NumberFormatException. So you can handle it like :
try {
arrayDimesion = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
The below code is clean, easy to read and handles the edge cases.
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int numOfWords;
Scanner scanner = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
numOfWords = Integer.parseInt(scanner.nextLine());
String[] wordArray = new String[numOfWords];
//Populate with user input
System.out.println("Please enter the word(s)");
for (int i = 0; i < numOfWords; i++) {
wordArray[i] = scanner.nextLine();
}
//Print all entered Strings
System.out.println("These are the words you entered: ");
for (int i = 0; i < numOfWords; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
if (numOfWords == 0) {
System.out.println("You didn't enter a word");
} else {
int r = (int) (Math.random() * numOfWords);
System.out.println("The random word is: " + wordArray[r]);
}
}
}

FOR Loop array in JAVA, not working

Can someone point out what is wrong with my program?
I have done most of it but I can't seem to find what's wrong with it.
It doesn't ask the user for the "enter your grade" prompt for each course.
This is for an array assignment for school. Here is my code.
I am having difficulties figuring out what is wrong with the for loop I made specifically the for loop.
This program is supposed to ask the user for their courses and then the user enters their grades for that course.
If possible, please provide me hints on what I am doing wrong.
import java.io.*;
public class StudentMarks {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
i++;
System.out.println("Please enter course name " + i);
course = br.readLine();
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
}//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
Instead of i++ use
System.out.println("Please enter course name " + (i+1));
you do not need any nested loop
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
instead use
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
HERE is the Full code if you still having trouble understanding it let me know .
import java.io.*;
public class sort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
System.out.println("Please enter course name " + (i+1));
course = br.readLine();
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
}
I think you didnt intend to have the i++ / j++ in your for loops (first statement).
The third “parameter” of the loop head actually tells the program what to do, when it reaches the end of the loop. Therefore you increment twice each time.
Your inner loop (with int j = i--) has a condition that is always false, and so it's body is never executed.
The line of code:
j = i--
isn't as simple as it seems and can be broken down into two lines:
j = i;
i = i - 1;
Note that j is set to the value of i, and only after that does i get decremented. So if j is set to i, and then i becomes i - 1, i will be one less than j. So the condition of the for loop i.e. j < i, will always be false, and so the body of the loop will never be executed.
Example:
i = 5;
j = i--;
this boils down to
i = 5;
j = i; //j is 5
i = i - 1; //i is 4
j < i; //5 < 4 is false, inner for loop not executed
Hope this helps!

java array that accepts input of put name mark, quit and get name (not working)

im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}

I'm having problems writing a code with String Arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I have to write a piece of code that manages an event. There are 4 events with limited seats. I'm supposed to write string arrays for each one. The program will then add the name to the pertaining string. My problem is I don't know how to keep adding values to a String array using a loop without deleting the previous values. Any help will be greatly appreciated.
import java.util.Scanner;
public class Assignment_1 {
public static void main(String[] args) {
String [] Hockey_Game;
Hockey_Game = new String[10];
String [] Turner_Concert;
Turner_Concert = new String [5];
String [] Cats_Play;
Cats_Play = new String [3];
String [] StarTrek_Convention;
StarTrek_Convention = new String [3];
System.out.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
for (int i = 0; i < Hockey_Game.length; i++){
Hockey_Game[i] = name;
}
for (String x: Hockey_Game ){
System.out.print(x +",");
}
This should be doing what you're looking for...
import java.util.Scanner;
public class Assignment_1 {
public static void main(String[] args) {
String[] Hockey_Game;
int numHockey = 0;
Hockey_Game = new String[10];
String[] Turner_Concert;
int numConcert = 0;
Turner_Concert = new String[5];
String[] Cats_Play;
int numPlay = 0;
Cats_Play = new String[3];
String[] StarTrek_Convention;
int numCon = 0;
StarTrek_Convention = new String[3];
for (int user = 0; user < 1; user++) {
System.out
.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
switch (input) {
case 1:
if (numHockey < Hockey_Game.length) {
Hockey_Game[numHockey] = name;
}
numHockey++;
for (int j = 0; j < numHockey; j++) {
System.out.print(Hockey_Game[j] + ",");
}
break;
case 2:
if (numConcert < Turner_Concert.length) {
Turner_Concert[numConcert] = name;
}
numConcert++;
for (int j = 0; j < numConcert; j++) {
System.out.print(Turner_Concert[j] + ",");
}
break;
// ... continue for last two ...
}
}
}
}
I do agree with the other answerer that you should be using List/ArrayList for this, but if the purpose of the assignment was to use arrays, here's how you could do it.
Since you need to loop for 4 users (as per your comment), you should have a loop around the whole input process:
for (int i = 0; i < 4; i++) {
// read the input
// add name to correct array
}
You should keep counters for each of your event types:
// here come all your variable declarations
// declare the counters
int hockeyCounter = 0;
int tinaCounter = 0;
int catsCounter = 0;
int startrekCounter = 0;
// no need to redeclare the keyboard all the time, just once is enough
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
System.out.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
switch (input) {
case 1: Hockey_Game[hockeyCounter++] = name; break;
case 2: Turner_Concert[tinaCounter++] = name; break;
case 3: Cats_Play[catsCounter++] = name; break;
case 4: StarTrek_Convention[startrekCounter++] = name; break;
default: System.out.println(input + " is not a valid input");
}
}
Is this now perfect? No, not quite. There are still some problems:
I didn't account for the maximum number of available tickets. This code will crash if all customers want a ticket to the cats' play.
There is a lot of code duplication. It already annoyed me enough to ignore the previously mentioned problem.
Variable names should always start with a lowercase (and preferably use camelCase). This is a Java convention, which helps other people read your code.
It would be better to somehow solve all these problems at once. For this I would propose an array of arrays (although that is maybe more complicated for a beginner, but would make the code much simpler):
final int EVENT_COUNT = 4;
final String[] EVENTS = { "Hockey Game", "Tina Turner Concert",
"Cats Play", "Star Trek Convention" };
final int[] LIMITS = { 10, 5, 3, 3 };
String[][] buyers = new String[EVENT_COUNT][];
int[] counters = new int[EVENT_COUNT];
for (int i = 0; i < EVENT_COUNT; i++) {
buyers[i] = new String[LIMITS[i]];
}
final int CUSTOMER_COUNT = 4;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < CUSTOMER_COUNT; i++) {
System.out.println("Which Event would you like to purchase a ticket for?");
for (int j = 0; j < EVENT_COUNT; j++) {
System.out.print((j+1) + ". " + EVENTS[j] + " ");
}
System.out.println();
int input = keyboard.nextInt();
if (input < 1 || input > EVENT_COUNT) {
System.out.println(input + " is not a valid choice");
i--;
} else if (counters[input-1] >= LIMITS[input-1]) {
System.out.println(EVENTS[input-1] + " is sold out!");
i--;
} else {
System.out.println("Please enter your first and last name");
buyers[input-1][counters[input-1]++] = scan.nextLine();
}
}
Don't use String[] use List
List<String> event1 = new List<String>();
. . .
event1.add(name);
Also define an int[] (this time an array would suffice) that holds the maximum slots for each event, that way when the customer asks for a spot on an already maxed out event you can give him the bad news.
My problem is I don't know how to keep adding values to a String array using a loop without deleting the previous values.
Given the following string array definition:
String[] sa = new String[3];
You can replace existing elements' values...
sa[0] = "test"; // index 0 = "test"
sa[1] = "another"; // index 1 = "test", index 1 = "another"
sa[1] = "different"; // index 1 = "test", index 1 = "different"
You can append to a String array element just like a normal string...
sa[2] = "123"; // index 2 = "123"
sa[2] += "456"; // index 2 = "123456"
Now you can do either of those things in a loop as you see fit...
for (int i = 0; i < sa.length; i++) {
String userInputVar = getUserInput();
sa[i] = userInputVar; // replace value
sa[i] += "foo"; // append to value
}

Categories