Ordinals java - Java I class - java

Stuck on getting the prompt to enter a number 1 to 10 - and results should add the st, rd, th, and nd to the number.
Write a program that prompts the user to enter any integer from 1 to 10 and then displays the integer in ordinal form with suffix attached.
public class Ordinals {
public static String Ordinals(int i) {
System.out.println("Enter an integer between 0 to 10: ");
Scanner input = new Scanner(System.in);
int hundred = value % 100;
int tens = value % 10;
if (hundred - tens == 10) {
return "th";
}
switch (tens) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
public static void main(String[] args) {
Ordinals number = new Ordinals();
for (int i = 1; i <= 10; i++) {
String st = number.Ordinals(i);
System.out.println(i + " = " + i + st);
}
}
}

In my opinion it would be better to move Scanner to main:
public static void main(String[] args) {
Ordinals number = new Ordinals();
Scanner input = new Scanner(System.in);
while(true){
System.out.println("Enter an integer between 0 to 10: ");
int i = input.nextInt();
System.out.println(i+number.Ordinals(i));
}
}
and then add to Ordinals:
int value = i;
Method will be independent form input type.

Add value = input.nextInt() under the line creating Scanner.

Related

How to pass user input variables in my Java code?

//Inventory Items classs
import java.util.Scanner;
public class InventoryItems {
public int sackrice = 4;
public int animalfeed = 12;
public int trayeggs = 15;
public int bottlemilk = 9;
ItemSupplier supple = new ItemSupplier();
public void inventoryItem() {
System.out.println("\nAvailable items:\n");
sackrice = sackrice + supple.getRice();
System.out.println("Sack of rice: " + sackrice);
if(sackrice < 10)
System.out.println("Sack of rice low, please restock");
System.out.println();
System.out.println("Animal feed: " + animalfeed);
if(animalfeed < 10)
System.out.println("Animal feed low, please restock");
System.out.println();
System.out.println("Tray of eggs: " + trayeggs);
if(trayeggs < 15)
System.out.println("Tray of eggs low, please restock");
System.out.println();
System.out.println("Bottle of milk: " + bottlemilk);
if(bottlemilk < 15)
System.out.println("Bottle of milk low, please restock");
System.out.println();
press();
}
public static void press(){
Scanner input = new Scanner(System.in);
System.out.println("Press Enter to continue...");
String enter = input.nextLine();
}
}
//Item Supplier class
import java.util.Scanner;
public class ItemSupplier {
public int z;
Scanner scan = new Scanner(System.in);
public void ricesupplier() {
System.out.println("How many sacks of rice would you like to
order?");
z = scan.nextInt();
}
public int getRice() {
return z;
}
public void feedsupplier() {
}
public void eggsupplier() {
}
public void milksupplier() {
}
}
import java.util.Scanner;
public class InventoryManager{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int x;
int y;
do {
System.out.println("Input option:\n" + "\n1. Check inventory" + "\n2. Search item supplier" + "\n3. Exit\n");
x = scan.nextInt();
switch(x) {
case 1:
InventoryItems items = new InventoryItems();
items.inventoryItem();
break;
case 2:
ItemSupplier supply = new ItemSupplier();
do {
System.out.println("\nChoose supplier:\n" + "\n1. Rice supplier\n" + "2. Animal feed supplier\n" + "3. Egg supplier\n" + "4. Milk supplier\n" + "5. Back\n");
y = scan.nextInt();
switch(y) {
case 1:
supply.ricesupplier();
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
System.out.println("Invalid option");
break;
}
break;
} while (y != 5);
break;
case 3:
System.out.println("Program closed");
System.exit(0);
default:
System.out.println("Invalid option");
break;
}
} while(x != 3);
}
}
The "z" I get from getRice() is 0. It only takes the declared but initialized z. How do I get the "z" that was inputed in ricesupplier() method? Specifically, here: System.out.println("How many sacks of rice would you like to order?") and here z = scan.nextInt().
I'm really just a beginner. A lot of parts are still incomplete. I need to finish this problem first before I can proceed.
This won't be a direct answer to your question but here's some hints in order to improve your code and eventually solve your problem.
You should not make a new InventoryItems every time the user's input is 1. This will result into printing the initial inventory items, thus making your user order an item is useless
You should not make a new ItemSupplier every time the user's input is 2.
You don't need ItemSupplier in your InventoryItems
You don't need the variable z in ItemSupplier, you can directly return the input of the user in ricesupplier() method
thus if the user's input is 2 then you can just call ricesupplier() method and add it's return to the current items.sackrice

Validate a course code using a method in java

I have to get my course code to validate. The course code is set to a number 1-7 and the choice has to be within this range. Each course is worth 3 credits. The user can not register for more than 9 credits. The user can not register for the same course more than once. I am having trouble with the repeat course code.
Here is my code:
package u6a1_consoleregisterforcourse;
import java.util.Scanner;
public class U6A1_ConsoleRegisterForCourse {
public static void main(String[] args) {
System.out.println("Quenten's Copy");
Scanner input = new Scanner(System.in);
//choice is the current menu selection
//firstChoice is the first menu selection mande by the user
//secondChoice is the second menu selection mande by the user
//thirdChoice is the third menu selection mande by the user
// a choice of 0 means the choice has not been made yet
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
String yesOrNo = "";
do {
choice = getChoice(input);
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registerd for this " + ChoiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + ChoiceToCourse(choice) );
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
System.out.println("[1]IT4782\n[2]IT4784\n[3]IT4786\n[4]IT4789\n[5]IT2230\n[6]IT3345\n[7]IT3349");
System.out.print("Enter your choice : ");
return (input.nextInt());
}
//This method validates the user menu selection
//against the given registration business rules
//it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
int ValidateChoice;
if ((choice < 1) || (choice >= 8)){
ValidateChoice = -1;}
else if (secondChoice == firstChoice){
ValidateChoice = -2;}
else
{ValidateChoice = 0;}
return ValidateChoice;
}
public static void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice) {
if (firstChoice == 0)
System.out.println("Current course registration: { none } " );
else if (secondChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + " }" );
else if (thirdChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + " }");
else
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + ", " + ChoiceToCourse(thirdChoice) + " }");
}
public static String ChoiceToCourse(int choice) {
String course = "";
switch (choice)
{
case 1:
course = "IT4782";
break;
case 2:
course = "IT4784";
break;
case 3:
course = "IT4786";
break;
case 4:
course = "IT4789";
break;
case 5:
course = "IT2230";
break;
case 6:
course = "IT3345";
break;
case 7:
course = "IT3349";
break;
default:
break;
}
return course;
}
}
The ValidateChoice method is what I am working on. This is for an academic assignment.
It is better to get rid of those firstChoice, secondChoice, thirdChoice variables and use a homogeneous collection instead:
package u6a1_consoleregisterforcourse;
import java.util.*;
public class U6A1_ConsoleRegisterForCourse {
public static final int CREDITS_PER_COURSE = 3;
public static final int MAX_CREDITS = 9;
public static final int MAX_COURSES = MAX_CREDITS / CREDITS_PER_COURSE;
private final List<Integer> registeredCourses = new ArrayList<>(MAX_COURSES);
private int totalCredit;
public static void main(String[] args) {
System.out.println("Quenten's Copy");
U6A1_ConsoleRegisterForCourse registrar = new U6A1_ConsoleRegisterForCourse();
Scanner input = new Scanner(System.in);
//choice is the current menu selection
int choice;
String yesOrNo;
do {
choice = getChoice(input);
switch (registrar.validateChoice(choice)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registered for this " + choiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than " + MAX_CREDITS + " credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + choiceToCourse(choice));
registrar.totalCredit += CREDITS_PER_COURSE;
registrar.registeredCourses.add(choice);
break;
}
registrar.writeCurrentRegistration();
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
private static final String[] courses = {"IT4782", "IT4784", "IT4786", "IT4789", "IT2230", "IT3345", "IT3349"};
public static String choiceToCourse(int choice) {
return courses[choice - 1];
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
for (int i = 1; i <= courses.length; i++)
System.out.format("[%d]%s%n", i, choiceToCourse(i));
System.out.print("Enter your choice : ");
return (input.nextInt());
}
// This method validates the user menu selection
// against the given registration business rules
// it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public int validateChoice(int choice) {
if ((choice < 1) || (choice > courses.length))
return -1;
if (registeredCourses.contains(choice))
return -2;
if (totalCredit + CREDITS_PER_COURSE > MAX_CREDITS)
return -3;
return 0;
}
public void writeCurrentRegistration() {
StringBuilder sb = new StringBuilder("Current course registration: ");
if (registeredCourses.isEmpty())
sb.append(" { none }");
else {
sb.append("{ ");
boolean first = true;
for (int i : registeredCourses) {
if (first)
first = false;
else
sb.append(", ");
sb.append(choiceToCourse(i));
}
sb.append(" }");
}
System.out.println(sb);
}
}
You need to write 3 different validations in your code:
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
//Validation: Choice is in range of 1 and 7
if(choice > 7 || choice < 1){
return -1;
}
// Validation : No 2 course choices have same value
boolean isInvalid = firstChoice!=0 ?
(firstChoice == secondChoice ||firstChoice == thirdChoice):
(secondChoice!=0 && secondChoice==thirdChoice);
if(isInvalid) {
return -2;
}
// Validation : Total credits are not more than 9
else if(totalCredit > 9){
return -3;
}
else{
return 0;
}
}
One of your fellow course mate have also asked this question here,
Validating inputs in a function in java to avoid duplicate data other than non entry with default of 0 (No database )
Be careful of Plagiarism
With the parameters I was given, and only allowed to change the ValidateChoice method, I was able to take John McClane's answer and convert it to make it work. I thank you for the help. What I have done is simple and now makes sense.
Here it is:
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
if ((choice < 1) || (choice >7))
return -1;
if ((choice == secondChoice) || (choice == firstChoice))
return -2;
if (totalCredit >= 9)
return -3;
return 0;
}

