How to get an user input using scanner class and use it inside method to process, and obtain output?
Example : You get two numbers from the user and pass it to 4 methods to get its value after addition, subtraction, multiplication, division.
The scanner should be in main class and not inside every method.
Here is my code, it's in basic form. I want to get input from the user and process it inside the methods and get the result:
class Calc{
public static void main(String[] args){
add();
sub();
mul();
div();
{
void Add() {
int a=5,b=10;
sum=a+b;
System.out.println(sum);
}
void sub() {
int a=5,b=10;
sub=a=b;
System.out.println(sub);
}
void mul() {
int a=5,b=10;
mul=a*b;
System.out.println(mul);
}
void div() {
int a=5,b=10;
div=a/b;
System.out.println(div);
}
}
}
}
Simply use the array or nextInt() method to get the number of input and passed it to your method.
For e.g. If you are supposed two take two input at time
Scanner sc = new Scanner(System.in);
int[] integers = new int[2];
for(int i = 0; i < 2; i++)
{
integers[i] = sc.nextInt();
}
Now use the integers array to get the value from index and passed it to your method
You can get input by using new Scanner(System.in), as follows:
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
add(a,b);
sub(a,b);
multiply(a,b);
divide(a,b);
Related
I must read few Int Vector. I put it to ArrayList.
Methods to read have own class.
In main function i create object and start method readMy which is to be put in the list of values which are entered on one line separated by a space. The problem is that after the number of loops ends, it is not completed. how can I leave this loop except ctrl + d.
public class Wektory
{
List<Integer> wektor = new ArrayList<Integer>();
public Wektory(){}
public void readMy()
{
Scanner C=new Scanner(System.in);
while(C.hasNextInt())
wektor.add(C.nextInt());
}
}
I checked the contents of the list and it is correct
I don't know if i did understand your point but you can do something like this:
Scanner C=new Scanner(System.in);
boolean quit = false;
while (!quit){
System.out.println("please enter the values : \r");
if(C.hasNextInt()){
int value = C.nextInt();
C.nextLine();
wektor.add(value);
}
// to end you can do this or you can break directly :
if(wektor.size() >= 10){
System.out.println("the loop has been ended");
quit =true;
}
}
You can use a unique int value to exit the scanner e.g. -1
public class Wektory
{
List<Integer> wektor = new ArrayList<Integer>();
public Wektory(){}
public void readMy()
{
Scanner C=new Scanner(System.in);
while(C.hasNextInt()){
int val = C.nextInt();
if(val==-1){
break;
}
wektor.add(C.nextInt());
}
}
}
I'm having a hard time with my second method, The method declaration is:
public static void displayOutput(int loopCount)
The method is called from the main() and is passed the valid input value which determines repetition. The method displays the output pattern only and returns nothing. Every 3rd line displays a space and 3 asterisks
I know I'm not calling each method right in the main() and I know that displayOutput(int loopCout) is wrong.
Could someone explain this to me or use an example that would help write the program?
public static void main(String[] args) {
int repeat;
Scanner goGet = new Scanner(System.in);
repeat = getValidValue(goGet); //Uncompilable source code -Erroneous sym type
displayOutput(repeat);
}
public static int getValidValue() {
int input;
do {
Scanner getInfo = new Scanner(System.in);
System.out.print("Enter an integer Greater than zero: --> ");
input = getInfo.nextInt();
} while (input <= 0);
return input;
}
public static int displayOutput(int loopCount) {
int i;
for (i = 0; i < loopCount; i++) {
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon.*** ");
}
return loopCount;
}
You are passing a value to method getValidValue which doesn’t take any value.
Also displayOutput is returning loopcount but you are not catching it anywhere so after asterisk it is not displaying anything.
I created an array of three integers that I ask input to the user, then I return that array and instantiated the class, but I don't have access to the array items:
import java.util.Scanner;
public class Input {
public static int[] getInput() {
Scanner sc = new Scanner (System.in);
int choice[] = new int[3];
System.out.println("Type the options: ");
System.out.println("Plate: ");
choice[0] = sc.nextInt();
System.out.println("Dessert: ");
choice[1] = sc.nextInt();
System.out.println("Drink: ");
choice[2] = sc.nextInt();
return choice;
}
}
Main class:
public class Main
{
public static void main (String [] args) {
Menu menu = new Menu();
Input input = new Input();
menu.ShowMenu();
Input.getInput();
//I want to compare choice[0] here
if (input.getInput() == 1) {
//code block
}
Do I need to write a method to the three choices? I just want to pass the three user inputs to use in the Main class if's and else's.
Instead of Input.getInput(), write int[] arr=Input.getInput(). You have to store the result of the Method in a variable.
You can than access the Elements with arr[index], index starting with 0, for example a[0]
Save the return value in a variable.
int[] choices = Input.getInput();
if (choices[0] == 1) {
...
}
int[] inputs = Input.getInput();
if (inputs[0] == 1) { ... }
That is an array and is static... so you can save this declaration:
Input input = new Input();
and you must only do:
if (Input.getInput()[0] == 1) {
//code block
}
I just want to know how to call methods/functions in java. Can you please help me with this?
So here's my code.
import java.util.Scanner;
public class MyFirstProject {
public static void main(String[] args) {
hello();
}
static void hello(int a, int b) {
Scanner scan = new Scanner(System.in);
int total;
System.out.print("Enter first number: ");
a = scan.nextInt();
System.out.print("Enter second number: ");
b = scan.nextInt();
total = a + b;
System.out.println("The total is: " + total);
}
}
You make the method hello static for the class MyFirstProject so it has connotations -> Explanation.
But the problem here is that you are missing to pass parameters to the method:
int example_arg_one = 3;
int example_arg_two = 5;
MyFirstProject.hello(example_arg_one,example_arg_two);
2 clicks away, here's a pictured answer - http://www.wikihow.com/Call-a-Method-in-Java
In your code what you're actually missing is passing the required parameters - the values for a and b. The call should actually look like MyFirstProject.hello(2, 5)
Since your method hello(int a, int b) has a parameter of two integers, you need to give it the integers when calling it in order for it to work. But that also doesn't make sense since you have a Scanner which defines your integers in your method. Just remove the parameters of your method and your code should work.
public static void main(String[] args) {
hello();
}
static void hello() {
Scanner scan = new Scanner(System.in);
int total;
System.out.print("Enter first number: ");
int a = scan.nextInt();
System.out.print("Enter second number: ");
int b = scan.nextInt();
total = a + b;
System.out.println("The total is: " + total);
}
Regarding how to call methods, you're doing it right. Just do not neglect your parameter, if your method has one you have to give it one. If you do not know what a parameter is, it is the hello (int a, int b). Your method is expecting you to give it two integers, because that is how you defined your method, you defined it to take two integers. If you want to call it using the parameter, call it in your main and give it two integers, for example hello(1, 2)
Note: If you want to do that you have to remove the scan.nextInt() from your code.
You forgot to pass two parameters a and b into method hello.
public static void main(String[] args) {
int a = 1;
int b = 2;
hello(a,b);
}
Write the following methods:
13. A method named loadScores that will be passed the size of an array, prompt the user to enter the appropriate number of floating point grades, then return the loaded array.
I wrote the method, but the problem comes when I try to call it. Here's what I have:
public class ArrayHandout {
public static void main(String[] args) {
int size = loadScores(size);
double[] scoresArray = loadScores(size);
} // end main
public static double[] loadScores(int size) {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
} // end loadScores
} // end class
I have changed a few things in an attempt to correct some errors I was having when I wrote the original code, and unfortunately don't even remember what those changes were or if they fixed the problems since I can't get it to compile now. I do know that the problem I was having when I could get the original to compile was that it was only printing the first number in the array rather than printing the entire array. Like I said, I don't know if that problem has been corrected since now when I try to compile I receive the following error message:
1 error found:
File: C:\Users\HiTechRedneck\Desktop\Fall 2013\PlayingwithJava\ArrayHandout.java [line: 6]
Error: incompatible types
required: int
found: double[]
I know that size needs to be declared in main because previously I was getting the "cannot find variable size" error, but I think the fact that I'm trying to declare int size as loadScores(size) is throwing it off since the variable I'm declaring is also an argument in the method.
Any help would be greatly appreciated.
Your line int size = loadScores(size) is incorrect. loadScores has a return type of double[], so you need to assign that return value as such.
Just delete that one line and everything should work as expected.
int size = loadScores(size); is throwing an error because loadScores returns an array of type double.
Since the task just wants a code snippet you could probably give size an arbitrary value and pass that in. Or you could get rid of size in main and just pass a number in:
public static void main(String[] args) {
double[] scoresArray = loadScores(5);
}
Edit: Also worth noting that the print statement after the for loop will throw an ArrayIndexOutOfBoundsException since i is now greater than the length of the array. If you want to print the contents of the scoresArray you'll need another loop to traverse through each element.
Second edit: If you're prompting the user for a size you should run your prompt for that in the main method and then pass that to loadScores().
You don't need size at all before you call the function as you read it in the function
your declaration could be :
public static double[] loadScores()
and call
loadScores()
in main. Example:
public class ArrayHandout {
public static void main(String[] args) {
double[] scoresArray = loadScores();
//do whatever you want here or change declaration of
//the function to void and do not return anything
}
public static double[] loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
return scoresArray;
}
}
if you don't use the returned array it would be better to do it like this:
public class ArrayHandout {
public static void main(String[] args) {
loadScores();
}
public static void loadScores() {
Scanner input= new Scanner(System.in);
System.out.println("How many scores would you like to enter?");
int size = input.nextInt();
double[] scoresArray = new double[size];
int i;
for(i = 0; i < scoresArray.length; i++) {
System.out.println("Please enter a score:");
scoresArray[i] = input.nextDouble();
}// end for
System.out.println(scoresArray[i]);
}
}
(When a method doesn't return anything you have to specify it by using the void keyword in its signature)-You also need validation but I was only answering to the specific problem -without validation your program will still fail if incompatible values are given.