I am pretty new to JAVA. I want to know how I can create a little program where the user can have the start and the end input (2 user inputs). And then count the in between numbers. Like this for example:
After some research I got this code but something is wrong, I really appreciate the help!
import javax.swing.*;
class Users{
public static void main(String[] args)
{
int a = userinput();
int b = userinput();
for( a = a <= b ; a = a + 1)
{
System.out.println(a);
}
}
public static int userinput()
{
String tekst = JOptionPane.showInputDialog(null, "enter a number", "Users",3);
int number = Integer.parseInt(tekst);
return number;
}
}
You had a little error in your for loop.
Plus I'd use a special variable only for counting/iterating, in order not to mess up the input:
import javax.swing.JOptionPane;
class Users {
public static void main(final String[] args) {
final int a = userinput();
final int b = userinput();
for (int counter = a; counter <= b; counter++) {
System.out.println(counter);
}
}
public static int userinput() {
final String tekst = JOptionPane.showInputDialog(null, "enter a number", "Users", 3);
final int number = Integer.parseInt(tekst);
return number;
}
}
Also, if you wanna increase a value, you can to
a++;
++a;
a+=1;
a=a+1;
which are more or less the same.
(This is not gui based solution, it displays in console)
First I think you should learn scanner in java. you need to import scanner
import java.util.Scanner;
Then you need to create a scanner object inside your main method.
Scanner keyboard = new Scanner(System.in);
You can take input with this code:
System.out.println("Enter first number");
int firstInput=keyboard.nextInt();
System.out.println("Enter second number");
int secondInput=keyboard.nextInt();
After you have inputs you can make a for loop to count between
for(int i=firstInput;i<=secondInput;i++){
System.out.print(i);
}
I hope this helps your problem.
Use scanner instead of joption if you are new. import this in top of the line.
import java.util.*;
Write below code in your function to take input
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter number- ");
int number= sc.nextInt();
import scanner class at top.
import java.util.*; //here is a code to create new user defined variable.
Scanner sc= new Scanner(System.in);
// Create a Scanner object
System.out.println("Enter first variable");
int firstVariable= sc.nextInt();
System.out.println(" First Variable is: " + firstVariable); // Output user input
int secondVariable= sc.nextInt();
System.out.println(" Second Variable is: " + secondVariable); // Output user input
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.