Magic 8ball Using securerandom with switch statements and while loops

I have my following code working like this:
import java.util.Scanner;
import java.lang.Math;
public class Magiceightball {
private static void Number() {
int magic = (int) Math.ceil(Math.random() * 10);
String x;
switch (magic)
{
case 1: x = "Yes.";
break;
case 2: x = "No.";
break;
case 3: x = "The odds are in favor.";
break;
case 4: x = "The odds are against you.";
break;
case 5: x = "Never.";
break;
case 6: x = "Definitely!";
break;
case 7: x = "Maybe.";
break;
case 8: x = "I don't think so.";
break;
case 9: x = "I'd say no.";
break;
case 10: x = "Probably.";
break;
default: x = "Try Again.";
break;
}
System.out.println(x);
}
public static void main (String [ ] args)
{
Scanner scan = new Scanner(System.in);
boolean a = true;
while (a)
{
System.out.println();
System.out.println();
System.out.println("What would you like to ask the Magic Eight Ball? Make it a \"Yes\" or \"No\" question for it to work.");
System.out.print("\n\n--> ");
String what = scan.nextLine();
System.out.println();
Number();
System.out.println();
System.out.println();
System.out.println();
System.out.println("Would you like to go again? Enter \"Y\" for yes, and \"N\" for no.");
System.out.print("\n\n--> ");
String run = scan.nextLine();
run = run.toLowerCase();
if (run.equals("n"))
{
a = false;
}
}
}
} `
My dilemma is, I want all these methods being used the switch statement, the while loop but I want to replace the Math.random with the SecureRandom method how would I go about doing that?
I tried using the whole SecureRandom randomNumber = new SecureRandom(); to do it but it kept giving me errors that I could not convert secure random to "int".
You just need to instantiate a SecureRandom object and use its nextInt() method:
Random rand = new SecureRandom();
int magic = 1 + rand.nextInt(10);
You can use this function:
public static int generateRandomInteger(int min, int max) {
SecureRandom rand = new SecureRandom();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Call it with
int magic = generateRandomInteger(1,10); // to get a number between 1 and 10.

Why do I get a "String index out of range" error when I run this program?

I am creating a program that converts roman numeral input to it's integer value and every time I run the program I get an error that says,
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:646)
at romannumeralconverter.RomanNumeralConverter.convert(RomanNumeralConverter.java:20)
at romannumeralconverter.RomanNumeralConverter.romanInput(RomanNumeralConverter.java:68)
at romannumeralconverter.RomanNumeralConverter.printValue(RomanNumeralConverter.java:72)
at romannumeralconverter.RomanNumeralConverter.main(RomanNumeralConverter.java:77)
Java Result: 1"
Now I am new to programming so I don't know what this means exactly. I am guessing my conversion algorithm is wrong in which the roman numeral entered is not read by the loop. Here is what I have:
public class RomanNumeralConverter {
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result;
}
public int romanInput() {
return convert(getUserInput());
}
public void printValue() {
System.out.println(romanInput());
}
public static void main (String[] args) {
new RomanNumeralConverter().printValue();
}
}
If my algorithm is wrong, does anyone know how to fix it?
change userInput.charAt(x); to userInput.charAt(x - 1);
charAt starts with index 0 to length -1
or int x = userInput.length() - 1;
#nd issue, everything coming out as 0
You are actually using uppercase characters in switch statement.
so just add below statement,in the starting of your function convert(String userInput)
userInput = userInput.toUpperCase(); // converts user input to uppercase , even if its is already or not.
code
public int convert(String userInput) {
userInput = userInput.toUpperCase();
int result = 0;
int subtractamount = 0;
int x = userInput.length() - 1;
while (x != 0) {
char romanConvert = userInput.charAt(x);
if (x >= 1) {
if (convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
output
Enter a roman numeral in uppercase: adig
Invalid character!
Invalid character!
Invalid character!
Invalid character!
501
You should start with
int x = userInput.length() - 1;
The last character in a string is at the index - (length-of-string - 1), not length-of-string.

Bracket expected.... not sure where [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm doing an assignment on modular programing and here Im getting a bracket expected error. Here is the code:
import java.util.*;
public class stlab09
{
public static void main (String args[])
{
System.out.println("\nLAB09 90 POINT VERSION\n\n");
enterData();
computeGPA();
displayData();
}
static String lGrade1;
static String lGrade2;
static String lGrade3;
static String lGrade4;
static int cHours1;
static int cHours2;
static int cHours3;
static int cHours4;
static String dummy;
public static double gpa;
public static void enterData()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter course 1 Grade ===>> ");
lGrade1 = in.nextLine();
System.out.print("enter course 1 Hours ===>> ");
cHours1 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 2 Grade ===>> ");
lGrade2 = in.nextLine();
System.out.print("enter course 2 Hours ===>> ");
cHours2 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 3 Grade ===>> ");
lGrade3 = in.nextLine();
System.out.print("enter course 3 Hours ===>> ");
cHours3 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 4 Grade ===>> ");
lGrade4 = in.nextLine();
System.out.print("enter course 4 Hours ===>> ");
cHours4 = in.nextInt(); dummy = in.nextLine();
}
public static void computeGPA()
{
Grades.gradeValue();
Grades.courseValue();
Grades.getGPA();
}
public static void displayData()
{
System.out.println();
System.out.println("Course1 Grade: " + lGrade1 + " Course1 Credit Hours: " + cHours1);
System.out.println("Course2 Grade: " + lGrade2 + " Course2 Credit Hours: " + cHours2);
System.out.println("Course3 Grade: " + lGrade3 + " Course3 Credit Hours: " + cHours3);
System.out.println("Course4 Grade: " + lGrade4 + " Course4 Credit Hours: " + cHours4);
System.out.println();
System.out.println("Current GPA: " + gpa);
}
}
public class Grades() ***<<<<<<<<<<<<<<<<<< bracket expected here***
{
public static void gradeValue()
{
int value = 0;
char lg1 = lGrade1.charAt(0);
switch(lg1)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal1 = value;
char lg2 = lGrade2.charAt(0);
switch(lg2)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal2 = value;
char lg3 = lGrade3.charAt(0);
switch(lg3)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal3 = value;
char lg4 = lGrade4.charAt(0);
switch(lg4)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal4 = value;
}
public static void courseValue()
{
int cVal1 = gVal1 * cHours1;
int cVal2 = gVal2 * cHours2;
int cVal3 = gVal3 * cHours3;
int cVal4 = gVal4 * cHours4;
}
public static void getGPA()
{
double totalValue = cVal1 + cVal2 + cVal3 + cVal4;
double totalHours = cHours1 + cHours2 + cHours3 + cHours4;
double gpa = totalValue / totalHours;
}
}
So yeah I need some help figuring this out because I'm kinda going crazy about it. The expected program is supposed to use keyboard input of letter grades and course hours to compute GPA and grades. The assignment is to get that outcome but the main method must stay exactly as is, and almost every method was provided to me and i just had to organize them.
You have declared the inner class Grades as if it's a method (you added () onto the end of it), look at how the class stlab09 is declared, there aren't any ().

Categories

Resources