Why is my program not accepting input through the console? (Java) - java

I know it's a silly silly program. It's just to practice constructors.
public class PetRecord {
private String name = "Bob";
private int age;
private double weight;
public PetRecord(String initialName, int initialAge, double initialWeight) {
name = initialName;
if(initialAge < 0 || weight < 0) {
System.out.println("Error: Age or weight cannot be negative");
System.exit(0);
}
else {
age = initialAge;
weight = initialWeight;
}
}
public PetRecord(String initialName) {
name = initialName;
}
public void output() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
}
public void setAll(String newName, int newAge, double newWeight) {
name = newName;
if ((newAge < 0) || (newWeight < 0)) {
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else {
age = newAge;
weight = newWeight;
}
}
public void review() {
if(age < 8 && weight < 8) {
System.out.println("Your pets weight and age are healthy.");
}
if(age >= 8 && weight >=8) {
System.out.println("Your pets weight and age are unhealthy.");
}
else {
System.out.println("Come to my office for a proper assessment.");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PetRecord d = new PetRecord("Bob");
System.out.println("Please check if our current records are correct.");
d.output();
System.out.println("Are they correct?");
String answer = input.nextLine();
String yes = "Yes";
String no = "No";
if((answer.equals(yes))) {
System.exit(0);
}
if(answer.equals(no)) {
System.out.println("Please enter your pets name.");
String correctName = input.nextLine();
System.out.println("Age?");
int correctAge = input.nextInt();
System.out.println("Weight?");
double correctWeight = input.nextDouble();
d.setAll(correctName, correctAge, correctWeight);
System.out.println("Your updated records say: ");
d.output();
System.out.println("Would you like a health review?");
String answer1 = input.nextLine();
String yes1 = "yes";
String no1 = "no";
if(answer1.equals(yes1)) {
d.review();
}
if(answer1.equals(no1)) {
System.out.println("Thank you for using PetSystem. Goodbye.");
System.exit(0);
}
}
}
}
My program accepts input for String answer, but my program will not accept String answer1. I can't even type anything in the console after the program asks you if you would like a health review.

The issue comes from here
System.out.println("Your updated records say: ");
d.output();
Because you have printed something out in the middle of accepting input, you most likely have an extra newline token you have not dealt with. Prior to asking the "health review" question place the following code.
while (input.hasNextLine()) {
input.nextLine();
}
This will make sure that you clear out any extra tokens before continuing to accept user input.

you can,t type anything in the console after "if you would like a health review." because you code only runs ones you should put it in a loop to make it run more than once

Related

Scanner cant read/incorrectly reading my input

I am writing a code whereby I have to input people's name and money value. However I have used a scanner but it does not read the name that I input into the console. Whatever name I put, the code will tell me that no such name is found. I have tried for many hours trying to resolve this, assistance would be appreciated! (there are 6 total cases but I only posted the first one since its the only one I'm having problems with)
The code is as such:
import java.util.Scanner;
public class Client {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
Change[] changeArray = new Change [10];
int numNames = 0;
System.out.println("Please enter at least 10 records to test the program");
String name = "";
int change = 0;
int flag = 0;
int[] totalNumberOfCoinsOf = {0,0,0,0,0};
for (int i = 0;i < changeArray.length;i++)
{
System.out.println("Enter name: ");
name = reader.nextLine();
do {
System.out.println("Enter coin value for the person");
change = Integer.parseInt(reader.nextLine());
if (change % 5 ==0) {
break;
}else if (change % 5 <2.5) {//round down to nearest 5 if change is less than 2.5
change = change - change %5;
break;
}
else if (change %5>=2.5)
{
change = Math.round(change * 100)/100; //round up to nearest 5 if change is more than 2.5
}
}while (true);
changeArray[i] = new Change(name, change);
numNames++;
do {System.out.println("Do you have another person to enter? (Y/N) ");
String choice = reader.nextLine();
if (i!=changeArray.length - 1) {
if(choice.toUpperCase().equals("Y")) {
break;
}else if (choice.toUpperCase().equals("N")) {
flag = 1;
break;
}
}
}while(true);
if (flag==1) {
break;
}
}
do {
System.out.println("\n[1] Search by name ");
System.out.println("\n[2] Search largest coin");
System.out.println("\n[3] Search smallest coin");
System.out.println("\n[4] Total coins");
System.out.println("\n[5] Sum of coins");
System.out.println("\n[6] Exit the program");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(reader.nextLine());
switch (choice) {
case 1:
System.out.print("Enter name to search: ");
name = reader.nextLine();
flag = 0;
for (int i = 0;i < numNames; i++) {
if (name.equals(changeArray[i].getName())) {
System.out.println("Customer: ");
System.out.println(changeArray[i].getName() + " " + changeArray[i].getCoinChangeAmount());
int[] coins = changeArray[i].getChange();
System.out.println("Change: ");
if(coins[0]!=0) {
System.out.println("Dollar coins: "+coins[0]);
}
if(coins[1]!=0) {
System.out.println("50 cents: "+coins[1]);
}
if(coins[2]!=0) {
System.out.println("25 cents: "+coins[2]);
}
if(coins[3]!=0) {
System.out.println("10 cents: "+coins[3]);
}
if(coins[4]!=0) {
System.out.println("5 cents: "+coins[4]);
}
flag++;
}
}
if (flag==0) {
System.out.println("Name: "+name);
System.out.println("Not found! ");
}
break;
//Change class
import java.util.Scanner;
public class Change {
private String name;
private int coinChangeAmount;
public Change() {
this.name = "no name";
this.coinChangeAmount = 0;
}
public Change(String name, int coinChangeAmount) {
this.name = "name";
this.coinChangeAmount = coinChangeAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoinChangeAmount() {
return coinChangeAmount;
}

Grade Check java

I wrote this program to convert a number grade into a letter grade but I keep getting the same errors. Could someone help me figure out what I'm doing wrong?
import static java.lang.System.*;
import java.util.Scanner;
public class Grade
{
private int numGrade;
public Grade()
{
Grade test;
}
public void setGrade(int grade)
{
numGrade = grade;
if (grade >= 90)
{
System.out.println("A");
}
{
System.out.println("B");
}
public String getLetterGrade( ) {
String letGrade="A";
if (grade>= 90)
{
return letGrade;
}
public String toString(){
return numGrade + " is a " + getLetterGrade() + "\n";
}
}
Seems like you tried to attack the same thing from many different positions.
first of lets start with converting numerical grades into letter grades, so before engaging to inputs, start with asking the kind of grade the user wishes to convert
char choise;
choise = reader.nextChar(); //ask for N or L for numerical or letter
next i'll show a sample code for letter to numerical convertion
public int getNGrade(char grade)
{
if (grade == 'A')
return 90;
else if (grade == 'B')
return 80; //and so on
}
same way can be used for the numerical to letter convertion
in the main class u call the function:
charGrade = reader.nextChar();
System.out.println("Your grade in numbers is " + getNGrade(charGrade));
i'm guessing that's what u meant, hope i was helpful.
Your code can be this and it works perfectly:
public class Grade {
private int numGrade;
public Grade(int grade) {
numGrade = grade;
}
public int getGrade() {
return numGrade;
}
public void setGrade(int grade) {
numGrade = grade;
}
public String getLetterGrade() {
if(numGrade <0 || numGrade > 100) throw new IllegalArgumentException("No such a grade!");
else if(numGrade>=90) return "A";
else if (numGrade >= 80) return "B";
else if(numGrade >= 70) return "C";
else if(numGrade >= 60) return "D";
else return "F";
}
public String toString(){
return numGrade + " is a " + getLetterGrade() + "\n";
}
}
You can include in the same class a main method or create a separate class for testing:
public static void main(String[] args) {
Grade g = new Grade(75); //you can enter the grade manually or simply using a Scanner object
System.out.println(g);
}
The syntax used is incorrect.
Attached is a sample code to do the conversion
public class Grade {
private int numGrade;
public void setGrade(int grade) {
numGrade = grade;
if (grade >= 90) {
System.out.println("A");
} else {
System.out.println("B");
}
}
public String getLetterGrade() {
String letGrade = "B";
if (numGrade >= 90) {
return "A";
}
return letGrade;
}
public String toString() {
return numGrade + " is a " + getLetterGrade() + "\n";
}
}
import java.util.Scanner;
class Tutorial {
public static void main(String args[]){
Scanner input = new Scanner(System.in); // calling Scanner method
String restart = "Y"; //initialising the restart variable
while (restart.equals("Y")) // testing the conditon(if Y is equals then it continues)
{
int grade;
System.out.println("WELCOME TO ABD GRADING SYSTEM.");
System.out.println("Enter your Score(between 1 - 100) : "); // Displaying a message on screen
grade = input.nextInt(); // Accept Input from the user
if(grade<=39)
System.out.println("Your grade is F9");
else if(grade==40 || grade<=49)
System.out.println("Your grade is D7");
else if(grade==50 || grade<=59)
System.out.println("Your grade is C6");
else if(grade==60 || grade<=69)
System.out.println("Your grade is C5");
else if(grade==70 || grade<=79)
System.out.println("Your grade is B2");
else if(grade==80 || grade<=100)
System.out.println("Your grade is A1");
else
{
System.out.println("Input Correct score between (1 - 100).");
}
System.out.println("THANK YOU.");
System.out.println("Would you like to Calculate again? Y/N ");
restart = input.next();
}
}
}

Why is my program repeating itself. Java Error

I am supposed to make the program give the number of pets and the percentage of how many that are below 5lbs, 5-10lbs, and over 10lbs. The program keeps repeating the statements and I don't know why. I've been working on this problem for the past couple of days and I still can't figure it out. At times it seems like I fixed it but then later on it happens again. Can anyone clarify why this is happening? I need help please.
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.lang.Object;
public class SetPetWeight
{
public static void main(String[] args) {
ArrayList<Pet> list = new ArrayList<Pet>();
String name;
String answer;
int age;
Double weight;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("Enter a String for Pet name: ");
name = keyboard.next();
System.out.println("Enter an int for Pet age: ");
age = keyboard.nextInt();
if(age <= 0)
System.out.println("Error! Enter a real age");
System.out.println("Enter a double for Pet weight: ");
weight = keyboard.nextDouble();
if(weight <= 0)
System.out.println("Error! Enter a real weight");
do
{
System.out.println("Do you want to enter another pet? Y/N");
answer = keyboard.nextLine();
keyboard.nextLine();
} while (answer.equalsIgnoreCase("Y"));
} while (name.length() < 0 && age < 0 && weight < 0);
System.out.println("The weight is now sorted by weight!");
Collections.sort(list, Pet.SortByWeight);
for (Pet p2 : list)
p2.writeOutput();
int average1 = 0;
int average2 = 0;
int average3 = 0;
for (Pet p : list)
{
if(p.getWeight() >= 0 && p.getWeight() <= 5)
{
++average1;
}
else if(p.getWeight() >= 5 && p.getWeight() <= 10)
{
++average2;
}
else if(p.getWeight() > 10)
{
++average3;
}
System.out.println("The average of pets under 5 pounds:" + average1);
System.out.println("The average of pets between 5 and 10 pounds:" + average2);
System.out.println("The average of pets over 10 pounds:" + average3);
}
}
}
Pet Class that is used for the SetPetWeight class and is compiled correctly and is used for the array.
import java.util.*;
public class Pet {
private String name;
private Integer age; // in years
private double weight; // in pounds
public void writeOutput() {
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName) {
name = newName;
// age and weight are unchanged.
}
public void set(int newAge) {
if (newAge <= 0) {
System.out.println("Error: illegal age.");
System.exit(0);
} else
age = newAge;
// name and weight are unchanged.
}
public void set(double newWeight) {
if (newWeight <= 0) {
System.out.println("Error: illegal weight.");
System.exit(0);
} else
weight = newWeight;
// name and age are unchanged.
}
public Pet(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
public static Comparator<Pet> SortByWeight = new Comparator<Pet>()
{
public int compare(Pet pet1, Pet pet2)
{
return (int)(pet1.getWeight() - pet2.getWeight());
}
};
}
Move keyboard.nextLine(); after weight = keyboard.nextDouble(); to consume the dangling newline character .
There are a few changes you may want to make.
1. Every time you retrieve user input for pet's name, age and weight. You may want to create an object of type pet to store this values and then add this to your ArrayList. Before you ask them if they wan to add another pet.
2. Remove the outer do while loop, and change the inter loop to include the "Enter a String for pet name: ".
3. Also check for validation for input.
do {
System.out.println("Enter a String for Pet name: ");
name = keyboard.next();
System.out.println("Enter an int for Pet age: ");
age = keyboard.nextInt();
if(age <= 0)
System.out.println("Error! Enter a real age");
System.out.println("Enter a double for Pet weight: ");
weight = keyboard.nextDouble();
keyboard.nextLine();
if(weight <= 0)
System.out.println("Error! Enter a real weight");
System.out.println("Do you want to enter another pet? Y/N");
answer = keyboard.nextLine();
keyboard.nextLine();
} while (answer.equalsIgnoreCase("Y"));

Bank Program error when I try to access an account that does not exist

I have been working on this bank program for my Java class at school for the past week and a half. I thought I finally had it working the way my instructor wanted. However, when I try to access an account that does not exist, the program "blows up" (my instructors words). I need it to let the user know that the account does not exist and redirect them back to the main menu. So, my problem I believe is in my findAcct method in my Bank class. I have tried several fixes but none have worked. Any insight or help would be greatly appreciated! I need to have this done by Monday. I know I said the problem is in one method, but I'll post my whole program for context.
Bank Class
import java.util.Scanner;
public class Bank
{
private int max = 25;
private int count;
bankAcct myAcct[] = new bankAcct[max];
Scanner scannerObject = new Scanner(System.in);
public void openAcct()
{
if (count >= max){
System.out.println("Not accepting new customers at this time.");
}else{
System.out.println("Please enter your name: ");
String lname = scannerObject.next();
myAcct[count] = new bankAcct(count + 1, 25, lname);
count++;
System.out.println("Thank you " + lname + ", your account number is: " + count);
}
}
public int findAcct() // This is the method in question
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
found = i;
}
}
return found;
}
public void seeBal()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].dispBal();
}
}
public void Deposit()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].makeDeposit();
}
}
public void Withdrawal()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].makeWithdrawal();
}
}
}
bankAcct Class
import java.util.Scanner;
public class bankAcct
{
private double Bal;
private int acctNum;
private String name;
Scanner scannerObject = new Scanner(System.in);
public bankAcct(int pAcctNum, double pBal, String pName)
{
Bal = pBal;
acctNum = pAcctNum;
name = pName;
}
public void makeDeposit()
{
System.out.print( "Hello " + name + ", please, enter amount to deposit $");
double lDep = scannerObject.nextDouble();
Bal = Bal + lDep;
System.out.println( " You have deposited $" + lDep);
System.out.println( " Your new balance is $" + Bal);
}
public void makeWithdrawal()
{
System.out.print( "Hello " + name + ", please, enter amount to withdraw $");
double lWDraw = scannerObject.nextDouble();
if (lWDraw <= Bal){
Bal = Bal - lWDraw;
System.out.println( "You have withdrawn $" + lWDraw);
System.out.println( "Your new balance is $" + Bal);
}else{
System.out.println("Insufficient funds!");
}
}
public void dispBal()
{
System.out.println( "Hello " + name + ", your current balance is $" + Bal);
}
public int getAcctNum()
{
return acctNum;
}
public void setName(String pName)
{
name = pName;
}
public String getName()
{
return name;
}
}
bankUser Class
import java.util.Scanner;
public class bankUser
{
public static void main(String[] args)
{
Bank myBank = new Bank();
int Choice;
do
{
dispMenu();
Choice = getChoice();
proChoice(Choice, myBank);
}
while (Choice !=0);
}
public static void dispMenu()
{
System.out.println( "|==================================|");
System.out.println( "| TONY'S FIRST NATIONAL BANK |");
System.out.println( "|***********Menu Options***********|");
System.out.println( "|__________________________________|");
System.out.println( "| Press [1] To Open New Account |");
System.out.println( "| Press [2] To View Balance |");
System.out.println( "| Press [3] To Make Deposit |");
System.out.println( "| Press [4] To Make Withdrawal |");
System.out.println( "| Press [0] to Exit |");
System.out.println( "|__________________________________|");
System.out.println( "| Please Make Selection Now... |");
System.out.println( "|==================================|");
}
static int getChoice()
{
Scanner scannerObject = new Scanner(System.in);
int pChoice, Choice;
pChoice = scannerObject.nextInt();
Choice = pChoice;
return Choice;
}
static void proChoice(int Choice, Bank myBank)
{
switch (Choice)
{
case 1: myBank.openAcct();
break;
case 2: myBank.seeBal();
break;
case 3: myBank.Deposit();
break;
case 4: myBank.Withdrawal();
break;
case 0: System.out.println( "Thank you, come again.");
break;
}
}
}
Again, any help would be greatly appreciated. I am still a padawan when it comes to Java.
*UPDATE: I have tried this code, and it seems to work! However, my instructor told me that we can never have 2 return statements within a method.
public int findAcct()
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
return found = i;
}
}
return -1;
}
UPDATE: Here is what I did to my findAcct method in my Bank Class:
public int findAcct()
{
System.out.println("Greetings, please enter your account number: ");
int acctNum = scannerObject.nextInt();
int found = -1;
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == acctNum){
found = i;
break; //Ends Loop
}
}
return found;
}
My instructor did not mind a break statement, so I added out at the end of my for loop. I also moved my local variable found = -1; down a couple lines. Thank you for all the help! I can't wait to learn more!
If you do not want to have 2 return statements within a method (which you can have, but sometimes it is bad practice when you are beginning coding so professors like to just make that rule) you can use your found variable to store the value that will be returned and return found at the end of the function.
You were on the right track.
Example:
public int findAcct()
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
found = i;
break; //Exit out of the loop
}
}
return found;
}
This code will set found to i if it finds the account and then break out of the loop. After it breaks out of the loop it will return found. Otherwise, found will never be set and return -1 since you initialized it to -1 at the top.
If your instructor has not taught you break statements yet, then you can use a boolean variable foundAccount initialized to false. Then check if foundAccount is false before doing your if statement check. Once you find it, set it to true so you do not keep looking.
Example:
public int findAcct()
{
int found = -1;
boolean foundMatch = false;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(!foundMatch){
if(myAcct[i].getAcctNum() == found){
found = i;
foundMatch = true; //we will no longer search
}
}
}
return found;
}

