I'm really new to java (third week of class), but I've been trying to work on this code for hours and I just can't seem to find an answer to what I'm doing. javac tells me I only have three errors, but I'm wondering if there's more than that.
Here's my code, and I know my average section still needs work but i just cant figure out what's going on with the middle section of if and else statements. Sorry if this is really dumb, and im sure my syntax is all over the place:
import java.util.Scanner;
public class Program1
{
static public void main( String args [ ] )
{
int grade;
int A,B,C,D,F;
A = 0;
B = 0;
C = 0;
D = 0;
F = 0;
System.out.println( "*************** Grade Computer *************");
// ********************** //
Scanner kbd = new Scanner (System.in);
System.out.println("Enter Students First Name: ");
String fname = kbd.next( );
System.out.println("Enter Students Middle Initial: ");
String mi = kbd.next( );
System.out.println("Enter Students Last Name: ");
String lname = kbd.next( );
System.out.println("Enter First Exam Grade: ");
int firstexam = kbd.nextInt( );
System.out.println("Enter Second Exam Grade: ");
int secondexam = kbd.nextInt( );
System.out.println("Enter Third Exam Grade: ");
int thirdexam = kbd.nextInt( );
System.out.println("Was the bonus done? [yes/no] : ");
boolean b = kbd.nextBoolean( );
boolean yes = true;
boolean no = false;
// *********************** //
if(true)
{
{
if((firstexam >= (secondexam * 0.60 ) ) & (firstexam >= (thirdexam * 0.80 )));
{
System.out.println(firstexam);
}
else if((secondexam * 0.60) >= (thirdexam * 0.80));
{
System.out.println(secondexam * 0.60);
}
else {
System.out.println(thirdexam * 0.80);
}
}
if(true)
{
if((secondexam >= firstexam) & ((thirdexam * 0.80) >= secondexam));
{
if(secondexam >= (thirdexam * 0.80));
{
System.out.println(secondexam);
}
}
else {
System.out.println(thirdexam * 0.80);
}
}
else {
System.out.println(firstexam);
System.out.println(secondexam);
System.out.println(thirdexam);
}
}
// ********************** //
System.out.println(" **********Grade Summary********** ");
double average = calcAverage(firstexam, secondexam, thirdexam);
System.out.println("Grade Report For: " + fname);
if (true)
{
System.out.println("Bonus was done so grades are adjusted if appropriate.");
}
else
{
System.out.println("Bonus was not done.");
}
System.out.println("Exam 1: " + firstexam);
System.out.println("Exam 2: " + secondexam);
System.out.println("Exam 3: " + thirdexam);
System.out.println("The average is: " + average);
determineGrade(average);
}
public static double calcAverage(int firstexam, int secondexam, int thirdexam)
{
double average = (firstexam + secondexam + thirdexam) / 3.0;
return average;
}
public static void determineGrade(double average)
{
if (average>90)
{
System.out.println("Grade: A");
}
else if (average>=80)
{
System.out.println("Grade: B");
}
else if (average>=70)
{
System.out.println("Grade: C");
}
else if (average>=60)
{
System.out.println("Grade: D");
}
else if (average<60)
{
System.out.println("Grade: F");
}
}
// ************** //
}
Your if statements having ; in the end
if((firstexam >= (secondexam * 0.60 ) ) & (firstexam >= (thirdexam * 0.80 )));
They are considering as statements and proceeding further.
Remove all of them in the end of each statement.
if((firstexam >= (secondexam * 0.60 ) ) & (firstexam >= (thirdexam * 0.80 ))) (;)
The ; shouldn't be here.
Difference between & and && :
& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false
(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.
(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).
An other thing :
if(true)
{
{
This should be deleted because it just adds more code , it will be executed every time so no need to add it.
Besides the colon the end of the if statement you also should keep in mind that if you use
if(true){
}else{
}
The else statement will never execute cos the if will always be true, so you should be using the yes/no variables as flags for your if statement instead of the "true" itself.
If your statements inside the if should always be executed then you don't need the conditions at all.
Related
I have a program that takes one's income and multiplies it by a factor according to the income given. It also gives a code either 1 or 0 that defines the range of the incomes accordingly.
It seems correct on a first sight but I seem to get errors that concern the if statements that exist in the method that I use in order to calculate the incomes.
The code is the following:
import java.util.Scanner;
public class IncomeCalc{
public void Cal(double inc, int code)
{
if( code == 0 )
{
if((inc >= 0) && (inc <= 5,000))
{
System.out.println("Your tax declaration is "+ inc*0.1);
}else if((inc >= 5,001) && (inc <= 10,000))
{
System.out.println("Your tax declaration is "+ inc*0.15);
}else if((inc >= 10,001) && (inc <= 20,000))
{
System.out.println("Your tax declaration is "+ inc*0.25);
}else if(inc >= 20,001)
{
System.out.println("Your tax declaration is "+ inc*0.35);
}
}
else if( code == 1 )
{
if((inc >= 0) && (inc <= 10,000))
{
System.out.println("Your tax declaration is "+ inc*0.1);
}else if((inc >= 10,001) && (inc <= 20,000))
{
System.out.println("Your tax declaration is "+ inc*0.15);
}else if((inc >= 20,001) && (inc <= 30,000))
{
System.out.println("Your tax declaration is "+ inc*0.25);
}else if(inc >= 30,001)
{
System.out.println("Your tax declaration is "+ inc*0.35);
}
}
}
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
System.out.println("Enter your annual income");
double income = obj.nextDouble();
Scanner obj2 = new Scanner(System.in);
System.out.println("If you are an individual choose 0 else choose 1 ");
int decl = obj2.nextInt();
Cal(income, decl);
}
}
Thank you!!!
Are you actually using commas to separate digits? if so this is your issue, also don't create 2 scanner objects, use the same one for both operations.
So the program works, it just has a few things that I cant seem to fix:
1) It feels like it can be simplified using more/different methods. I don't want ot be redundant.
2) At the end of the program, I can't get figure out how to turn the two final scores into "first" and "second" We aren't allowed to use several sopln's the program has to be able to identify which of the two scores is highest and be able to recognize if it was the first or second applicant. Here is the code
import java.util.Scanner;
public class Admissions {
public static void main(String[] args) {
questionaire();
Scanner console = new Scanner(System.in);
double first = designation(console, " first ");
double second = designation(console, " second ");
System.out.println("First applicant overall score = " + first);
System.out.println("Second applicant overall score = " + second);
System.out.println();
double mostQualified = (Math.max(first,second));
System.out.println("The " + mostQualified + " applicant is better qualified.");
}
// *** Methods ***
public static void questionaire() {
System.out.println(" This program compares two applicants to \n " +
"determine which one is the stronger candidate. \n " +
"For each candidate please provide either SAT \n " +
"or ACT scores, plus a weighted GPA.");
System.out.println();
}
public static double designation(Scanner console, String x) {
System.out.println("Information for the" + x + "applicant: \n" +
"do you have 1) SAT scores or 2) ACT scores?");
int answer = console.nextInt();
if(answer == 2){
return act(console);
} else if (answer == 1){
return sat(console);
}else{
return cheat();
}
}
public static double designation2(Scanner console) {
System.out.println("Information for the second applicant: \n" +
"do you have 1) SAT scores or 2) ACT scores?");
int answer2 = console.nextInt();
if(answer2 == 2){
return act(console);
} else if (answer2 == 1){
return sat(console);
}else {
return cheat();
}
}
public static double act(Scanner console) {
System.out.println("ACT English?");
int actEnglish = console.nextInt();
if ((actEnglish < 1) || (actEnglish > 36)){
return cheat();
}
System.out.println("ACT math?");
int actMath = console.nextInt();
if ((actMath < 1) || (actMath > 36)){
return cheat();
}
System.out.println("ACT reading?");
int actReading = console.nextInt();
if ((actReading < 1) || (actReading > 36)){
return cheat();
}
System.out.println("ACT science?");
int actScience = console.nextInt();
if ((actScience < 1) || (actScience > 36)){
return cheat();
}
System.out.println("Overall GPA?");
double overallGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
System.out.println("Maximum GPA?");
double maxGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
int actScore = ((actScience - 1) + (actMath - 1) + (actReading - 1) + (actEnglish - 1) / (4*35));
double actGPA = ((overallGPA) / (maxGPA) * 100);
double finalActScore = (actScore + actGPA);
return finalActScore;
}
public static double sat(Scanner console){
System.out.println("SAT math?");
int satMath = console.nextInt();
if ((satMath < 200) || (satMath > 800)){
return cheat();
}
System.out.println("SAT verbal?");
int satVerbal = console.nextInt();
if ((satVerbal < 200) || (satVerbal > 800)){
return cheat();
}
System.out.println("Overall GPA?");
double overallGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
System.out.println("Maximum GPA?");
double maxGPA = console.nextDouble();
if ((overallGPA < 0.0) || (overallGPA > 4.0)){
return cheat();
}
int satScore = ((satVerbal - 200) + (satMath - 200)) / (2*600);
double satGPA = ((overallGPA) / (maxGPA) * 100);
double finalSatScore = (satScore + satGPA);
return finalSatScore;
}
public static double cheat(){
System.out.println("YOU'RE A CHEATER.");
System.exit(-1);
return 0;
}
1) You can factorize part of your code
You already did it with your designation method which is good. You can delete the designation2 method.
In your act method. There is 4 repetitions of this test :
if ((value < 1) || (value > 36)){
return cheat();
}
You can factorise it inside a method like this :
private void checkScoreForAct(int value) {
if ((value < 1) || (value > 36)){
cheat();
}
}
Then in your act method, you call it to check the ACT score for the english, math, reading and science.
System.out.println("ACT English?");
int actEnglish = console.nextInt();
checkScoreForAct(actEnglish);
That's one exemple but you could also factorise the part where you calculate the overall GPA (present in the act and sat method).
Same for when you calculate the satGPA and actGPA, you could put this logic in a method.
2) How to turn the two final scores into first and second ?
You can easily check who is the applicant who have the best score.
public static String FIRST = "first";
public static String SECOND = "second";
public static String BOTH = "both";
String bestApplicant;
if (first == second) {
bestApplicant = BOTH;
} else if (first > second) {
bestApplicant = FIRST;
} else {
bestApplicant = SECOND;
}
double maxScore = (Math.max(first,second));
if (bestApplicant.equals(BOTH)) {
System.out.println("Both applicant are equally qualified with a score of " + maxScore);
} else {
System.out.println("The " + bestApplicant + " applicant is better qualified with a score of " + maxScore);
}
I'm not sure if your parameters exclude this, as what you say you aren't allowed to do makes no sense to me. Here's what you seem to be asking how to do:
String mostQualified = (first > second)? "first" : "second";
double bestScore = Math.max(first, second);
System.out.println("The " + mostQualified
+ " applicant is better qualified, with a score of "
+ bestScore);
Sample result:
The first applicant is better qualified, with a score of 88.1
I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();
Whats happening is when I try to add a new class to my student, I have to check to make sure that the class time I am trying to add doesn't conflict with my students other class times, but for some reason when the code gets into the loop to check the other course times stored in an array list, there is an exeption called when their shouldn't be. For example, I could put in 5:00p-10:00p for one course, then 1:00p-2:00p for the second course and it will throw the exception like there is a conflict there when there isn't. please check the comment to see where the problem occurs. any ideas?
package myschool;
import java.util.ArrayList;
import java.util.Scanner;
public class MySchool {
private static Exception e;
public static void main(String[] args) {
ArrayList<Student> listStudent = new ArrayList<>();
ArrayList<Integer> listCourseStart = new ArrayList<>();
ArrayList<Integer> listCourseEnd = new ArrayList<>();
boolean continueLoop = true;
boolean addFirstCourse = true;
boolean addACourse = false;
Scanner userInput = new Scanner(System.in);
int option;
do{
try {
System.out.println(" What would you like to do?");
System.out.println(" 1) Add a student");
System.out.println(" 2) View students");
System.out.println(" 3) Remove a student");
System.out.println(" 4) Exit");
System.out.print("--> ");
option = userInput.nextInt();
switch( option ){
case 1:
Scanner inputs = new Scanner(System.in);
String fName, lName;
int sID;
double sGPA;
System.out.print(" First Name:");
fName = inputs.nextLine();
System.out.print(" Last Name:");
lName = inputs.nextLine();
System.out.print(" ID Number:");
sID = inputs.nextInt();
System.out.print(" GPA:");
sGPA = inputs.nextDouble();
Student newStudent = new Student(fName, lName, sID, sGPA);
listStudent.add(newStudent);
inputs.nextLine();
while (true) {
try {
System.out.println("Would you like to add a course? Y/N");
String shouldAddCourse = inputs.nextLine();
if( "N".equals(shouldAddCourse.toUpperCase()))
break;
System.out.print(" CourseName:");
String cName = inputs.nextLine();
System.out.print(" Instructor:");
String instructor = inputs.nextLine();
System.out.print(" CourseID:");
int cID = inputs.nextInt();
System.out.print(" CourseCredit:");
int cCred = inputs.nextInt();
inputs.nextLine();
System.out.print(" StartTime:");
String cStart = inputs.nextLine();
System.out.print(" AM or PM ?");
String startAMorPM = inputs.nextLine();
System.out.print(" EndTime:");
String cEnd = inputs.nextLine();
System.out.print(" AM or PM ?");
String endAMorPM = inputs.nextLine();
String cStartRemove = cStart.replace(":","");
int startInt = Integer.parseInt( cStartRemove );
String cEndRemove = cEnd.replace(":","");
int endInt = Integer.parseInt( cEndRemove );
if( "PM".equals(startAMorPM) || "pm".equals(startAMorPM) || "P".equals(startAMorPM) || "p".equals(startAMorPM) )
startInt = startInt + 1200;
if( "PM".equals(endAMorPM) || "pm".equals(endAMorPM) || "P".equals(endAMorPM) || "p".equals(endAMorPM) )
endInt = endInt + 1200;
if( addFirstCourse ){
Course newCourse = new Course( cName, instructor, cCred, cStart, cEnd, cID );
newStudent.listCourse.add(newCourse);
listCourseStart.add( startInt );
listCourseEnd.add( endInt );
addFirstCourse = false;
}else{
for( Integer r: listCourseStart ) {
if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) /*|| endInt >= listCourseStart.get(r) && endInt <= listCourseEnd.get(r)*/ ) //the problems happens hear on the first listCourseStart.get(r)
throw e;
else
addACourse = true;
}
if( addACourse == true ){
listCourseStart.add( startInt );
listCourseEnd.add( endInt );
Course newCourse = new Course( cName, instructor, cCred, cStart, cEnd, cID );
newStudent.listCourse.add(newCourse);
addACourse = false;
}
}
} catch (Exception e) {
System.out.println("You have already added a class at that time!");
}
}
break;
case 2:
if(!listStudent.isEmpty()){
for(Student l:listStudent) {
System.out.println(l);
for(Course n:l.listCourse) {
System.out.println(n);
}
System.out.println();
}
}else
System.out.println("There are no students to view\n");
break;
case 3:
Scanner removeChoice = new Scanner(System.in);
try {
if(!listStudent.isEmpty()){
int j = 0;
System.out.println("Which student do you want to remove?");
for(Student l:listStudent) {
System.out.print(j+1 + ")");
System.out.println(l);
j++;
}
int remove = removeChoice.nextInt();
listStudent.remove( remove - 1 );
System.out.println("Student has been removed\n");
}else
System.out.println("There are no students to remove\n");
} catch (Exception e) {
System.out.println("There are no students to remove\n");
}
break;
case 4:
continueLoop = false;
break;
}
} catch (Exception e) {
System.out.println("That is not a valid option!!!");
continueLoop = false;
}
}while( continueLoop );
}
}
You're throwing an exception in your for loop.
for( Integer r: listCourseStart ) {
if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) /*|| endInt >= listCourseStart.get(r) && endInt <= listCourseEnd.get(r)*/ ) //the problems happens hear on the first listCourseStart.get(r)
throw e;// <-- This guy is the culprit, but I'm guessing you already knew that...
else
addACourse = true;
}
It's fairly difficult to say exactly where it's going wrong (it's a bit hard to read your code, but it should be behaving as you've stated).
You may want to use some breakpoints, if you're using an IDE, and check the values of your input variables before they get put into the list, or have it spit them back out at you on the command line, before putting them in the list.
You are misusing the list listCourseStart in the for loop.
for( Integer r: listCourseStart ) {
if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) )
throw e;
else
addACourse = true;
}
listCourseStart is a list of intergers and with
for( Integer r: listCourseStart ) {
// ...
}
you iterate over the list elements. So in the first iteration r will be the first list element, in the second iteration the second list element and so on.
But inside your loop you call listCourseStart.get(r). The list's get() method retrieves the list element at the given position. So if the first list element is 5 then with listCourseStart.get(5) you get the fifth list element. I'm sure, this is not really what you want.
Why didn't you use a debugger? You can run your program step by step, it shows you the actual variable values so you can see what's going on in detail.
I think the problem is your loop
for( Integer r: listCourseStart ) { // r ist the value in listCourseStart
// you use the value 'r' as index
// you have to use for( int i = 0; i.....) or 'r' is the the right value
if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) )
throw e;
else
addACourse = true;
}
Try this
for( Integer r: listCourseStart ) {
if( startInt >= r && startInt <= r )
throw e;
else
addACourse = true;
}
EDIT:
Yout are right in your comment. Your condition is not necessary. You need to store the start and end time together. Here is an exsample:
List<Integer[]> times = new ArrayList<>();
times.add(new Integer[]{900,1100});
times.add(new Integer[]{1300,1400});
for( Integer[] time : times ){
if( startInt >= time[0] && startInt <= time[1]
|| endInt >= time[0] && endInt <= time[1] ){
throw e;
}
}
A little Hint: Your Exception e was never initiate - you will get a NullPointerException
I wrote some code that is supposed to ask for input from the user and assign it to the String skillAssign. When I try to asses skillAssign, it returns false no matter what. Here is my code:
import java.util.*;
public class CharacterCustomization
{
public CharacterCustomization()
{
}
public static void Customization()
{
Scanner keyboard = new Scanner(System.in);
int skillPoints = 100;
String skillAssign = "";
int newMaxHealth = 0;
int newMaxMagic = 0;
int newMaxStamina = 0;
int assignmentValue = 0;
boolean isDone = false;
System.out.println("Welcome to character customization, you have 100 points to allocate to your skills.");
System.out.println("To allocate points, type name of skill, followed by the points you want to assign (blank for positive, - for negative, ex. -5)");
System.out.println("Put Skill on one line, and press enter, then the value on the next line");
System.out.println("Type \"stats\" to view full stats at any time");
System.out.println("Type \"done\" to finish");
while (true)
{
while (isDone == false)
{
skillAssign = keyboard.nextLine();
if (skillPoints == 0)
{
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
System.out.println("Type \"done\"to finish");
}
if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
{
assignmentValue = keyboard.nextInt();
if (((skillAssign.equals("health")) || (skillAssign.equals("Health"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxHealth = (assignmentValue + newMaxHealth);
}
else if (((skillAssign.equals("magic")) || (skillAssign.equals("Magic"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxMagic = (assignmentValue + newMaxMagic);
}
else if (((skillAssign.equals("stamina")) || (skillAssign.equals("Stamina"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxStamina = (assignmentValue + newMaxStamina);
}
else
{
//System.out.println("Sorry, I could not read that!");
System.out.println(skillAssign == "stats");
}
}
else if (skillAssign.equals("stats"))
{
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
}
else if ((skillAssign.equals("done")) || (skillAssign.equals("Done")))
{
isDone = true;
continue;
}
else
{
System.out.println("Sorry, I could not read that!");
}
}
System.out.println("Are you sure this is the setup you want? [y] [n]");
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
//skillAssign = keyboard.nextLine();
if (((keyboard.nextLine()).equals("y")) || ((keyboard.nextLine()).equals("Y")) || ((keyboard.nextLine()).equals("yes")) || ((keyboard.nextLine()).equals("Yes")))
{
Player player = new Player(newMaxHealth, newMaxMagic, newMaxStamina);
}
else
{
isDone = false;
}
}
}
}
Its not complete, but Im inputting stats when prompted and all evaluations of it are false
Is there a way I can get it to read the variable properly?
You will always get in inside this condition scope if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
It because that when one word failed to pass it, the other condition will let it pass, because they are different completely.
e.g:
let's take "stats", this will results with if (false || true) => true.
let's take "done", this will results with if (true || false) => true.
let's take "sTats", this will results with if (true || true) => true.
You can't escape it, you need to check it like that:
if (!(skillAssign.equals("stats") || skillAssign.equals("done")))
this way we're checking if either of the logical expression are true, then we change it to "not" and then checking if the whole condition is true.
P.S
A. You can use "abc".equalsIgnoreCase("AbC") instead what you're using now.
B. Don't add for every logical expression parenthesis it's making the code more complex and unclear for the first glance.
The problem was that I was using || instead of && in the if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
What ever Orel said is pretty much it. Just wanna add if you are using System.out.println(skillAssign == "stats") to asses your skillAssign it will always return false, even if they have the same value.
Because == compare the reference of Strings not their values.
you must use equals() method.