I was practicing my coding skills on hackerrank 30 days of code.While Solving Day 4 problem of classes and instances it showed wrong outcome.[enter image description here][1]
Expected Output:
https://i.stack.imgur.com/YOgMw.jpg
My Output:
https://i.stack.imgur.com/Ee27n.jpg
If you notice, there's an extra line in my code and it only comes when last input is old.
Can anyone tell how to fix this?
https://i.stack.imgur.com/jnPZZ.jpg
Here's my code:
import java.io.*;
import java.util.*;
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
this.age=initialAge;
}
public void amIOld() {
// Write code determining if this person's age is old and print the correct statement:
if(age<0)
{ age=0;
System.out.println("Age is not valid,setting age to 0");
System.out.println("You are young.");
}
else if(age<13){
System.out.println("You are young.");}
else if(age>=13&&age<18){
System.out.println("You are a teenager.");}
else
{ System.out.println("You are old.");
}
}
public void yearPasses() {
// Increment this person's age.
age=age+1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
Try this:
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if(initialAge<0){
age = 0;
System.out.println("Age is not valid, setting age to 0.");
}else{
age = initialAge;
}
}
public void amIOld() {
// Write code determining if this person's age is old and print the correct statement:
if(age<13){
System.out.print("You are young.");
System.out.println("");
}else if (age>=13 && age<18){
System.out.print("You are a teenager.");
System.out.println("");
}else {
System.out.print("You are old.");
System.out.println("");
}
}
public void yearPasses() {
// Increment this person's age.
age++;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
this is my try:
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if(initialAge>=0) age=initialAge;
else{
age=0;
System.out.println("Age is not valid, setting age to 0.");
}
}
public void amIOld() {
if(age<13)System.out.println("You are young.");
if(age>=13 && age<18)System.out.println("You are a teenager.");
if(age>=18) System.out.println("You are old.");
}
public void yearPasses() {
// Increment this person's age.
age=age+1;
}
This is the answer for HackerRank - 30 Days of Code - Day 4 classes and instances
import java.io.*;
import java.util.*;
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if (initialAge > 0) {
age = initialAge;
} else {
System.out.println("Age is not valid, setting age to 0.");
age = 0;
}
}
public void amIOld() {
// Write code determining if this person's age is old and print the correct statement:
String output="";
if (age < 13) {
output="You are young.";
}else if (age < 18) {
output="You are a teenager.";
}else {
output="You are old.";
}
System.out.println(output);
}
public void yearPasses() {
// Increment this person's age.
age++;
}
public static void main(String[] args) { ... }
i have tried this and i have rectify this error by using the following code;
import java.io.;
import java.util.;
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if(initialAge<0)
{
this.age=0;
System.out.print("Age is not valid, setting age to 0.");
}
else
this.age=initialAge;
}
public void amIOld() {
// Write code determining if this person's age is old and print the correct statement:
System.out.println("");
if(age>=0 && age < 13){
System.out.print("You are young.");}
else if(age>=13 && age < 18){
System.out.print("You are a teenager.");}
else{
System.out.print("You are old.");}
}
public void yearPasses() {
// Increment this person's age.
age=age+1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
Related
This program is to reserve time available from three different games. So far in the program, I had printed the two different menus on that shows the game and the other one shows the available time Slots. the Program is set to be an infinite loop so other users have the chance to pick a game and reserve time as well. This is where my problem comes, the second time the program runs it stills displays the time that was previously picked.
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean avaliableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
avaliableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
avaliableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}
In fact, your problem isn't that you didn't change the boolean values in your table from true to false. Instead, your problem is that you didn't use information in the table before you make reservations. What you were doing is to always set that value to false and print "succesfully reserve", without checking whether that time has already been reserved by someone else.
Try the following code. I also add some codes to handle invalid input number.
By the way, "avaliableTime" looks like a typo, so I changed it to "availableTime".
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean availableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
availableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
if (availableTime[userChoice][i]) {
//if false, this time is not available and should not be displayed.
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}else {
//handle unexpected game number.
System.out.println("Invalid game number, please try again.");
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
//what if someone typed 0 although 0 wasn't displayed? (0 wasn't displayed, for example, because it has been reserved by someone else.)
//So you should check whether it is available by the following line.
if (availableTime[userChoice][reserveTime]) {
//if true, this time hasn't been reserved, so it is a valid input.
availableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}else {
//if already false, this time has already been reserved by someone else,
//thus it is an invalid input.
System.out.println("This time has already been reserved, please try again.");
}
}else {
System.out.println("Invalid time number, please try again.");
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}
For class, I have to write a program using arrays where someone can look up popular baby names during a certain time frame. (Ex: The most popular boy and girl name from 1890-1910 is ....)
I think the program is decent, but it runs really slow. I don't know if it is just because of my code, or having a simple program look through a large file; but is there a way to speed up the process?
import java.io.*;
import java.util.*;
import java.net.URL;
public class BabyNamesMainDriver {
// ===========================================================================================
private static void process(Scanner sc, String[] args) throws Exception {
// The two arrays
ArrayList<BabyNameClass> boys = new ArrayList<BabyNameClass>();
ArrayList<BabyNameClass> girls = new ArrayList<BabyNameClass>();
System.out.println("Enter a start year between 1880 and 2016:");// start year
int startYear = sc.nextInt();
if (startYear < 1880 || startYear > 2016)// Error check
System.out.println("ERROR: Invalid start year.\n");
else
System.out.println("Enter a end year. Must be less then 2016 but greater than the start year :");// End year
int endYear = sc.nextInt();
if (endYear < 1880 || endYear > 2016)// Error check
System.out.println("ERROR: Invalid end year. \n");
else
System.out.println("Enter the number of baby names to list. ");// Number of baby names
int numOfNames = sc.nextInt();
// if (topBabies <= 0);//Error Check
// System.out.println("ERROR: Invalid number of names. \n");
ReadBabyNames(startYear, endYear, boys, girls);// Reads file info
// Header for top girl names
System.out.print("\nTop " + numOfNames + " Girl names:\n");
for (int i = 0; i < numOfNames; i++) {
System.out.println(girls.get(i));
}
// Header for top boy names
System.out.print("\nTop " + numOfNames + " Boy names:\n");
for (int i = 0; i < numOfNames; i++) {
System.out.println(boys.get(i));
}
sc.nextLine();
}
// ===========================================================================================
private static void ReadBabyNames(int startYear, int endYear, ArrayList<BabyNameClass> boys,
ArrayList<BabyNameClass> girls) throws IOException, Exception {
System.out.println("Please stand by...");
for (int year = startYear; year <= endYear; year++) {
#SuppressWarnings("resource")
Scanner sc = new Scanner(
new URL("https://cs.stcc.edu/~silvestri/babynames/yob" + year + ".txt").openStream());// file from
// URL
sc.useDelimiter("\\s*,\\s*|\\s+");
while (sc.hasNextLine()) {
String name = sc.next();
String sex = sc.next();
int number = sc.nextInt();
sc.nextLine();
BabyNameClass babies = new BabyNameClass(name, number);
Collections.sort(boys);
Collections.sort(girls);
// Getting number of lil' babies
if (sex.equalsIgnoreCase("F")) {
int index = 1;
index = girls.indexOf(babies);
if (index == -1)
girls.add(babies);
else
girls.get(index).addToAmount(number);
} else {
int index = 1;
index = boys.indexOf(babies);
if (index == -1)
boys.add(babies);
else
boys.get(index).addToAmount(number);
}
}
}
}
// ===========================================================================================
public static void main(String args[]) throws Exception {
final String TITLE = "Baby Name Ranking";
final String CONTINUE_PROMPT = "\nDo this again? [y/N] ";
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
// ===========================================================================================
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.equalsIgnoreCase("Y");
}
}
2nd class
public class BabyNameClass implements Comparable<BabyNameClass> {
// ==========================
private String name;
private int num;
// ===========================================================================================
public BabyNameClass(String name, int num) {
this.name = name;
this.num = num;
}
// ===========================================================================================
public String getName() {
return this.name;
}
// ===========================================================================================
public int getNum() {
return this.num;
}
// ===========================================================================================
public void addToAmount(int num) {
this.num += num;
}
// ===========================================================================================
public void setAmount(int num) {
this.num = num;
}
// ===========================================================================================
public boolean equals(Object lak) {
if (lak == null)
return false;
if (this == lak)
return true;
if (getClass() != lak.getClass())
return false;
BabyNameClass Gu = (BabyNameClass) lak;
if (name == null) {
if (Gu.name != null)
return false;
} else if (!name.equals(Gu.name))
return false;
return true;
}
// ===========================================================================================
public int compareTo(BabyNameClass arg0) {
if (this.num < arg0.num)
return 1;
if (this.num > arg0.num)
return -1;
if (this.name.compareTo(arg0.name) > 0)
return 1;
if (this.name.compareTo(arg0.name) < 0)
return -1;
else
return 0;
}
// ===========================================================================================
public String toString() {
return " " + this.num + " babies were named " + this.name;
}
}
You're sorting two arraylists every single time you read a new line from the txt file. Why? Sorting is very cpu-intensive. Especially when those txt files you are using are huge.
Just try and move the sort out of the while loop.
I am having trouble calling a getter from an imported class.
I have created a working class (Students) and an action class (ProgressReport). The main class reads a text file and writes the data to an array. The data is then manipulated in the working class. Last, ProgressReport.generateReport will create a report giving the students name, their grade average and the letter grade associate with that average.
I am having trouble using the Students getters from the Progress Report class. Eclipse is saying the method is undefined. I am not exactly sure what I have done wrong or how to go about fixing it. Any help would be very much appreciated.NOTE: I added some println to make sure parts of the code were being executed. Thank you all in advance.
Code to follow:
Progress Report
package Lab1A;
import java.util.*;
import Lab1A.Students;
import java.io.*;
public class ProgressReport {
public Students section[][];
public static void main(String[] args) throws IOException
{
Students tmpStudent;
ProgressReport progressReport = new ProgressReport();
progressReport.readInputFile();
progressReport.generateReport();
System.out.println("\nSEARCH TEST");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(0, "Cooper");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(0, "Bronson");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(1, "Diana");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
}
public ProgressReport()
{
section = new Students [2][];
}
public void readInputFile() throws FileNotFoundException
{
System.out.println("in readInputFile method");
//Open file
File input = new File("Lab1A.in");
Scanner inputFile = new Scanner(input);
System.out.println("file is open");
//Read file data
int currentStudent = 0;
while (inputFile.hasNext())
{
System.out.println("In while loop");
//Get Student count
int rows = inputFile.nextInt();
//Read student data
section[currentStudent] = new Students[rows];
System.out.println("array initiated");
for(int i = 0; i < rows; i++)
{
System.out.println("In for loop");
//read in a students info
String sName = inputFile.next();
//Read in grades
int grade1 = inputFile.nextInt();
int grade2 = inputFile.nextInt();
int grade3 = inputFile.nextInt();
int grade4 = inputFile.nextInt();
int grade5 = inputFile.nextInt();
//Send to Students Array
section[currentStudent][i] = new Students(sName, grade1, grade2, grade3, grade4, grade5);
}
//Next Student Line
currentStudent++;
}
inputFile.close();
}
public void generateReport()
{
System.out.println("Progress Report");
double average = Students.class.getAverage();
//String section = "Section\n";
}
public Students sequentialSearch(int section, String searchName)
{
return null;
}
}
Students Class
package Lab1A;
import java.lang.reflect.Array;
public class Students {
private String name;
private char grade;
private double average;
private int scores[];
public Students(String sName, int grade1, int grade2, int grade3, int grade4, int grade5)
{
//CONSTRUCTOR load data from ProgressReport
name = sName;
int newScores[] = {grade1, grade2, grade3, grade4, grade5};
scores = newScores;
}
//Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getGrade() {
if(average >= 90 && average <= 100)
{
grade = 'A';
}
if(average >= 80 && average < 90)
{
grade = 'B';
}
if(average >= 70 && average < 80)
{
grade = 'C';
}
if(average >= 60 && average < 70)
{
grade = 'D';
}
if(average >= 0 && average < 60)
{
grade = 'F';
}
return grade;
}
public void setGrade(char grade) {
this.grade = grade;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public int[] getScores() {
return scores;
}
public void setScores(int[] scores) {
this.scores = scores;
}
//Calculate average score
public void calculateAverage()
{
int total = 0;
for (int i = 0; i < scores.length; i++)
{
total += scores[i];
}
average = total*1.0/scores.length;
}
//calculate letter grade based on average score (calulateAverage.average)
public void calculateGrade()
{
if(average >= 90 && average <= 100)
{
grade = 'A';
}
if(average >= 80 && average < 90)
{
grade = 'B';
}
if(average >= 70 && average < 80)
{
grade = 'C';
}
if(average >= 60 && average < 70)
{
grade = 'D';
}
if(average >= 0 && average < 60)
{
grade = 'F';
}
}
}
Your not specifying which Student you want the average of (Not sure why you named your class students with an s). It needs to look something like this:
section[1][1].getAverage()
import java.util.*;
/**
* Write a description of class TheaterApp here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class TheaterApp {
static int [][] seats = {
{10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10},
{10,10,20,20,20,20,10,10},
{20,20,30,30,30,30,20,20},
{30,30,40,40,40,40,30,30},
{30,40,40,50,50,40,40,40}};
/**
* Constructor for objects of class TheaterApp
*/
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print("Enter request, please (or 'help' or 'quit') ");
ans = input.next();
if (ans.equals("help")) {
System.out.println("Possible commands");
System.out.println("price <price>");
System.out.println("seat <row> <seat>");
System.out.println("left");
System.out.println("remaining <price>");
System.out.println("print");
System.out.println("quit");
System.out.println("help");
} else if (ans.equals("price")) {
int p = input.nextInt();
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
System.out.println("Next available seat at position: " + i + " " + j);
}
}
}
// Find the 'best' seat at the given price
} else if (ans.equals("seat")) {
int r = input.nextInt();
int c = input.nextInt();
int k;
int i;
int j;
for (int l = 0; l < 6; l++) {
k = 1;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if (k == input.nextInt()) {
// check if the seat has already been reserved
if (seats[i][j]== 0) {
System.out.println("That seat has already been reserved");
}
// if its not reserved then reserve it
else {
seats[i][j]= 0;
}
}
k++;
System.out.println(seats[i][j]);
}
}
}
// Reserve the given row and seat, if possible
} else if (ans.equals("left")) {
// Print the total available seats
} else if (ans.equals("remaining")) {
int p = input.nextInt();
// Print the total available seats at this price
} else if (ans.equals("print")) {
for (int r = 0; r < seats.length; ++r) {
for (int s = 0; s < seats[r].length; ++s) {
System.out.print(seats[r][s] + " ");
}
System.out.println();
}
} else if (!ans.equals("quit")) {
System.out.println("Come again?");
}
} while (!ans.equals("quit"));
System.out.println("Good bye");
}
}
This array represents theater seats and I have to mark sold seats by changing the price to 0. I also have to make sure seats are open when a user asks for a a certain spot, and when a user enters a price, find any seats that are open.
So I'm pretty sure I figured out the code for finding the best seat at any given price. I can't figure out how to do the remaining code.
I just need to find out how to print the total available seats and also how to print the total available seats when a certain price is entered.
Thanks.
You'd just use nested for loops, like you did before, except now you'd have some kind of a availableSeats counter you'll increment every time a seat meets a certain condition.
Like so:
int availableSeats = 0;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if(seats[i][j] == sometargetprice){
availableSeats++;
}
}
}
System.out.println("Total of " + availableSeats + " are available.");
Unless I'm not understanding the problem correctly.
I am trying to code a simple program in which the user can view and update a list of NBA player's racing for the MVP Trophy. However I have failed in the past to code a program in which can loop for however long the user decides to. I want the program to have the options 1. Go Back & 2. Exit but I cannot figure out how to loop it. Here is my Rank.java & AdminAccount.java. Hope it is not confusing to understand, thank you for reading.
import java.util.Scanner;
public class Rank {
String player[] = { "Stephen Curry", "Russel Westbrook", "Kevind Durant", "LeBron James", "Kawhi Leonard" };
Scanner rankInput = new Scanner(System.in);
Scanner playerInput = new Scanner(System.in);
int rank;
String playerUpdate;
public void Rank() {
System.out.println("Rank\tPlayer");
for (int counter = 0; counter < player.length; counter++) {
System.out.println(counter + 1 + "\t" + player[counter]);
}
}
public void updateRank() {
System.out.print("Select rank to update: ");
rank = rankInput.nextInt();
if (rank == 1) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[0] = playerUpdate;
} else if (rank == 2) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[1] = playerUpdate;
} else if (rank == 3) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[2] = playerUpdate;
} else if (rank == 4) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[3] = playerUpdate;
} else if (rank == 5) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[4] = playerUpdate;
}
}
}
import java.util.Scanner;
public class AdminAccount {
public static void main(String[] args) {
Rank rank = new Rank();
Scanner adminInput = new Scanner(System.in);
Scanner exitInput = new Scanner(System.in);
boolean keepRunning = true;
// menu variables
int menuOption;
int exitOption;
while (keepRunning) {
System.out.println("*** NBA MVP Race Administor Account ***");
System.out.print("\n1.Ranking 2.Update\t- ");
menuOption = adminInput.nextInt();
System.out.println("");
if (menuOption == 1) {
rank.Rank();
} else if (menuOption == 2) {
rank.updateRank();
}
}
}
}
Just add an "exit" option to your loop:
while(keepRunning){
System.out.println("*** NBA MVP Race Administor Account ***");
System.out.print("\n1.Ranking 2.Update 3.Exit\t- ");
menuOption = adminInput.nextInt();
System.out.println("");
if(menuOption == 1)
{
rank.Rank();
}
else if(menuOption == 2)
{
rank.updateRank();
}
else
{
keepRunning = false;
}
}
This a sample code using arrays
This Program Uses Do.... While Loop to Loop over a whole program when there is a user prompt.
package doWhileLoop;
import java.util.Scanner;
public class doWhileLoop {
public static void main(String[] args) {
//this is a program to prompt a user to continue or pass using the do while loop
String programCounter;
do {
int sum=0;
int list[] = new int[3];
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 numbers to be added: ");
for (int i = 0; i < 3; i++) {
list[i] = in.nextInt();
sum+= list[i];
}
System.out.println("sum = "+ sum);
System.out.println("Enter Yes to continue or No to exit........");
programCounter = in.next();
}
while (programCounter.equals("yes"));
}
}