So I just created a little program, which prints out a Box of Stars after asking the User to input a specific height and width of the Box, for example:
height: 4; width: 5 would print out this
Starbox :
Here is my code
import java.util.*;
public class Stars {
public static Scanner scan = new Scanner(System.in);
public static int height = scan.nextInt();
public static Scanner scan2 = new Scanner(System.in);
public static int width = scan.nextInt();
public static void main(String[] args) {
drawBox(height, width);
}
public static void drawBox(int height, int width) {
drawStars(width);
drawStarsWithSpaces(height, width);
drawStars(width);
}
public static void drawStars(int width) {
for (int i = 0; i < width; i++) {
System.out.print("*");
}
System.out.println();
}
public static void drawStarsWithSpaces(int height, int width) {
for (int x = 0; x < height - 2; x++) {
System.out.print("*");
for (int i = 0; i < width - 2; i++) {
System.out.print(" ");
}
System.out.print("*");
System.out.println();
}
}
}
My first Question now is, how do implement a Text saying "Height of the Box" and after that "Width of the Box" when I start the program, so the user knows what to input.
Next thing is that I heard, to not use global variables for some reason and that I should implement code only after the main method... but what would the code of the program with these requirements look like?
First, you don't need two Scanners. One is enough.
Second, the comments on your code are right - it's considered bad practice to use static variables if they're not needed (That's what you referenced as 'global').
These values should be internal to the main function (Which should read the values and invoke appropriate functions, so they should be declared and used in it, and not outside of it.
It would look like:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int width = input.nextInt(), height.nextInt();
...
}
As for running code only after main: you initialize width and height in deceleration. As they're declared static, they're initialized the moment the class is loaded.
Before main has an opportunity to be run!
That is also considered bad practice.
And one more thing - it means you can't run any code before the nextInt() happens (Well, you could initialize another static variable with a method that would print the desired instructions...).
To summarize:
Make all the variables you use local to main and then you could print (using System.out.println()) whatever you wanted before scanning the next input (as scanning will happen in main itself.
Related
I am currently learning Java and following some online tutorials. One of the assignments is to compute the body age of a person by getting their various scores, getting the average of these scores and then applying a formula to it to get the total. I can do it with one big class, but the assignment then asks to go further and split everything into different classes. My program currently looks like this:
import java.util.Scanner;
public class fit2 {
public static void main(String[] args) {
int average, bodyAge;
average = average2();
System.out.println(average);
bodyAge = fitAge();
System.out.println(bodyAge);
}
public static int fs() {
int fs;
System.out.println("Enter first number: ");
Scanner bucky = new Scanner(System.in);
fs = bucky.nextInt();
return fs;
}
public static int ss() {
int ss;
System.out.println("Enter second number: ");
Scanner bucky = new Scanner(System.in);
ss = bucky.nextInt();
return ss;
}
public static int average2() {
int first, second, average;
first = fs();
second = ss();
average = (first + second) / 2;
return average;
}
public static int fitAge() {
int fitAge, average;
average = average2();
fitAge = average * 8 / 5 + 10;
return fitAge;
}
}
My idea was to have different methods for each part of the program - two methods to get the users scores and then pass these into a averageing method, which would then pass it into a final method which would apply the formula, then passing it back it into the Main class, which would print that age out as well as the Average age.
I read somewhere that you shouldnt get user input in classes but get it in main and pass it into the average class using parameters -- can anyone advise on this?
Thanks.
Try something like this (as suggested by my comment on the question):
import java.util.Scanner;
public class fit2 {
public static void main(String[] args) {
System.out.println("Enter first number: ");
Scanner bucky = new Scanner(System.in);
int fs = bucky.nextInt();
System.out.println("Enter second number: ");
bucky = new Scanner(System.in);
int ss = bucky.nextInt();
int average = average2(fs, ss);
int bodyAge = fitAge(average);
System.out.println(average);
System.out.println(bodyAge);
}
public static int average2(int first, int second) {
int average;
average = (first + second) / 2;
return average;
}
public static int fitAge(int average) {
int fitAge;
fitAge = average * 8 / 5 + 10;
return fitAge;
}
}
I believe I understand your question - you are unsure of where to place user input in your program.
In a small program like this, it may be wise to place user input in the main() method, solely because you gather user input, delegate input to methods that perform computation on the data that is "under the hood" of the program, and then return the value back to the user.
In your specific instance, this seems like a wise decision, as your program is small and a standard console-based application. This may not always be the case in the future, depending on the program you are writing.
Realistically, it doesn't matter all too much if it runs as intended, but for simplicity sake (remember KISS) putting user input in your main() method is probably a good idea.
I'm trying to create a simple program to output the number of stars entered by user. I'm trying to learn how to use more than one method to do this
Here's my code
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
}
public static void Loop ()
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
The problem I'm facing is that in the Loop method, I am unable to use the variable n
Is there a way to use a variable which is in the main method, in another one?
Ty
-Pingu
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n); //calls Loop function and passes parameter n
}
public static void Loop(int n) //this function now expects a number n
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
simply pass it as parameter:
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n);
}
public static void Loop (int count)
{
for (int counter = 1; counter <= count; counter++)
{
System.out.println("*");
}
}
Pass it as a paramteer
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
loop(n); // added this
}
public static void loop (int n) // changed here
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
I think you should use it as a instance variable and for better understanding name your class like StarClass it can provide better understanding. Good programming practice.
But you should avoid unneccesserily making instance variable without any logic behind it.
I also think you could declare n as a public variable.
That should make it accessible throughout the code.
public int n;
But I guess that passing it as parameter is a better practice, since you don't create a deppendance inside your code. What I mean is, if something changes with the variable you break the function. It's good practice to always keep things "modular" in your code, so it makes it more resilient to changes and debugging.
It's better if you get used to it from the beggining =)
Two ways.. one has been posted already as answer and the other one would be using the variable as a field. This way you can access (and modify) it in every method without having to pass it on.
public class Alpha
{
static int n;
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter no. of stars");
n = input.nextInt();
loop();
}
public static void loop ()
{
for (int counter = 0; counter < n; counter++)
{
System.out.println("*");
}
}
}
And please start method names with lowercase and counting with 0. It's common practise and it helps a lot to use the standards right from the beginning.
Like this you can use variable from different methods in different methods
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum=0;
int a=Sum(sum);
System.out.println("The Average of the numbers is: "+a);
}
public static int Sum(int sum) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the total count of number for Average: ");
int a=sc.nextInt();
for(int i=1;i<=a;i++) {
System.out.println("Enter the"+i+"Number: ");
int b=sc.nextInt();
sum+=b;
}
int avg=sum/a;
return avg;
}
I want to create a program in Java, which -- basing on user inputs -- finds the area of the entered shape. But I failed to achieve that.
This is my script:
import java.util.Scanner;
public class area {
static Scanner advance = new Scanner(System.in);
public void main(String[] args) {
nu();
}
int length;
int height;
int area;
public void nu(){
String message = advance.nextLine();
if (message.equalsIgnoreCase("rectangle")){
System.out.println("Enter the length of the rectangle: ");
length = advance.nextInt();
//length declared.//
System.out.println("Enter the height of the rectangle");
height = advance.nextInt();
//Height has been declared.//
area = length * height;
System.out.print("The area is: " + area);
}
}
}
First problem is, that this code is not running and so I don't know if its working. All the other things are fine. Can you tell me, what I'm doing wrong?
You need to add static to the main method and create a new instance of area. See the code below.
public class area {
static Scanner advance = new Scanner(System.in);
public static void main(String[] args) {
new area().nu();
}
int length;
int height;
int area;
public void nu(){
String message = advance.nextLine();
if (message.equalsIgnoreCase("rectangle")){
System.out.println("Enter the length of the rectangle: ");
length = advance.nextInt();
//length declared.//
System.out.println("Enter the height of the rectangle");
height = advance.nextInt();
//Height has been declared.//
area = length * height;
System.out.print("The area is: " + area);
}
}
}
You need to add static to the main method of your program.
You won't be able to directly call the nu() method from the main, as it is instance method to call it you will need to create an object of your class.
public static void main(String[] args) {
area a = new area();
a.nu();
}
The other alternate is that you can make your nu() method to be static but then you will not be able to use int length;int height;int area; instance variables directly in your static method nu(). Then you will either need to make these variables to be static too or create an object of the class and then use these variables as per your need.
Because of Java program can't find the main method to run:
We need to add static keyword in 3 places according to your code.
Please try with below full source code:
import java.util.Scanner;
public class area {
static Scanner advance = new Scanner(System.in);
public static void main(String[] args) { //1st change
nu();
}
static int length; //2nd change
static int height; //2nd change
static int area; //2nd change
public static void nu(){ //3rd change
String message = advance.nextLine();
if (message.equalsIgnoreCase("rectangle")){
System.out.println("Enter the length of the rectangle: ");
length = advance.nextInt();
//length declared.//
System.out.println("Enter the height of the rectangle");
height = advance.nextInt();
//Height has been declared.//
area = length * height;
System.out.print("The area is: " + area);
}
}
}
Need some help trying to set up this assignment. I am not to good with arrays, nor setting up methods to be used in the main. I need to make an array of 10 random numbers 1-100, that can be compared to the user input. I only need the comparison true/false to display. Here is what I have.
I get several errors in trying to print, so i haven't even tried to compare it to the user input yet.
Thanks,
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print(shots);
}
public int [] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++)
shots[i] = r.nextInt(100);
return shots;
}
public static void print(int shots[]) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}
As commentors said, please provide error messages.
However, I can pick out several issues just for starters. Let's look at your main method...
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
print int [](shots);
}
In this call to the print method, why do you have int [] in there? Are you trying to cast something to an int array? Anyways, that has to come out.
Also, you are passing the print method some shots variable that doesn't exist.
Your print method takes an int array as its only argument, so you have to pass it a valid int array. Perhaps you meant to call getRandomNumbers() and pass the int array that it returns to the print method?
Also, what's with the nested classes you're showing. You have this class Final with another class ShotClass defined inside of it. And your closing brackets are all out of whack.
In short, you need to do as the comments ask and format your code and then work through each individual error message, because you've got a whole lot to fix.
EDIT
I'm not sure if I'm doing you more harm than good by giving you the answer to your homework assignment, but I feel for you so here it is. Please just look very carefully at the exact differences between what you posted in your question and what I show below. There's several mistakes you made, including bad syntax and a misunderstanding of how scope works, and I can't properly explain all the problems without typing several pages, so I hope you can learn from this example instead...
import java.util.*;
public class Final {
public static void main(String[] args) {
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
int[] shots = getRandomNumbers();
print(shots);
}
public static int[] getRandomNumbers(){
int [] shots = new int [10];
Random r = new Random();
for(int i = 0; i < 10; i++) {
shots[i] = r.nextInt(100);
}
return shots;
}
public static void print(int[] shots) {
for (int i=0; i<shots.length; i++) {
System.out.print(shots[i]);
if (i < shots.length-1) {
System.out.print(", ");
}
else {
System.out.println("");
}
}
}
}//END class
I need to run a method code for GCD. My java file is called "GCD.java" and the public class is called "GCD." Yet I keep getting the message "Class GCD does not have a main method" even though I have no red explanation point circles in any of my lines. I can run the code without the method code (i.e. public static void main(String[] args)), but I need to run the code with a method. Thanks.
==========================
import java.util.Scanner;
public class GCD
{
public static int getDivisor(int x, int y)
{
System.out.println("Greatest Common Divisor Finder");
System.out.println();
String choice = "y";
Scanner sc = new Scanner(System.in);
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Enter first number: ");
x = sc.nextInt();
System.out.print("Enter second number: ");
y = sc.nextInt();
int secondNumber = 0;
int firstNumber = 0;
int Greatestcommondivisionfinder = 0;
// x = first, y = second
if (x > y)
{
do
{
x -= y;
}
while (x > y);
do
{
y -= x;
}
while (y > 0);
System.out.println("Greatest Common Divisor: " + x);
}
else if (y > x)
{
do
{
y -= x;
}
while(y > x);
do
{
x -= y;
}
while (x > 0);
System.out.println("Greatest Common Divisor: " + y);
}
else
{
int subtract;
do
{
subtract = (int)y - (int)x;
}
while(y > x);
int gcd;
gcd = (int)x - subtract;
}
System.out.println();
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
return 0;
}
}
It's entirely valid for a class not to have a main method - or for it to have a main method which isn't declared as public static void main(String[] args).
However, in order to treat a class as the entry point for a Java application, it needs that method, with that signature (although the parameter name can vary).
So basically, you've got a class which is fine in itself, but you can't launch on its own. You could create a separate class, e.g.
public class GcdLauncher {
public static void main(String[] args) {
GCD.getDivisor(0, 0); // Parameters are ignored anyway...
}
}
Then after compilation you could run:
java GcdLauncher
Or you could add a public static void main(String[] args) method to your GCD class.
I would strongly advise you to change your getDivisor method not to have parameters though - you're not actually using them anyway...
Yes, as your Eclipse correctly says, you don't have main method in your GCD.java file. In-order run this class independently, you need to have main method. Otherwise you can only create Object of this class and call from other class.
If your class is to be used as a main program, it has to implement an
public static void main(String[] args))
Method from where you can call your GCD method.