How do I make this if statement? - java

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");
}
}
}

Related

I want to find max and min values in java

I want max and min values of salary to display but i get same values for max and min. Here's my code:
import java.util.*;
class Wage {
String employee_name, skill;
int hours;
double sum;
String[] sno = {"1", "2", "3", "4"};
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
Scanner s = new Scanner(System.in);
public void getEmployeeDetails() {
System.out.println("Welcome to Use General Wage Record System");
for (String count : sno) {
if (count.equalsIgnoreCase("1")) {
System.out.print("Enter Name of Employee 1: ");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("2")) {
System.out.print("Enter Name of Employee 2:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee " + employee_name + "(Level " + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("3")) {
System.out.print("Enter Name of Employee 3:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " $" + sum);
}
}
if (count.equalsIgnoreCase("4")) {
System.out.print("Enter Name of Employee 4:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + "$ " + sum);
}
}
}
}
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
if (sum > max) {
max = sum;
System.out.println("Maximum of wage" + max + ", " + employee_name);
}
if (sum < min) {
min= sum ;
System.out.println("Minimum of Wage" + min + ", " + employee_name);
}
}
}
public class Pay {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Wage wm = new Wage();
wm.getEmployeeDetails();
wm.average();
}
In the loop of the getEmployeeDetails() method, you don't store and update the min wage, the max wage and the employee names that have these wages.
Besides, you should be more specific in the naming. For example, maxWage and minWage are more meaningful than max and min.
So, you should have maxWage, maxWageEmployeeName, minWage and minWageEmployeeName fields in the field declaration of the Wage class.
At each employee inserted in the system, you should update these values by calling a dedicated method:
public void getEmployeeDetails() {
if (count.equalsIgnoreCase("1")) {
....
updateRanking(sum, employee_name);
}
}
public void updateRanking(double actualWage, String employee_name){
if (actualWage > maxWage) {
maxWage = actualWage;
maxWageEmployeeName = employee_name;
}
else if (actualWage < minWage) {
minWage = actualWage;
minWageEmployeeName = employee_name;
}
}
Besides, your average() method called at the end of your program should only display the result and not performing comparison since you should have updated information about max, min wage and who have these as updateRanking() is called at each insertion of employee wage :
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
System.out.println("Maximum of wage" + maxWage + ", " + maxWageEmployeeName );
System.out.println("Minimum of Wage" + minWage + ", " + minWageEmployeeName );
}

Sports game summary using Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
IndexOutOfBounds with array
(5 answers)
Closed 6 years ago.
The basic idea of this assignment is to create a program that can provide a summary and identify who won a "match" in a sports event (football, basketball, Soccer, baseball, etc.)
**This is my code:**
`import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask questions about the game type etc.
System.out.println("Please enter game name: ");
String gameName = sc.next();
System.out.println("Please enter " + gameName + " team 1 name: ");
String t1N = sc.next();
System.out.println("Please enter " + gameName + " team 2 name: ");
String t2N = sc.next();
System.out.println("What is a score in " + gameName + " called? ");
String scoreName = sc.next();
System.out.println("How many points per " + scoreName + " in " + gameName + "?");
int scoreValue = sc.nextInt();
System.out.println("What is a period in " + gameName + " called?");
String periodName = sc.next();
System.out.println("How many " + periodName + " in " + gameName + "?");
int numberOfPeriods = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
for (int i = 1; i <= numberOfPeriods; i++) {
System.out.println(periodName + " #" + i);
System.out.println("How many " + scoreName + " for " + t1N + "?");
int numberOfScoresT1[] = new int[sc.nextInt()];
System.out.println("How many " + scoreName + " for " + t2N + "?");
int numberOfScoresT2[] = new int[sc.nextInt()];
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum1 += numberOfScoresT1[counter];
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum2 += numberOfScoresT2[counter];
}
System.out.println("Team 1 scored " + sum1 + " team 2 scored " + sum2);
}`
This is the error I'm receiving:
Please enter game name:
Football
Please enter Football team 1 name:
Dolphins
Please enter Football team 2 name:
Jaguars
What is a score in Fotball called?
Touchdown
How many points per Touchdown in Fotball?
7
What is a period in Fotball called?
Quarter
How many Quarter in Fotball?
4
Quarter #1
How many Touchdown for Dolphins?
3
How many Touchdown for Jaguars?
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Team.main(Team.java:36)
I recognize that the arrays I'm using are in the for loop, and I think thats what is causing the problem, but i'm not sure how to fix it.
This is a sample output is supposed to look like:
Quarter #1:
How many Touchdowns for Dolphins? 2
How many Touchdowns for Chargers? 1
Quarter #2:
How many Touchdowns for Dolphins? 0
How many Touchdowns for Chargers? 1
Quarter #3:
How many Touchdowns for Dolphins? 0
How many Touchdowns for Chargers? 2
Quarter #4:
How many Touchdowns for Dolphins? 3
How many Touchdowns for Chargers? 0
Football Game Results:
Dolphins scored 5 Touchdowns for a score of 35
Chargers scored 4 Touchdowns for a score of 28
Dolphins Win by 7 points!
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum2 += numberOfScoresT2[counter];
Should the second parameter of the loop be
for (int counter = 0; counter < numberOfScoresT2.length; counter++)
seeing as you are accessing numberOfScoresT2 array in the body.
Your inner for loops should be as follows
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum1 += numberOfScoresT1[counter];
for (int counter = 0; counter < numberOfScoresT2.length; counter++)
sum2 += numberOfScoresT2[counter];
You have used length of array numberOfScoresT1 instead of array numberOfScoresT2 in second inner for loops.
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask questions about the game type etc.
System.out.println("Please enter game name: ");
String gameName = sc.next();
System.out.println("Please enter " + gameName + " team 1 name: ");
String t1N = sc.next();
System.out.println("Please enter " + gameName + " team 2 name: ");
String t2N = sc.next();
System.out.println("What is a score in " + gameName + " called? ");
String scoreName = sc.next();
System.out.println("How many points per " + scoreName + " in " + gameName + "?");
int scoreValue = sc.nextInt();
System.out.println("What is a period in " + gameName + " called?");
String periodName = sc.next();
System.out.println("How many " + periodName + " in " + gameName + "?");
int numberOfPeriods = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
int numberOfScoresT1[] = new int[numberOfPeriods];
int numberOfScoresT2[] = new int[numberOfPeriods];
for (int i = 0; i <numberOfPeriods; i++) {
System.out.println(periodName + " #" + i);
System.out.println("How many " + scoreName + " for " + t1N + "?");
numberOfScoresT1[i] = sc.nextInt();
System.out.println("How many " + scoreName + " for " + t2N + "?");
numberOfScoresT2[i] = sc.nextInt();
}
sc.close();
for (int counter = 0; counter < numberOfPeriods; counter++) {
sum1 += numberOfScoresT1[counter];
sum2 += numberOfScoresT2[counter];
}
System.out.println("Team 1 scored " + sum1 + " team 2 scored " + sum2);
}
}

Array Length Outcome

My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02
If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.

How do i keep track of correct answers?

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+"%)");

I have 2 errors compiling my java Lottery program using arrays

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.

Categories

Resources