Could someone explain to me when I run this code, I don't get the Sysout statement until I enter my first keyboard input?
import java.util.Scanner;
public class test1{
static Scanner scan = new Scanner(System.in);
static int k = scan.nextInt();
public static void main(String[] args) {
setK();
System.out.println(" K is: " + k);
}
public static void setK(){
System.out.println("Please input K value");
k = scan.nextInt();
}
}
The static variables of your test1 class are initialized before your main method is executed. This happens when the class is initialized.
Therefore the
static int k = scan.nextInt();
statement is executed before your main method and waits for input. Only after the input is entered, main starts running and calls setK();, which prints "Please input K value".
I'm not sure this was intentional, since your setK() method seems to be the method that should read the input and assign it to k. Therefore, change your code to :
import java.util.Scanner;
public class test1{
static Scanner scan = new Scanner(System.in);
static int k;
public static void main(String[] args) {
setK();
System.out.println(" K is: " + k);
}
public static void setK(){
System.out.println("Please input K value");
k = scan.nextInt();
}
}
This line
static int k = scan.nextInt();
runs during class initialization. It blocks and waits for input of an integer.
This code runs before main because it is a static initialization. It must be complete before the first method of the class is called. At that point k has the first value you have entered. After that, main calls setK, prompting for another input.
You can fix this by removing initialization (i.e. the = scan.nextInt(); part) from declaration of k.
Maybe the behaviour you expect would be as follows:
package test;
import java.util.Scanner;
public class ScannerTest {
static Scanner scan = new Scanner(System.in);
static int k;
public static void main(String[] args) {
System.out.println("Please input K value");
k = scan.nextInt();
System.out.println(" K is: " + k);
}
}
BTW, you should stick to Java naming conventions.
Related
So I'm trying to make a program where the user inputs a number and the computer outputs the factorial. I have to use recursion and have 1 class and 1 client.
My class is:
public class Factorial
{
public static int Factorial(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*(Factorial(n-1));
}
}
}
My client is:
public class FactorialClient
{
public static void main()
{
Factorial n = new Factorial();
System.out.println(n.Factorial(4));
}
}
These both compile and work completely fine. However, I'm trying to figure out a way for the user to input the number instead of my inputting the number inside the client. Please help!
Try this.
public class FactorialClient
{
public static void main()
{
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int x = reader.nextInt();
Factorial n = new Factorial();
System.out.println(n.Factorial(x));
}
}
The Scanner class is great for reading user input.
The following should work:
public class FactorialClient {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextInt();
System.out.println(Factorial.Factorial(userInput));
}
}
Note that you don't have to declare a new Factorial object because the Factorial method has been declared static.
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;
}
public class Main{
public static void main(String args[]){
int i = nextInt();
}
public int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()){
scanner.nextLine();
Printer.println(Printer.PLEASE_NUMBER);
}
i=scanner.nextInt();
scanner.close();
return i;
}
}
The code above is how I'm trying to force a user to input a int value, but I get the nosuchelement exception, as the scanner.nextLine() reads a NULL.
In c++ the software waits for the user to input something. Is there anything I can do to force the program to stop, wait for the user to input something and then make the check?
EDIT:
So I'm having problems regardless, if I use scanner outside of Main class, it gives that error...
If you want the user to input and the scanner to pick up solely an integer value Scanner provides the method:
int i = scanner.nextInt();
Where i will store the next value entered into the console. It will throw an exception if i is not an integer.
Here is an example: Let's say I want the user to input a number and then I want to spit it back out to the user. Here would be my main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please print your number: ");
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
}
Now to check whether i is a integer you can use an if statement. However if you want the program to repeat until the user inputs an integer you can use a while loop or a do while loop where the loop's arguments would check if i is an integer.
Hope this is what you were looking for! By the way avoid naming your method nextInt() as the import java.util.Scanner; already has that method name. Don't forget imports as well!
You can do this:
public static void main(String[] args) {
System.out.println("" + nextInt());
}
public static int nextInt(){
int i=0;
boolean done=false;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!scanner.hasNextInt()){
System.out.println("Please enter a number:");
scanner.nextLine();
}
i = scanner.nextInt();
scanner.close();
return i;
}
This will cause the program to stop and wait for input each time the loop is executed. It will keep looping until it has an int in the scanner.
This works. There surely is a better solution.
EDIT As predicted. Check this,
import java.util.Scanner;
public class NewMain{
static boolean badNumber;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do{
System.out.print("Please print your number: ");
try{
int i = sc.nextInt();
System.out.println("Your Number is: " + i);
badNumber = false;
}
catch(Exception e){
System.out.println("Bad number");
sc.next();
badNumber = true;
}
}while(badNumber);
}
}
So I'm learning Java in class and I'm really loving it so far but its really hard to understand sometimes. Right now I'm trying to understand how methods work. My question is why my code is not working. I am trying to read in an integer from user input then square it.
Here is my code:
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
square(number);
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Let's say I input 5 on the console, the program immediately terminates and I cannot figure out why.
As mentioned by others, you don't print the value and the console will close as soon as the program ends. So you could try something like this
public class ScannerTest {
public static void main(String []args){
while(true){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number (-1 to stop)");
int number = input.nextInt();
if(number == -1){
break;
}
int output = square(number);
System.out.println(output);
}
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
This will print the result and loop ask for new input as long as you don't stop the program.
In Java, when main method comes to end and if there aren't any non-deamon threads running, the JVM ends. Your program came to an end without printing out the result of the square() call.
/*here is your solution :*/
import java.util.*;
import java.lang.*;
import java.io.*;
/*in java everything has to be in a class */
class SquareNumber
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
System.out.println(square(number));
/*something to print the squared number*/
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Your program is terminated because there is no other statement after square(number); statement. So your program executes square(...) method and after then it found end of main function so the program is terminated. To see some output you must print result of square(...) method.
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
int result=square(number);//executing square(...) method and store the returned value of square method to result variable
System.out.println("Square of "+number+" is : "+ result);//printing result
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
import java.util.Scanner;
public class CHP4Ex
{
Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("enter a n: ");
int n = scan.nextInt();
int i=10;
while (i<n)
{
System.out.println(i);
i = i + 10;
}
}
}
Why am I getting this error? I'm basically writing a while loop that prints all positive numbers that are divisible by 10 and less than n. For example, if n is 100, enter 10 ... 90.
Put the Scanner class object inside the main function. Basically the problem is that your code violates the static feature. You cannot use non-static members inside a static function, main being static in your case. So it should be :
import java.util.Scanner;
public class CHP4Ex
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a n: ");
int n = scan.nextInt();
int i=10;
while (i<n)
{
System.out.println(i);
i = i + 10;
}
}
}
You can't refer to non static variable in static context, so change
Scanner scan = new Scanner(System.in);
to
private static Scanner scan = new Scanner(System.in); It should work