Printing integers between 2 given integers [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I'm trying to create a class with a method that prints all integers between any two given integers. This is what I've got now-
public class IntList {
public static void main(String[] args) {
int start = Integer.parseInt(args[0]);
int stop = Integer.parseInt(args[1]);
for (int i = start + 1; i < stop; i++) {
System.out.print(i);
}
}
}
This won't compile, I get 2 errors saying "reached end of file while parsing", once each for lines 4 and 5.

Wrong main() method declaration. You have to pass an array as the only parameter for this function.
Then either declare your start and stop variables as local, and do the job inside the main method itself, or create a new function you call from the main() method.
No more explanation needed, this is Java basics. You should read a Java lesson.

There are 2 problem with this code
Main method doesn't have proper signature
make main like
public static void main(String ar[]){
}
and create another static method to accept two int variable
duplicate local variable declaration
remove
int i;
You already declare and initialize as a part of for loop
It will give you duplicate local variable error

Your main method declaration is incorrect. The argument list in a Java application's main method is required to be a String array. Read the start and stop values from the first 2 values of the String array after removing the duplicate declaration of the variable i:
public static void main(String[] args) {
int start = Integer.parseInt(args[0]);
int stop = Integer.parseInt(args[1]);
for (int i = start + 1; i < stop; i++) {
System.out.print(i);
}
}
Don't forget to pass in the start & stop values to the application
java IntList 1 10

You need public static void main(String[]) in your class in order it to be executed.
import java.util.Random;
public class IntList {
public static void main(int start, int stop){
for (int i = start + 1; i < stop; i++) {
System.out.print(i);
}
}
public static void main(String args[]){
main(random.nextInt(20),random.nextInt(100));
}
}

Related

What does public static void mean? What is a class? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I just accepted that all my programs I made have to start with this. Then I was looking at a example #2 here regarding generation of a random number.
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
I noticed that this had a public static void and a private static void. Why not just combine the code into one thing under public static void? More importantly, what do these mean? I did research and saw the word "class" pop up often. What is a class? I hope my question meets the guidelines, this is my first time posting here. Thanks.
I will assume you asked here because you wanted a concise answer that gives you some intuition, rather than a deep dive into OOP which you can pull from the tutorial.
A class is a template from which objects are built. However, until you understand OOP, the class is just a necessary wrapper around the imperative code you are writing because Java requires all code to live inside a class.
public means the method is publicly accessible. Methods which are defined in classes other than this one can access it. private has the opposite meaning.
static means that this is a class-level function that is not tied to any particular instance of the class.
void means the method returns nothing.
You can certainly put all the code under a single method, but that carries at least the following problems.
Code is harder to read because the intent of the code is hidden by the details of the implementation.
Code is harder to reuse because you have to copy and paste whenever you need the same functionality in multiple places.
The following is not fully correct, it is very simplified:
Mostly one class equals one file. Even so they can access each other (if in the same project/folder) Here are 3 example classes:
Class withe the main method:
package ooexample;
public class OOExample {
public static void main(String[] args) {
int min = 2;
int max = 101;
// use of static method
int randomNumberA = MyMath.generateRandomNumber(min, max);
// use of non static method
RandomNumberGenerator generator = new RandomNumberGenerator();
int randomNumberB = generator.randomNumber(min, max);
/**
* does not work, method is private, can not be accessed from an outise class
* only RandomNumberGenerator can access it
*/
// generator.printSomeNumber(123);
}
}
Class with a static method. The method can be access by writing classname.nameOfStaticMethod(...) see main method.
package ooexample;
public class MyMath {
public static int generateRandomNumber(int min, int max) {
return min + (int) (Math.random() * ((max - min) + 1));
}
}
Class without static method. You have to create the class in the main method, using the new operator and assign the created class to a variable. Then you can use the variable to access PUBLIC methods of that class. You can not access private methods anywhere else but inside of the class itself. See main method.
package ooexample;
public class RandomNumberGenerator {
public RandomNumberGenerator() {
}
public int randomNumber(int min, int max) {
int randomNumber = min + (int) (Math.random() * ((max - min) + 1));
printSomeNumber(randomNumber);
return randomNumber;
}
private void printSomeNumber(int number) {
System.out.println(number);
}
}

When the use sort an array, fix and write private static void sort

My Main Code is :
public class Arrays {
public static void main(String[] args) {
//////////////// Sorting Arrays
String [] castNames = new String [6];
castNames[0] = "Zareyee Merila";
castNames[1] = "Hosseini Shahab";
castNames[2] = "Bayat Sareh";
castNames[3] = "Peyman Moadi";
castNames[4] = "Hatami Leila";
castNames[5] = "Farhadi Sarina";
Arrays.sort(castNames);
for (int number = 0 ; number < 6 ; number++) {
System.out.println(number + " : " + castNames[number]);
}
}
}
How can I fix this line of code:
Arrays.sort(castNames);
Without having to write this one:
private static void sort(String[] castNames) {
// TODO Auto-generated method stub
}
Okay, this question is a bit vague, but I expect you're just running into an issue with name collision.
You've named your class Arrays. This class has no static method called sort. There is, however, a utility in Java called java.util.Arrays which does implement a static sort method.
Your code is not calling the Java utility class, unless there's an import statement you haven't included.
Try changing the line to this: java.util.Arrays.sort(castNames);
Otherwise, you might consider renaming your Arrays class to something else.

Cannot find Symbol and function cannot be applied : Java [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
class Demo2
{
int i=1,j=2;
void fun1()
{
i=i+1;
j=j+1;
}
public static void main(String[] args)
{
Demo2 d1=new Demo2();
d1.fun1();
d1.fun1();
d1.fun1();
System.out.println("Hello World!");
}
}
symbol cannot find and func cant be applied errors are showing Please help me i am a basic learner....
There are several errors in the code. I've commented and suggested some working code.
class Demo2
{
void fun1()
{
i=i+1; //i has not been initialized
j=j+1; //j has not been initialized
}
public static void main(String[] args)
{
Demo2 d1=new Demo2();
d1.fun1(1);//"fun1" does not accept a parameter.
d1.fun1();
d1.fun1();
System.out.println("Hello World!");
}
}
Here is a working Demo2 class that may help you along:
class Demo2
{
int i = 0;
int j = 0;
public void fun1(int param)
{
i=i+param;
j=j+param;
}
public static void main(String[] args)
{
Demo2 d = new Demo2();
d.fun1(1);//adds 1 to both i and j
d.fun1(2);//adds 2 to both i and j
System.out.println("i is equal to " + i);
System.out.println("j is equal to " + j);
}
}
You Does not declare i and j and doesnot defined a method fun1 with one argument
It's very important to understand why your code does not compile, or you will not be able to do anything else even if it gets fixed.
For starters, declare i and j by putting them right under your class declaration
class Demo2 {
int i = 0;
int j = 0;
Now look at where you defined void fun1(). You don't allow it to accept any parameters. So d1.fun1(); is allowed but d1.fun1(1); is not. You did not define a function named fun1 that accepts an int as a parameter. You would have to define it like so:
void fun1(int input) {
// Whatever you wanted this function to do
}

non-static method move(int,int) cannot be referenced from a static context [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 9 years ago.
When i try to use the move i.e. Slide.move(1,0) i get the error: non-static method move(int,int) cannot be referenced from a static context
This is my code at the moment, which i have no idea whats wrong.
public void move(int row, int col) {
char [][] temp= new char [cells.length][];
for (int i= 0; i< cells.length; i++) {
int destRow = (i+row)%cells.length;
temp[destRow] = new char [cells[i].length];
for (int j= 0; j < cells[i].length; j++)
temp[destRow][(j+col)%cells[i].length] = cells[i][j];
}
cells= temp;
}
}
The error means exactly what it says.
Your move method is not static. It requires an instance of an object to be called, e.g.:
Slide s = new Slide();
s.move(...);
You are calling it, as it says, from a static context, i.e. a place with no this, perhaps another static method or directly via Slide.move(...). You will need to not do that.
These fail:
Slide.move(...); // error: move requires an instance
// and
class Slide {
void move (...) {
...
}
static void method () {
move(...); // error: method is static, there is no instance
}
}
These do not fail:
Slide s = new Slide();
s.move(...);
// or
class Slide {
void move (...) {
...
}
void method () {
move(...);
}
}
// or
class Slide {
static void move (...) {
...
}
static void method () {
move(...);
}
}
So either call it from a non-static context, or make it a static method.
As for recommending somewhere to read more about these things (which you asked in a comment), try the official Java tutorial at http://docs.oracle.com/javase/tutorial/ (take a look at the "Learning the Java Language" trail (in particular: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html).
As for your output problems, since that's a separate question, you'd want to post a separate question for it.
Well that is because you defined the move method as a non-static method by saying public void to make it static you need to write public static void instead.
Also be aware that variable names are case sensitive, if you write Slide.move() you clearly call upon your Slide class because your variable was named slide.

Variable not passing into anther class Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
got a strange one, i have a variable t i use it in one class, it changes, (e.g. 1 becomes 5) and then i call it from another class to use in that class, problem is t is always 0 when it is passed, what am i doing wrong
here is t in the class where it is edited
public int t = 1; //defualt value for amount of seconds in the future the job should wait untill sent
public int getT() {
return (t);
}
public void setT(int t) {
this.t = t;
}
and this is the class that i am using that calls t from the above class to use:
public class DealyTillPrint {
public int t;
public String CompletefileName;
private String printerindx;
private static int s;
private static int x;
public static int SecondsTillRelase;
public void countDown() {
System.out.println("Countdown called");
s = 1; // interval
t = (t * 60); // number of seconds
System.out.println("t is : " + t);
while (t > 0) {
System.out.println("Printing in : " + t);
try {
Thread.sleep(s * 1000);
} catch (Exception e) {
}
t--;
}
and here is where i set t using a spinner
<p:spinner min="1" max="1000" value="#{printerSettings.t}" size ="1">
<p:ajax update="NewTime"/>
</p:spinner>
How can i call t where the value is passed that is not zero
In DealyTillPrint you declare public int t; That t is different than the t you declare in the first code sample. Since you give it no value, it's default value of 0 is assigned. You are doing nothing to share t in the first sample with t in the second sample.
Change t = (t * 60); // number of seconds to t = (printerSettings.getT() * 60);
You need to get the printerSettings object from web page into your DealyTillPrint object. I can't tell you how to do that looking at the code you've submitted.

Categories

Resources