So far I have this code below:
class Card{
private static String[] pairArray{"A,A","K,K","Q,Q","J,J","10,10",
"9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(){
int minimum = 0;
int maximum = 13;
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player 1, You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
public static void main(String[] args) {
generateRandom();
}
}
It randomly assigns an element from the array to player 1.
I need to read a users input of how many players he wants to play with, then produce this 4 times with each player getting a different set of cards. I think I need to use the scanner feature, but I'm unsure of where to include it in this code.
Scanner s = new Scanner(System.in);
int num = s.nextInt();
That'll read the int the user inputs. And you put that before generateRandom(); in your main. Using the number the user gives, you can do whatever you want with it, including making a while loop that makes that many random stuff. You don't provide much info, so this is as much as I can give.
Related
My schoolwork is asking me to write a Java program. I'm not getting something quite right.
Basically I have to create a Java method that gets a user to enter x amount of grades (users choice), store the grades in an array and then add the grades in the array up to be called in the main method.
Here's my code:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int [] storeGrades = new int[numberOfGrades];
}
public static int getTotalScore(int numberOfGrades[]) {
Scanner keyboard = new Scanner(System.in);
int getTotalScore;
int []storeGrades;
for (int i = 0; i < getTotalScore; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
int userGradeNumbers = keyboard.nextInt();
storeGrades[i] = userGradeNumbers;
sum += userGradeNumbers;
}
}
}
I'm getting an error at "sum" that it hasn't been resolved to a variable? It won't let me initialize sum within the for loop, nor the getTotalScore method. Why not?
First, get the grades. Then call the method to get the sum. Declare the sum and initialize it to 0 before your loop. Return it after. Like,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println(getTotalScore(storeGrades));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
Your code has the right intent about it, but some of the ordering of things is a little off and there are syntactical issues at the moment.
I would advocate splitting up your code into two methods (unless you're specifically prohibited from doing so based on the assignment). One method to get the grades from the user, and another to sum the grades. The reason for this, is that you end up trying to both store and sum the grades at the same time (which is technically more efficient), but that doesn't teach you how to calculate a running total by iterating over an array (which is likely the point of the lesson).
One other thing that I would call out (which may be beyond where you are in the course right now), is that when you're using a Scanner, you need to validate that the user has typed what you think they've typed. It's entirely plausible that you want the user to type a number, and they type "Avocado." Because Java is strongly typed, this will cause your program to throw an exception and crash. I've added in some basic input validations as an example of how you can do this; the general idea is:
1) Check that the Scanner has an int
2) If it doesn't have an int, ask the user to try again
3) Else, it has an int and you're good to proceed. Store the value.
One last thing about Scanners. Remember to close them! If you don't, you can end up with a memory leak as the Scanner continues to run.
Below is how I would have revised your code to do what you want. Shoot me a comment if something doesn't make sense, and I'll explain further. I left comments inline, as I figured that was easier to digest!
package executor;
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Initial prompt to the user
System.out.println("Hello Drews, how many total grades do you want to process?");
// This loop validates that the user has actually entered an integer, and prevents
// an InputMismatchException from being thrown and blowing up the program.
int numberOfGrades = 0;
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
// If the program makes it through the while loop, we know that the Scanner has an int, and can assign it.
numberOfGrades = keyboard.nextInt();
// Creating the array using the method getGrades().
int[] storedGrades = getGrades(numberOfGrades, keyboard);
// Calculating the total score using the method getTotalScore().
int totalScore = getTotalScore(storedGrades);
System.out.println("Total Score is: " + totalScore);
keyboard.close();
}
/**
* Asks the user to provide a number of grades they wish to sum.
* #param numberOfGrades the total number of grades that will be requested from the user.
* #param keyboard the scanner that the user will use to provide the grades.
* #return the summed grades as an int.
*/
public static int[] getGrades(int numberOfGrades, Scanner keyboard) {
int[] grades = new int[numberOfGrades];
// Asking the user i number of times, to enter a grade to store.
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ":");
// More input validation to ensure the user can't store "Cat."
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
int userEnteredGrade = keyboard.nextInt();
// Storing the user's entry.
grades[i] = userEnteredGrade;
}
return grades;
}
/**
* Sums all of the grades stored within an integer array.
* #param storedGrades the grades to be summed.
* #return the total value of summed grades.
*/
public static int getTotalScore(int[] storedGrades) {
int totalScore = 0;
for (int i = 0; i < storedGrades.length; i++) {
totalScore += storedGrades[i];
}
return totalScore;
}
}
I need to have three arrays. The first array will allow the user to enter the points scored by a basketball team of 10 players for game 1. The second array will allow the user to enter the points scored for game 2. The third array will add the first two arrays together.
I'm stuck on the first part. I don't understand how to get the user to enter a number. I tried an input, but I got an error. How do I make it so the user can enter a number?
import java.util.Scanner;
public class array2 {
public static void main(String[] args) {
int i;
int [] game1 = new int[10];
// Enter Points scored by players in game 1
// Enter points scored by players in game 2
// Add arrays together
Scanner scanLine = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
for (i=0;i<game1.length;i++)
{
System.out.println ("The score of game 1 is " + game1[i]);
}
}
}
You can get points scored by a basketball team of 10 players for game1 array in following way...
Scanner scanner = new Scanner(System.in);
int[] game1 = new int[10];
for (int i = 0; i < 10; i++) {
game1[i] = scanner.nextInt();
}
scanner.close();
After doing this, you can print the array so that you can verify that you have got correct input from the user while you are developing the feature...
for (int i = 0; i < 10; i++) {
System.out.println(game1[i]);
}
And after that, you can get points scored by a team of 10 players for game-2 and game-3 in game2 and game3 arrays respectively...
Firstly, you only need one Scanner - you can use it as many times as you like.
At the point in your code where you need to read something, set a variable equal to
scanLine.nextLine()
Or
scanLine.nextInt()
You'll probably want to do some input validation on what you've scanner to make sure it is what you're expecting
The Java API documents for Scanner should be quite helpful for understanding how to use a scanner.
If points scored is integer type, try use nextInt() to read one integer:
Scanner scanner = new Scanner(System.in)
int number = scanner.nextInt();
Then you can save your input in array:
game1[0] = number;
For fill array you can use for loop:
for(i=0; i < game1.length; i++){
game1[i] = scanner.nextInt();
}
the user must input a set of numbers of type double that we must then find the number that equalizes the numbers
here is a link to the question
https://www.dropbox.com/s/0hlps5r8anhjjd8/group.jpg
I tried to solve it myself, I did the basics, but for the actual solution I don't even know where to start ?_? any hint would be much helpful
Here my attempt:
import java.util.Scanner;
public class test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int arr =1000000;
while(arr > 10000) {
System.out.println("enter number of students that are providing the money");
arr = input.nextInt(); //user input for the size of the array
}
double size[] = new double[arr]; //array creation , size based on user input
for (int i =0; i<size.length;i++) { //to input values into the array
System.out.println("enter amount of money");
size[i] = input.nextDouble(); //input values into the array
}
for(int i=0; i<size.length;i++) { //prints out the array
System.out.println(size[i]);
}
}
}
Thank you in advance
Step 1. Read the data for a test case and put it into a suitable structure. I would probably choose a double contribution[] for this assignment.
Step 2. Calculate the average contribution, avg.
Step 3. Sum up the amount of money that need to change hands. sum over abs(contribution[i]-avg). Note: Don't forget to divide the total by 2.
I am writing a program which lets the user put their own size of columns and rows for an array. I am using doubles so that the user can use decimals. However, I am getting this error that is telling me that I cannot convert doubles to integers. I don't understand why. I am using eclipse. I declare the array before the main method so I can use it freely the methods throughout the program.
import java.util.*;
public class array
{
private double themainarray[][];
Scanner input = new Scanner(System.in);
private double columnsize;
private double rowsize;
public static void main(String[] args)
{
System.out.print("Welcome!");
}
//Below on the last line of the method is where I am getting the error from eclipse.
public void arrayDimensions()
{
System.out.println("How many columns would you like?");
columnsize = input.nextDouble();
System.out.println("How many rows would you like?");
rowsize= input.nextDouble();
themainarray= new double [rowsize][columnsize];
}
}
array size variables should be of type int only.Other are not allowed.
In your code rowSize,columnSize should be of type int.
You need an int for sizing an array.
private double themainarray[][];
Scanner input = new Scanner(System.in);
private int columnsize;
private int rowsize;
Then when reading input from the user use nextInt();
Write the following methods:
13. A method named loadScores that will be passed the size of an array, prompt the user to enter the appropriate number of floating point grades, then return the loaded array.
I wrote the method, but the problem comes when I try to call it. Here's what I have:
public class ArrayHandout {
public static void main(String[] args) {
int size = loadScores(size);
double[] scoresArray = loadScores(size);
} // end main
public static double[] loadScores(int size) {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
} // end loadScores
} // end class
I have changed a few things in an attempt to correct some errors I was having when I wrote the original code, and unfortunately don't even remember what those changes were or if they fixed the problems since I can't get it to compile now. I do know that the problem I was having when I could get the original to compile was that it was only printing the first number in the array rather than printing the entire array. Like I said, I don't know if that problem has been corrected since now when I try to compile I receive the following error message:
1 error found:
File: C:\Users\HiTechRedneck\Desktop\Fall 2013\PlayingwithJava\ArrayHandout.java [line: 6]
Error: incompatible types
required: int
found: double[]
I know that size needs to be declared in main because previously I was getting the "cannot find variable size" error, but I think the fact that I'm trying to declare int size as loadScores(size) is throwing it off since the variable I'm declaring is also an argument in the method.
Any help would be greatly appreciated.
Your line int size = loadScores(size) is incorrect. loadScores has a return type of double[], so you need to assign that return value as such.
Just delete that one line and everything should work as expected.
int size = loadScores(size); is throwing an error because loadScores returns an array of type double.
Since the task just wants a code snippet you could probably give size an arbitrary value and pass that in. Or you could get rid of size in main and just pass a number in:
public static void main(String[] args) {
double[] scoresArray = loadScores(5);
}
Edit: Also worth noting that the print statement after the for loop will throw an ArrayIndexOutOfBoundsException since i is now greater than the length of the array. If you want to print the contents of the scoresArray you'll need another loop to traverse through each element.
Second edit: If you're prompting the user for a size you should run your prompt for that in the main method and then pass that to loadScores().
You don't need size at all before you call the function as you read it in the function
your declaration could be :
public static double[] loadScores()
and call
loadScores()
in main. Example:
public class ArrayHandout {
public static void main(String[] args) {
double[] scoresArray = loadScores();
//do whatever you want here or change declaration of
//the function to void and do not return anything
}
public static double[] loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
}
}
if you don't use the returned array it would be better to do it like this:
public class ArrayHandout {
public static void main(String[] args) {
loadScores();
}
public static void loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
}
}
(When a method doesn't return anything you have to specify it by using the void keyword in its signature)-You also need validation but I was only answering to the specific problem -without validation your program will still fail if incompatible values are given.