this block of code going straight to break in java - java

I have this block in a switch case statement that when selected, just breaks and presents me with the main menu again.
System.out.println("Choose a competitor surname");
String competitorChoice2 = input.nextLine();
int lowestSpeed = Integer.MAX_VALUE;
int highestSpeed = 0;
for(int j = 0; j < clipArray.length; j++) {
if(clipArray[j] != null) {
if(competitorChoice2.equals(clipArray[j].getSurname())) {
if(clipArray[j].getSpeed() > clipArray[highestSpeed].getSpeed()) {
highestSpeed = j;
}
}
}
}
for(int i = 0; i < clipArray.length; i++) {
if(clipArray[i] != null) {
if(competitorChoice2.equals(clipArray[i].getSurname())) {
if(clipArray[i].getSpeed() < clipArray[lowestSpeed].getSpeed()) {
lowestSpeed = i;
}
}
}
}
for(int h = lowestSpeed; h < highestSpeed; h++ ) {
System.out.println(""+clipArray[h].getLength());
}
I have an array of objects and each object has a surname and a speed.
I want the user to choose a surname and display the speeds of all of their clips from lowest to highest.
when I select this option it just breaks and brings me back to the main menu
The speeds are also originally entered as floats.
here is the menu:
while (true) {
System.out.println("Please select one of the following options by entering a number: \n"
+ "1) Quit\n"
+ "2) Add a new clip to the records\n"
+ "3) View information about a clip via an index number\n"
+ "4) Change information about a clip via an index number\n"
+ "5) List all competitors which have a clip recorded\n"
+ "6) Choose a competitor and display their longest clip\n"
+ "7) Choose a competitor and display their clips arranged by speed\n"
+ "8) display elements of array in alphabetical order");
choice = input.nextInt();
input.nextLine();
switch (choice) {
switch (choice) {
case (1):
System.out.println("You have quit the program");
System.exit(0);
case (2):
Clip c = new Clip();
System.out.println("Set an index number between 1-1000");
int setIndexNumber = input.nextInt();
c.setIndexNumber(setIndexNumber);
System.out.println("What is the given name of the competitor?");
String givenName = input.next();
c.setGivenName(givenName);
System.out.println("What is the surname of the competitor?");
String surname = input.next();
c.setSurname(surname);
System.out.println("What is the length of the clip?");
float setLength = input.nextFloat();
c.setLength(setLength);
System.out.println("What is the speed of the competitor?");
float setSpeed = input.nextFloat();
c.setSpeed(setSpeed);
System.out.println("What what time was this recorded? (24 hour)");
System.out.println("Enter hour: ");
int setHour = input.nextInt();
System.out.println("Enter minute: ");
int setMin = input.nextInt();
c.setTime(setHour, setMin);
clipArray[firstAvailableIndex()] = c;
counter++;
break;
case (3):
System.out.println("Which clip do you want to view?\n"
+ "Select from index 0-1000:");
int indexNo = input.nextInt();
for (int j = 0; j < clipArray.length; j++) {
if (j == indexNo) {
System.out.println("Index Number: " + clipArray[j].getIndexNumber());
System.out.println("Given Name: " + clipArray[j].getGivenName());
System.out.println("Surname: " + clipArray[j].getSurname());
System.out.println("Length: " + clipArray[j].getLength());
System.out.println("Speed: " + clipArray[j].getSpeed());
System.out.println("Time: " + clipArray[j].getHour() + ":" + clipArray[j].getMinute());
break;
}
}
break;
case (4):
System.out.println("Which clip do you want to change? choose and index number: ");
int clipIndex = input.nextInt();
input.nextLine();
System.out.println("What do want to set this given name to?");
String editGivenName = input.nextLine();
clipArray[clipIndex].setGivenName(editGivenName);
System.out.println("What do you want to set this surname to?");
String editSurname = input.nextLine();
clipArray[clipIndex].setSurname(editSurname);
System.out.println("What do you want to set this length to?");
float editLength = input.nextFloat();
clipArray[clipIndex].setLength(editLength);
System.out.println("What do you want to set this speed to?");
float editSpeed = input.nextFloat();
clipArray[clipIndex].setSpeed(editSpeed);
System.out.println("What do you want to set this hour to?");
int editHour = input.nextInt();
System.out.println("What do you want to set this minute to?");
int editMin = input.nextInt();
clipArray[clipIndex].setTime(editHour, editMin);
break;
case (5):
for (int g = 0; g < clipArray.length; g++) {
if (clipArray[g] != null) {
System.out.println(""+clipArray[g].getSurname());
}
}
break;
case (6):
System.out.println("Choose a competitor by surname");
String competitorChoice = input.nextLine();
int longestClip = 0;
for(int i = 0; i < clipArray.length; i++) {
if(clipArray[i] != null) {
if (competitorChoice.equals(clipArray[i].getSurname())) {
if(clipArray[i].getLength() > clipArray[longestClip].getLength()) {
longestClip = i;
}
}
}
}
System.out.println(""+clipArray[longestClip].getLength()+", at Index: "+clipArray[longestClip].getIndexNumber());
break;
case (7):
System.out.println("Choose a competitor surname");
String competitorChoice2 = input.nextLine();
int lowestSpeed = Integer.MAX_VALUE;
int highestSpeed = 0;
for(int j = 0; j < clipArray.length; j++) {
if(clipArray[j] != null) {
if(competitorChoice2.equals(clipArray[j].getSurname())) {
if(clipArray[j].getSpeed() > clipArray[highestSpeed].getSpeed()) {
highestSpeed = j;
}
}
}
}
for(int i = 0; i < clipArray.length; i++) {
if(clipArray[i] != null) {
if(competitorChoice2.equals(clipArray[i].getSurname())) {
if(clipArray[i].getSpeed() < clipArray[lowestSpeed].getSpeed()) {
lowestSpeed = i;
}
}
}
}
for(int h = lowestSpeed; h < highestSpeed; h++ ) {
System.out.println(""+clipArray[h].getLength());
}
break;
case (8):
for(int i = 1; i < counter; i++) {
for(int j = 0; j < counter - 1; j++) {
if(((clipArray[j].getSurname()).compareToIgnoreCase((clipArray[j+1].getSurname()))) > 0) {
Clip temp = clipArray[j];
clipArray[j] = clipArray[j+1];
clipArray[j+1] = temp;
}
}
}
for(int g = 0; g < counter; g++) {
System.out.println(clipArray[g].getSurname());
}
break;
default:
System.out.println("you have not selected a valid option");
break;
}//end of switch case
EDIT: out of bounds exceptions at the if statement for the lowest speed

When lowestSpeed is Integer.MAX_VALUE, that's out of bounds for the clipArray. Change the initialization for lowestSpeed to:
int lowestSpeed = 0;
Initializing a variable to the maximum before doing a loop that searches for the minimum is appropriate when the variable is used to store the minimum value itself, but in this case it's not: it's storing the index of the element having the minimum value, so start with the first valid index (Er, I think).

Related

I am unable to delete elements from within my array when i ask for user input

When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.

My while loop prints menu twice [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I wrote this program called soccer team roaster. It stores player's jerseys number and player rating. And then does what ever the user wants to do with it within the menu option. But for some reason the menu option keeps on printing twice. I've been informed that its because when I ask for the int input for PlayerRating[i] it takes the Enter button and an input when I first ask for the user's input for String "menuOption". Can someone help?
Here is the code
import java.util.Scanner;
public class SoccerTeamRoaster {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final int JERSY_NUMS = 5;
int[] JersyNumber = new int[JERSY_NUMS];
int[] PlayerRating = new int[JERSY_NUMS];
String[] jPut = new String[JERSY_NUMS];
int i = 0;
boolean quit = false;
for (i = 0; i < JERSY_NUMS; i++) {
System.out.println("Enter player " + (i + 1) + "'s jersey number: ");
JersyNumber[i] = sc.nextInt();
System.out.println("Enter player " + (i + 1) + "'s rating: ");
PlayerRating[i] = sc.nextInt();
System.out.println("");
}
System.out.println("");
System.out.println("ROSTER");
int N = 0;
for (N = 0; N < JERSY_NUMS; N++) {
System.out.println("Player " + (N + 1) + " -- Jersey number: " + JersyNumber[N] + ", Rating: " + PlayerRating[N]);
}
while (!quit) {
String Stg = "MENU\n"
+ "u - Update player rating\n"
+ "a - Output players above a rating\n"
+ "r - Replace player\n"
+ "o - Output roster\n"
+ "q - Quit\n";
System.out.println("");
System.out.println(Stg);
System.out.println("Choose an option: ");
String menuOption = "?";
menuOption = sc.nextLine();
boolean correctInput = false;
if (menuOption.equals("u") || menuOption.equals("a") || menuOption.equals("r") || menuOption.equals("o") || menuOption.equals("q")) {
correctInput = true;
menuOption = menuOption.trim();
} else {
correctInput = false;
}
if (menuOption.equals("u")) {
System.out.println("Enter jersey number: ");
int jerseyNum = sc.nextInt();
System.out.println("New rating for player: ");
int newRate = sc.nextInt();
int M = 0;
for (M = 0; M < JERSY_NUMS; M++) {
if (JersyNumber[M] == jerseyNum) {
PlayerRating[M] = newRate;
}
}
} else if (menuOption.equals("a")) {
System.out.println("Enter a rating: ");
int rating = sc.nextInt();
int k = 0;
for (k = 0; k < JERSY_NUMS; k++) {
if (PlayerRating[k] > rating) {
System.out.println("Player " + (k + 1) + " -- Jersey Number: " + JersyNumber[k] + ", Rating: " + PlayerRating[k]);
}
}
} else if (menuOption.equals("o")) {
System.out.println("ROSTER");
int J = 0;
for (J = 0; J < JERSY_NUMS; J++) {
System.out.println("Player " + (J + 1) + " -- Jersey number: " + JersyNumber[J] + ", Rating: " + PlayerRating[J]);
}
} else if (menuOption.equals("q")) {
quit = true;
} else if (menuOption.equals("r")) {
System.out.println("Enter jersey number: ");
int jerNum = sc.nextInt();
int l = 0;
for (l = 0; l < JERSY_NUMS; l++) {
if (JersyNumber[l] == jerNum) {
System.out.println("Enter new jersey number: ");
JersyNumber[l] = sc.nextInt();
System.out.println("Enter new player rating: ");
PlayerRating[l] = sc.nextInt();
}
}
int a = 0;
for (a = 0; a < JERSY_NUMS; a++) {
System.out.println("Player " + (a + 1) + " -- Jersey number: " + JersyNumber[a] + ", Rating: " + PlayerRating[a]);
}
}
}
return;
}
}
The reason why it prints two times is because of this code...
menuOption = sc.nextLine();
just change it to
menuOption = sc.next();
now, it only prints one time
You use Scanner#nextInt to get jersey numbers and rates. But Scanner#nextInt does not consume the last newline character of input, and thus that newline character is consumed when Scanner#nextLine is called after that.
So you have to call Scanner#nextLine once to throw aray the newline character before while loop.

(Java) Need help summing digits in sets of integers and applying them to a credit card verification algorithm

I have to create a java program that verifies a credit card number based on whether it is a Visa or MasterCard. I am required to read the card number as a single string with spaces in between each set of four digits (xxxx xxxx xxxx xxxx). There must be 16 digits. All the digits in the number must be totaled. Then, if sum%10=0, it is a valid Visa. If sum%10=1, it is a valid MasterCard. Any deviation from this results in an invalid message.
My problem is that once I run my current program, I enter the number and the card type, and then the program stops and won't continue. I'm not sure what I'm doing wrong here.
import java.util.Scanner;
public class Assignment4
{
public static void main (String[] args)
{
String cardNum;
String typeAnswer;
char cardType;
int testSum;
int modResult;
Scanner scan = new Scanner (System.in);
System.out.println("\t\t Credit Card Verification");
System.out.println("\t\t ========================");
System.out.println("Enter your card number <xxxx xxxx xxxx xxxx>: ");
cardNum = scan.nextLine();
if(cardNum.length()<19 || cardNum.length()>19)
{
System.out.println("Incorrect card number. Re-launch the program and enter a 16-digit card number");
System.exit(0);
}
else
{
System.out.println("Is your card Visa or MasterCard?");
typeAnswer = scan.next().toUpperCase();
cardType = answer.charAt(0);
String numSet1 = cardNum.substring(0,4);
String numSet2 = cardNum.substring(5,9);
String numSet3 = cardNum.substring(10,14);
String numSet4 = cardNum.substring(15,19);
int i = Integer.parseInt(numSet1);
int j = Integer.parseInt(numSet2);
int k = Integer.parseInt(numSet3);
int l = Integer.parseInt(numSet4);
int sum1=0;
while(i>0)
{
sum1 = sum1 + (i%10);
i = i/10;
}
int sum2 = 0;
while(j>0)
{
sum2 = sum2 + (j%10);
j = j/10;
}
int sum3 = 0;
while(k>0)
{
sum3 = sum3+ (k%10);
k = k/10;
}
int sum4 = 0;
while(l>0)
{
sum4 = sum4 + (l%10);
j = j/10;
}
testSum = sum1 + sum2 + sum3 + sum4;
modResult = testSum%10
if(modResult=0 && cardType=V)
{
System.out.println("Valid Visa card.");
}
else if (modResult=1 && cardType=M)
{
System.out.println("Valid MasterCard.");
}
else
{
System.out.println("Not a valid " + typeAnswer + " card. Re-launch and try again.");
}
}
}
}
answer is undefined. It should be typeAnswer.
A semicolon is missing after modResult = testSum%10.
The conditions in if statements are wrong:
Use == operator, not = operator, to compare values of primitive types.
Use Character literals 'V' and 'M' instead of undefined symbols V and M.
l is not updated in the 4th loop, so it will be an infinite loop if the 4th number is positive. j = j/10; should be l = l/10;.
Try this:
import java.util.Scanner;
public class Assignment4
{
public static void main (String[] args)
{
String cardNum;
String typeAnswer;
char cardType;
int testSum;
int modResult;
Scanner scan = new Scanner (System.in);
System.out.println("\t\t Credit Card Verification");
System.out.println("\t\t ========================");
System.out.println("Enter your card number <xxxx xxxx xxxx xxxx>: ");
cardNum = scan.nextLine();
if(cardNum.length()<19 || cardNum.length()>19)
{
System.out.println("Incorrect card number. Re-launch the program and enter a 16-digit card number");
System.exit(0);
}
else
{
System.out.println("Is your card Visa or MasterCard?");
typeAnswer = scan.next().toUpperCase();
cardType = typeAnswer.charAt(0);
String numSet1 = cardNum.substring(0,4);
String numSet2 = cardNum.substring(5,9);
String numSet3 = cardNum.substring(10,14);
String numSet4 = cardNum.substring(15,19);
int i = Integer.parseInt(numSet1);
int j = Integer.parseInt(numSet2);
int k = Integer.parseInt(numSet3);
int l = Integer.parseInt(numSet4);
int sum1=0;
while(i>0)
{
sum1 = sum1 + (i%10);
i = i/10;
}
int sum2 = 0;
while(j>0)
{
sum2 = sum2 + (j%10);
j = j/10;
}
int sum3 = 0;
while(k>0)
{
sum3 = sum3+ (k%10);
k = k/10;
}
int sum4 = 0;
while(l>0)
{
sum4 = sum4 + (l%10);
l = l/10;
}
testSum = sum1 + sum2 + sum3 + sum4;
modResult = testSum%10;
if(modResult==0 && cardType=='V')
{
System.out.println("Valid Visa card.");
}
else if (modResult==1 && cardType=='M')
{
System.out.println("Valid MasterCard.");
}
else
{
System.out.println("Not a valid " + typeAnswer + " card. Re-launch and try again.");
}
}
}
}
Note that there are more problems to be fixed in this program. For example, this program accepts -123 -456 -789 -147 as a valid Visa card.
In the line: cardType=answer.charAt(0); You have an error. The variable answer is undefined. It should be cardType=typeAnswer.charAt(0);
Next you have created an infinity loop ,i.e. the fourth loop
while(l>0)
{
sum4 = sum4 + (l%10);
j = j/10;
}
Another mistake was you were not using the equality in the if statement, instead you were assigning values to the variables.
The correct code would be as follows:
import java.util.*;
import java.io.*;
public class CreditCardVerification
{
public static void main (String[] args)
{
String cardNum;
String typeAnswer;
char cardType;
int testSum=0;
int r;
int modResult;
Scanner scan = new Scanner (System.in);
System.out.println("\t\t Credit Card Verification");
System.out.println("\t\t ========================");
System.out.println("Enter your card number <xxxx xxxx xxxx xxxx>: ");
cardNum = scan.nextLine();
if(cardNum.length()<19 || cardNum.length()>19)
{
System.out.println("Incorrect card number. Re-launch the program and enter a 16-digit card number");
System.exit(0);
}
else
{
System.out.println("Is your card Visa or MasterCard?");
typeAnswer = scan.next().toUpperCase();
cardType = typeAnswer.charAt(0);
String numSet1 = cardNum.substring(0,4);
String numSet2 = cardNum.substring(5,9);
String numSet3 = cardNum.substring(10,14);
String numSet4 = cardNum.substring(15,19);
int i = Integer.parseInt(numSet1);
int j = Integer.parseInt(numSet2);
int k = Integer.parseInt(numSet3);
int l = Integer.parseInt(numSet4);
int sum1=0;
while(i!=0)
{
sum1 = sum1 + (i%10);
i = i/10;
}
int sum2 = 0;
while(j!=0)
{
sum2 = sum2 + (j%10);
j = j/10;
}
int sum3 = 0;
while(k!=0)
{
sum3 = sum3+ (k%10);
k = k/10;
}
int sum4 = 0;
while(l!=0)
{
sum4 = sum4 + (l%10);
l = l/10;
}
testSum = sum1 + sum2 + sum3 + sum4;
modResult = testSum%10;
if((modResult==0) && (cardType=='V'))
{
System.out.println("Valid Visa card.");
}
else if ((modResult==1) && (cardType=='M'))
{
System.out.println("Valid MasterCard.");
}
else
{
System.out.println("Not a valid " + typeAnswer + " card. Re-launch and try again.");
System.exit(0);
}
}
}
}`
Try this code.Its not so different from the code given by MikeCat but this should solve your problem. Take caution that don't enter just any number and test the code. Try it with a valid Visa or MasterCard credit card.

Problems with my for loops printing out my arrays

can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;
import java.util.Scanner;
/**
*
* #author Anders
*/
public class Assignment91 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String studName = "Anders";
int counter = 1;// i think the problem is here
int answer = 1; // same
System.out.println(" welcome to student database, show informations about student" + studName);
Scanner courseScan = new Scanner(System.in);
Scanner gradeScan = new Scanner(System.in);
Scanner answerScan = new Scanner(System.in);
System.out.println(" Enter the name of courses");
String[] courseArray = new String[counter];
int[] gradeArray = new int[counter];
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
int n = gradeArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (gradeArray[j - 1] > gradeArray[j]) {
//swap the elements!
temp = gradeArray[j - 1];
gradeArray[j - 1] = gradeArray[j];
gradeArray[j] = temp;
// Swap the course array
String gradeArrayTemp;
gradeArrayTemp = courseArray[j - 1];
courseArray[j - 1] = courseArray[j];
courseArray[j] = gradeArrayTemp;
}
}
}
for (int l = 0; l < courseArray.length; l++) {
System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
}
Scanner request = new Scanner(System.in);
System.out.println(" what do you want to do. Enter 1 to rename a course");
System.out.println(" enter 2 to change a grade ");
int regNumber = request.nextInt();
switch (regNumber) {
case 1: // rename a course
Scanner search = new Scanner(System.in);
System.out.println("Enter the name of the course you want to rename");
String searchCourse = search.nextLine();
for (int i = 0; i < courseArray.length; i++) {
if (searchCourse.equals(courseArray[i])) {
System.out.println("Yes there is a course named " + courseArray[i]);
System.out.println(" to change coursename insert new name");
// here i change the coursename
Scanner newName = new Scanner(System.in);
courseArray[i] = newName.nextLine();
} else {
System.out.println(" no record of this course");
}
System.out.println(" you have chosen to rename course into " + courseArray[i]);
}
}
}
}
In this section of the code:
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
int k = 0;
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
k++;
}
} else {
System.out.println("Sorry, there is no more memory");
}
And
for (int i = 0; i < courseArray.length; i++) {
if(courseArray[i] != null)
System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
}
I have assumed that you take only 20 records depending on the loop. So i initiated arrays
String[] courseArray = new String[20];
int[] gradeArray = new int[20];

Loop the program until 0(exit)(java)

I have this java code that basically just prints a christmas tree of X height.However, the program ask for the number, then print the tree and then just end.I would like it to loop until I enter 0,wich would end the program,and also I would like to make it print only if the number entered is from 1-40(not over 40).Im begining in the java world and I dont know how to do that.Heres my code for now:
public class xtree {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
Thank you, im a beginner to java so please be lenient ;)
Well, I would separate the method out into two:
A printChristmasTree method, which accepts the height as a parameter
Your main method, which just deals with taking user input and calling printChristmasTree or exiting
Most of your current main method would go into the printChristmasTree, and main would be a loop. Something like:
public static void main(String[] args) {
Scanner scan = new Scanner(in);
while (true) {
System.out.print("Please enter a number (0-40): ");
int height = scan.nextInt();
if (height == 0) {
// Exit the program
return;
} else if (height >= 1 && height <= 40) {
printChristmasTree(height);
} else {
System.out.println("Invalid input.");
}
}
}
There are other approaches you could use instead of returning from a while (true) loop, but this looks the simplest to me.
The separation of the "taking input" from the "printing the Christmas tree" aspects leads to much more readable code than keeping them combined, in my view - and it's more flexible in terms of things like writing a different program to print all valid Christmas trees.
Use a while loop:
Scanner scan = new Scanner(System.in);
System.out.print("please enter a number: ");
int temp = scan.nextInt();
while (temp>0) {
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
System.out.print(" ");
}
for(int k = 0; k<z; k++)
{
System.out.print("*");
}
System.out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
System.out.print(" ");
}
System.out.println("*");
temp = scan.nextInt();
}
Here's the code for doing that:
public class xtree {
public static void main(String[] args)
{
int temp;
do{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
temp = scan.nextInt();
if(temp >= 1 && temp <= 40){ //don't display a tree higher than 40
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}else if(temp != 0){
out.print("Please enter a number between 1 and 40!");
}
}while(temp != 0);
}
}

Categories

Resources