how to find two's best answers

I am trying to find two's greatest numbers that are entered from the console.
I found the first one, but the solution for the second one is not working. The program is compiling and running. Here is the code.
import java.util.Scanner;
public class FindingSecondHighestScore_4_09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double max = 1;
double score2 = 0;
String firstName = "";
String secondName = null;
System.out.println("Enter number of students: ");
int x = input.nextInt();
while(x > 0)
{
System.out.println("Enter Sudent's name");
String name = input.next();
System.out.println("Enter Student's score");
double score = input.nextDouble();
//find max
if(score > max)
{
max = score;
firstName = name;
}
//find second max
if(max < score2 || score < score2)
{
max = score2;
score = score2;
}
else if(max > score2 && score2 < score)
{
score2 = score;
secondName = name;
}
x--;
}
System.out.println("The student: " + firstName + " has the greatest score: " + max);
System.out.println("Second studemt " + secondName + " with second results: " + score2);
}
}
Here is a bit more elaborate implementation (my waking up excercise of today):
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TopScores {
private static final int TOP_SELECTION_SIZE = 2;
public static class Student {
private final String name;
private double score;
public Student(String name) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Name cannot be empty");
}
this.name = name;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public void setScore(String score) {
try {
this.score = Double.parseDouble(score);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal score: " + score);
}
}
#Override
public String toString() {
return String.format("%s with score %s", name, score);
}
}
public static void main(String[] args) {
List<Student> students = new ArrayList<TopScores.Student>();
System.out.println("Please enter students. Press <RETURN> to stop.");
Scanner input = new Scanner(System.in);
boolean enteringData = true;
while (enteringData) {
try {
System.out.print("Enter student's name: ");
Student student = new Student(input.nextLine());
System.out.print("Enter student's score: ");
student.setScore(input.nextLine());
for (int i = 0; i < students.size(); i++) {
if (student.getScore() > students.get(i).getScore()) {
students.add(i, student);
break;
}
}
if (students.size() == 0) {
students.add(student);
}
} catch (IllegalArgumentException e) {
enteringData = false;
}
}
int studentsToDisplay = Math.min(TOP_SELECTION_SIZE, students.size());
if (studentsToDisplay > 0) {
System.out.println("Top students:");
for (int i = 0; i < studentsToDisplay; i++) {
System.out.println("* " + students.get(i));
}
} else {
System.out.println("No students to display");
}
}
}
I created a separate class Student which holds name and score, validates the input and creates the display format for one student.
To determine the top scores I keep all the entered students sorted in a list by adding each new student in the correct position.
The user doesn't have to enter the number of students beforehand but can terminate data entry by entering an empty line (or an invalid score).
After data entry is finished the desired number of top scoring students is printed.
This approach is more flexible; printing the top 3 or top 10 students is a matter of changing the value of TOP_SELECTION_SIZE.
Most important takeaway: try to think in classes (in this case Student) where possible and delegate sensible responsibilities to each class.
Since this looks like homework, I will just give you a few hints:
When you find a new max, what should happen to score2?
Should you look for a new score2 even if you found a new max?
If we want to address the if structures, consider rearranging to something like this:
if (/* new score beats second score, but not first */) {
// replace second score
} else if (/* new score beats both first and second */) {
// move first score down to second
// assign a new first score
}
Let your thought process to correspond closely to the code, which will clarify what each block should do, thus localizing any logic errors.
I think when score is greater than max then have to shift max into second score and set max with new score....
And
When the score is between max and score2 then have to update score2 only with new score
//find max
if(score > max)
{
score2 = max;
max = score;
secondName = firstName;
firstName = name;
}
//find second max
if(score < max && score > score2)
{
score2 = score;
secondName = name;
}

Categories