import java.util.Random;
import java.util.Scanner;
public class LotteryGame{
public static void main(String[] args) {
int NUM_DIGITS = 6;
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
sameNum = compareArrays(lotteryNumbers, userDigits);
System.out.println("Winning numbers: " + lotteryNumbers[0] + " "
+ lotteryNumbers[1] + " " + lotteryNumbers[2] + " "
+ lotteryNumbers[3] + " " + lotteryNumbers[4] + " " + lotteryNumbers[5] + " ");
System.out.println("Your numbers: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " " + userDigits[5] +" ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 6) {
System.out.println("First prize!!!");
}
if (sameNum == 5) {
System.out.println("Second prize!!!");
}
if (sameNum == 0) {
System.out.println("No matching numbers, you lost.");
}
}
public static void generateNumbers(int[] lotteryNumbers) {
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(59);
lotteryNumbers[1] = randNum.nextInt(59);
lotteryNumbers[2] = randNum.nextInt(59);
lotteryNumbers[3] = randNum.nextInt(59);
lotteryNumbers[4] = randNum.nextInt(59);
lotteryNumbers[5] = randNum.nextInt(59);
return lotteryNumbers[5];
}
public static void getUserData(int[] userDigits) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter first digit: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter second digit: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter third digit: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter fourth digit: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter fifth digit: ");
userDigits[4] = keyboard.nextInt();
System.out.print("Enter sixth digit: ");
userDigits[5] = keyboard.nextInt();
return userDigits[5];
}
public static int compareArrays(int[] userDigits, int[] lotteryNumbers) {
int sameNum = 0;
for (int i = 0; i < 6; i++) {
for (int x = 0; x < 5; x++) {
if (lotteryNumbers[i] == userDigits[x]) {
sameNum++;
}
}
}
return sameNum;
}
}
When I compile I get the following errors-
LotteryGame.java:51: error: incompatible types: unexpected return value
return lotteryNumbers[5];
^
LotteryGame.java:72: error: incompatible types: unexpected return value
return userDigits[5];
^
2 errors
Can any of you help me with these compilation errors? I'm trying to get this to work. The user is supposed to input 6 numbers, and the program is supposed to pick randomly 6 numbers. Using these numbers, the program will compare the numbers with echoed input.
generateNumbers and getUserData are void functions, meaning they don't return anything, so you can't return anything from them.
You probably want to declare them as functions returning int instead:
public static int generateNumbers(int[] lotteryNumbers)
Univerio is correct in answering your original question.
Looking at your test code you might consider removing the return statement on those two functions since you are just populating both arrays.
Related
import java.util.Scanner;
public class ComparingNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int FirstNum = Integer.valueOf(scanner.nextLine());
int SecondNum = Integer.valueOf(scanner.nextLine());
if (FirstNum > SecondNum) {
System.out.println(FirstNum + " is greater than " + SecondNum + ".");
} else if (FirstNum < SecondNum) {
System.out.println(FirstNum + " is smaller than " + SecondNum + ".");
} else {
System.out.println(FirstNum + " is equal to " + SecondNum + ".");
}
}
}
Line 9: Name 'FirstNum' must match pattern '^[a-z][a-zA-Z0-9]$'.
Line 10: Name 'SecondNum' must match pattern '^[a-z][a-zA-Z0-9]$'.
What is the issue with my variable names?. I am a beginner so a simple answer will be greatly appreciated.
Java variable names should be camelCase. Variable names should be firstNum and secondNum.
I am having trouble with the logic I think. My results are not adding up correctly. Can someone please help? The problem is in the arrayList.size, nums.length or something. I entered 50 40 60 as my integers.
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (input.hasNextInt()) {
list.add(input.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
System.out.printf("%s", "You entered: ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d%s", nums[i], ", ");
}
Collections.sort(list);
int b = Collections.max(list);
int c = Collections.min(list);
int arraySize = nums.length-1;
double sum = 0;
for(int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
System.out.println(" \nLast Number is : " + list.get(arraySize)
+ "\nLargest Number is: " + b
+ "\nSmallest number is :" + c
+ "\n" + "You entered " + (arraySize+1) + " numbers"
+ "\nTotal numbers added up is: " + sum
+ "\nAverage number is: " + (sum / (nums.length)));
input.close();
}
}
You are sorting list so it will return last value from sorted list. Collections.sort(list) is sorting asc so you get max number from the list. First approach,
1) Either you have to manage origanal list before sorting like
ArrayList<Integer> ori = new ArrayList<Integer>(list);
Collections.sort(list);
And get the value from ori.
System.out.println(" \nLast Number is : " + ori.get(list.size()-1)
2) Second approach, Create variable which will store temp last entered value. you can use it.
Might it helps!!
So your example like:
public static void main(final String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (input.hasNextInt()) {
list.add(input.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
System.out.printf("%s", "You entered: ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d%s", nums[i], ", ");
}
ArrayList<Integer> ori = new ArrayList<Integer>(list);
Collections.sort(list);
int b = Collections.max(list);
int c = Collections.min(list);
int arraySize = nums.length-1;
double sum = 0;
for(int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
System.out.println(" \nLast Number is : " + ori.get(list.size()-1)
+ "\nLargest Number is: " + b
+ "\nSmallest number is :" + c
+ "\n" + "You entered " + (arraySize+1) + " numbers"
+ "\nTotal numbers added up is: " + sum
+ "\nAverage number is: " + (sum / (nums.length)));
input.close();
}
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =Keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = Keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
}else{
System.out.println("Wrong!");
}
System.out.println("The correct answer is " +sum);
I have no clue on how to keep track of the correct answers. I need something to keep track of when it prints correct. I don't know what to do though. I know I just need to record the corrects and divide by four. Four because thats how many questions I have in my quiz.
If you just need to keep track of how many right answers were provided, just add an int variable starting with 0 as a value and increment it. If you want to keep track of the questions and answers which were right, create an empty ArrayList and add a string every time a correct answer is provided.
Here an example of the second option:
ArrayList<String> correctAnswers = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
for (int i=0;i<10;i++) {
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
correctAnswers.add(x + " + " + y + " = " + sum);
}
else{
System.out.println("Wrong!");
System.out.println("The correct answer is " +sum);
}
}
System.out.println("Correct answers:");
for (String correctAnswer : correctAnswers) {
System.out.println(correctAnswer);
}
It asks 10 questions, keeps track of the right answers and outputs them after the 10th question.
An example for the first option:
int correctAnswers=0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
int totalAnswers=4;
for (int i=0;i<totalAnswers;i++) {
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
correctAnswers++;
}
else{
System.out.println("Wrong!");
System.out.println("The correct answer is " +sum);
}
}
System.out.println("Correct answers: "+ correctAnswers + "("+correctAnswers*100/totalAnswers+"%)");
Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}
My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);