In the code below I have created a program that prints a triangle based on the number that the user inputs for the number of lines.
My questions is this: I am doing all of the computing in the main method, however how would I go about this by splitting this program up and putting the loops in their own method and calling it into the main method?
public class Triangle {
public static void main(String[] args) {
//declare a scanner for user input
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of lines: ");
int numLines = input.nextInt();
//include an if statement to make sure that the number of lines that
the user inputs is greater than zero
if (numLines <= 0)
{
System.out.println("Number of lines is negative. Exiting.");
System.exit(0);
}
//This for loops prints one line for each iteration.
for(int i=0;i<numLines;i++)
{
//This for loop takes care of the preceding spaces in each line.
for(int j=0;j<numLines-i-1;j++)
System.out.print(" ");
//This for loop prints the required number of characters in each line.
for(int k=0;k<=i;k++)
System.out.print("* ");
//We are done with a line. Moving on to the next one.
System.out.println();
}
}
}
You can also do it like this:
import java.util.Scanner;
public class Triangle {
// declare a scanner for user input
Scanner input = new Scanner(System.in);
public int getInput() { // method to take user input
System.out.print("Enter the number of lines: ");
int numLines = input.nextInt();
// include an if statement to make sure that the number of lines that
// the user inputs is greater than zero
if (numLines <= 0) {
System.out.println("Number of lines is negative. Exiting.");
System.exit(0);
}
return numLines;
}
public void printTriangle() {
int numLines = getInput();
// This for loops prints one line for each iteration.
for (int i = 0; i < numLines; i++) {
// This for loop takes care of the preceding spaces in each line.
for (int j = 0; j < numLines - i - 1; j++)
System.out.print(" ");
// This for loop prints the required number of characters in each
// line.
for (int k = 0; k <= i; k++)
System.out.print("* ");
// We are done with a line. Moving on to the next one.
System.out.println();
}
}
public static void main(String[] args) {
Triangle obj = new Triangle(); // create object
obj.printTriangle(); // call using object
}
}
Here we are creating two functions :
getInput() To take input from user and return numLines to the caller.
printTriangle() To print pattern
In the end we are creating an object of the Triangle class and calling the printTriangle().
Triangle obj = new Triangle(); // create object
obj.printTriangle(); // call using object
Related
I am a beginner and have a simple piece of code that works - it is designed to ask a user for seven numbers and store them in an array then print out what they entered
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
What I want to do is add an error trap to make sure the number is not greater than 49 - I have added the following code and there are no errors and it runs fine but I have to add two numbers for each loop as it only stores the second input - can anyone help tell me why?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] inputs = new int[7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++) {
if ( in .nextInt() > 49) {
System.out.println("please enter a number less than 49");
inputs[i] = in .nextInt();
} else
inputs[i] = in .nextInt();
}
System.out.println("You have entered the numbers:");
for (int i: inputs) {
System.out.println(i);
}
}
when you do in.nextInt() it give you the "next" integer in the input, so you are doing this twice for each loop cycle, once in the if statement and the other in the if or else body. so you need invoke that function only once. something like this:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [] inputs = new int [7];
System.out.println("Enter 6 numbers and a bonus ball");
for (int i = 0; i < 7; i++)
{
int current_input = in.nextInt()
if ( current_input > 49)
{
System.out.println("please enter a number less than 49");
inputs [i] = in.nextInt();
}
else
inputs [i] = current_input;
}
System.out.println("You have entered the numbers:");
for (int i : inputs)
{
System.out.println(i);
}
}
I don't test the code but you have the idea.
here you have another problem still, and is that when the user types a number over 49, the second time you ask the number to the user, you don't test again that it's below 49 so the user can enter any number.
I am creating a cash register where I have to use a scanner and can only have 5 input amounts. It has to also include hst and that is by only having a "h" after or before an amount. My question is how would the program recognize that I have put an "h" after or before an amount? This seems to be done only using a string variable, so how would I accomplish that? I have to store the inputs in an array, and so I got that to work.
My Code:
// Import scanner class
import java.util.Scanner;
// Create class and method
class Main {
public static void main(String[] args) {
// Declare the scanner object and create scanner variables
Scanner inp = new Scanner(System.in);
System.out.println("Press any key to start");
String key = inp.nextLine();
System.out.println("\nEnter the amount of each item");
System.out.println("Upto 5 inputs are allowed!\n");
// Define an array double variable, set the limit to 5 inputs
double[] numbers = new double[5];
// Create a for loop to input any numbers 5 times
for (int i = 0; i < numbers.length; i++){
// Add a scanner input to let the user type out the values
numbers[i] = inp.nextDouble();
}
}
}
below code asks the user input for 5 times , and only valid values will be in the Array , Vald values are the values with 'h' at start or end and should only occur once. i.e. at 'h' at both end and start or more than once is invalid.
public static void main(String[] args) throws ParseException {
int counter = 1;
Double[] result = new Double[5];
int index = 0;
while(counter <= 5) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an Amount ");
String value = scanner.nextLine();
int indexOfH = value.indexOf("h");
int lastIndexOfH = value.lastIndexOf("h");
boolean containsHatstartsOrEnd = indexOfH == 0 || indexOfH == (value.length()-1);
if(containsHatstartsOrEnd && indexOfH==lastIndexOfH){ //Validate h at begins or end and should contains only once
result[index] = Double.parseDouble(value.replace("h", ""));
index++;
}
counter++;
}
System.out.println("Printing Valid values");
for(int i=0; i< result.length; i++) {
if(result[i]!=null) {
System.out.println(result[i]);
}
}
}
input & result
Enter an Amount 13.45h
Enter an Amount 55h.65
Enter an Amount 32h.33h
Enter an Amount h100.23
Enter an Amount h20
Printing Valid values
13.45
100.23
20.0
Im stuck on this, I need a code that use 2 nested loops for this assignment (there are other solutions, but I need to demonstrate my understanding of nested loops). But I just dont get it. The outer loop repeats the entire algorithm and the inner loop iterates half-way (or less) through the string. I am not sure on what I need to put inside the for loops. This is what I have so far. Any Assistance would be pleasured.
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String x = 0;
String y = input.length-1;
for (String i = 0; i < line.length-1; i ++){
for (String j = 0; j < line.length-1; j ++){
if (input.charAt(x) == input.charAt(y))
{
x++;
y--;
}
}
}
}
Example Output:
Enter a string: 1331
1331 is a palindrome.
Enter a string: racecar
racecar is a palindrome.
Enter a string: blue
blue is NOT a palindrome.
Enter a string:
Empty line read - Goodbye!
Your algorithm is flawed, your nested loop should be to prompt for input - not to check if the input is a palindrome (that requires one loop itself). Also, x and y appear to be used as int(s) - but you've declared them as String (and you don't actually need them). First, a palindrome check should compare characters offset from the index at the beginning and end of an input up to half way (since the offsets then cross). Next, an infinite loop is easy to read, and easy to terminate given empty input. Something like,
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string: ");
System.out.flush();
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
boolean isPalindrome = true;
for (int i = 0; i * 2 < line.length(); i++) {
if (line.charAt(i) != line.charAt(line.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.printf("%s is a palindrome.%n", line);
} else {
System.out.printf("%s is NOT a palindrome.%n", line);
}
}
System.out.println("Empty line read - Goodbye!");
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String reversedText ="";
for(int i=line.length()-1/* takes index into account */;i>=0;i++) {
reversedText+=line.split("")[i]; //adds the character to reversedText
}
if(reversedText ==line){
//is a palidrome
}
}
Your code had lot of errors. I have corrected them and used a while loop to check if its a palindrome or not. Please refer below code,
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
String line;
boolean isPalindrome = true;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
int x = 0;
int y = line.length() - 1;
while (y > x) {
if (line.charAt(x++) != line.charAt(y--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(line + " is a palindrome");
} else {
System.out.println(line + "is NOT a palindrome");
}
System.out.println();
}
}
}
The point of this program is to take a three digit number from the command line and then reversing it. After that it is supposed to subtract the reverse from the original number and add the original to the reversed.
This is supposed to only take numbers that are three digits and the first digit of the number has to be greater than the last so that it is not negative when the numbers are subtracted.
The code compiles correctly but when I put a number in the command line prints out the line "Enter a three digit number, with the first digit larger than the third" only.
What it is supposed to print out like
$ java Rev 351
Reverse and subtract:
351
153 -
---
198
Reverse and add:
198
891 +
---
1089
This is my code:
public class Rev
{
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
num = Integer.parseInt(args[i]);
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
static boolean checkDigits(int number) // checks if numbers are correct
{
int reverse = reverseNum(number);
if(number > reverse)
{
throw new Error("Reverse number needs to be less than the original number!");
}
else
{
return true;
}
}
static int reverseNum(int number) //reverses number
{
int reverse = 0;
int r = 0;
while (number != 0)
{
if(number < 1000 || number > 99)
{
r = number % 10;
reverse = (reverse*10) + r;
number = number/10;
}
}
return reverse;
}
static void subtractNum(int number) // subtracts
{
int reverse = reverseNum(number);
int total = number - reverse;
System.out.println("Reverse and subtract: ");
System.out.println(number);
System.out.println(reverse + " - ");
System.out.println("---");
System.out.println(total);
System.out.println();
number = total;
}
static void addNum(int number) // adds
{
int reverse = reverseNum(number);
int total = number + reverse;
System.out.println("Reverse and add: ");
System.out.println(number);
System.out.println(reverse + " + ");
System.out.println("---");
System.out.println(total);
number = total;
}
}
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
num = Integer.parseInt(args[i]);
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
So the args variable is the command line argument. So if you're compiling via command line, you would call something like java Rev.class 321 where 321 is your 3 digit number. If you want to use the Java console to take inputs, use a Scanner.
To take inputs, use something like this:
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
You're never actually getting a number from the input. You need to do this in your main():
public static void main(String[] args)
{
int num = 0;
for (int i = 0; i < args.length; i++)
{
System.out.println("Enter a three digit number, with the first digit larger than the third");
try (Scanner s = new Scanner(System.in)){
num = s.nextInt();
}
reverseNum(num);
subtractNum(num);
addNum(num);
}
}
The Scanner reads the main input stream (from the keyboard). Otherwise, when you pass in the argument on the command line, it hasn't yet asked you for the input, and prints out the request for input.
Your other problem is that you don't call checkDigits() after getting your number, so you should probably do a while loop using it until you get a number you'll accept, like this:
public static void main(String[] args)
{
int num = -1;
while (num < 0 || !checkDigits(num)){
System.out.println("Enter a three digit number, with the first digit larger than the third");
try (Scanner s = new Scanner(System.in)){
num = s.nextInt();
}
}
reverseNum(num);
subtractNum(num);
addNum(num);
}
Also, your other methods are incorrect in that they are acting on an input parameter (which is possible for objects but not primitives, and is bad practice in any case).
Instead write them as functions which take in values and return them, then modify your main again to look like this:
public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
if (checkDigits(num)){
num = subtractNum(num);
addNum(num);
} else {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}
using nested for loops statements to draw triangles of ""s. The number of ""s on the last row is input from the user (valid range: 5 to 21). the out put should look like this:
Sample output:
How many stars/last row (5-21)? 25
Out of range. Reenter: 7
*
**
***
****
*****
******
*******
so far this is what i have for the code. I don't know how to get it to look like a triangle. any help would be great.
import java.util.Scanner;
public class Lab7_2{
public static void main(String[] args){
//declarations
Scanner input= new Scanner(System.in);
int how_many;//num of triangles
int m; //constant
int c;//constant
int rows;//row
//prompt for input
System.out.println("Drawing triangles program.");
System.out.println("==============================");
System.out.println("How many triangles?");
how_many=input.nextInt();
System.out.println("How many stars/last row (5-21)?");
rows=input.nextInt();
while(rows<=5||rows>=21){
System.out.println("Out of range. Reenter: ");
rows=input.nextInt();
}
for(m=1;m<=rows;m++){
for(c=1;c<=m;c++){
System.out.println("*");
System.out.println();
}
}
}
}
To center a line, use this:
private static String center(String line, int length) {
StringBuilder newLine = new StringBuilder();
for (int i = 0; i < (line.length() - length)/2; i++)
newLine.append(" ");
}
newLine.append(line);
return newLine.toString();
}
Also,
System.out.println();
prints a line break after each string, which is not what you intend.
Fixed code:
private void printTriangle(int base) {
StringBuilder currentStars = new StringBuilder();
for (int currLine = 1; currLine < base; currLine++) {
currentStars.append("*"); // Don't create a new String, just append a "*" to the old line.
//if (currLine % 2 == 1)
// System.out.println(center(currentStars.toString(), base)); // For centered triangle
System.out.println(currentStars.toString()); // For non-centered triangle
}
}
You are using a println statement to print your stars, as such each will be on its own line no matter what
System.out.println("*");
You want a print statement instead
System.out.print("*");
Additionally inside the star printing loop you have an extra System.out.println(); putting a blank line in, that should be outside the inner for loop
for(m=1;m<=rows;m++){
for(c=1;c<=m;c++){
System.out.println("*"); <-- println always starts a new line, should be print
System.out.println(); <--- shouldn't be within inner loop
}
<--- println() should be here to advance to the next line of stars
}
println() always starts a new line after the output. Try print instead and then one println() after the inner loop.
Just fix your for loop as
for (m = 1; m <= rows; m++) {
for (c = 1; c <= m; c++) {
// first print the * on the same line
System.out.print("*");
}
// then move to the next line
System.out.println();
}
Notice, that you need to use System.out.print() (that does not write a new line \n to the output stream) for the asterisks * to get printed on the same line.
I believe this is the most efficient and simple way to do it, saves having to call the print/println method hundreds of times when playing with larger pyramids.
String out;
for (m = 0; m < rows; m++) {
out = "";
for (c = 0; c < m; c++) {
out+="*";
System.out.println(out);
}
}
Basicly your string is "", and you add a "*" after every time you print it to the next line.