2 user inputs with condition and use in another method - java

I'm doing a school project which asks me to do the following in separate methods:
start a main method and present the program
ask for user to input 2 numbers (conditions a>b and both positive & if it's wrong to ask 3 times or finish program by letting user it's over)
if conditions are ok, it should print first 2 consecutive number starting from a number, and last 2 consecutive numbers from b number.
I am dealing with several problems but biggest of them is that I can't use global variables so I should pass the numbers from a method to the other.
How can I do that?
The code I tried is
import java.util.Scanner; //Importar scanner
public class Eac4_001 {
Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Eac4_001 programa = new Eac4_001();
programa.inicio();
}
public void inicio() {
presentarPrograma();
pedirNumeros();
mostrarResultado();
}
public void presentarPrograma() {
System.out.println("El programa pedirá dos números positivos.\n"
+ "El primero tiene que ser más pequeño que el segundo.\n"
+ "Luego enseñará los primeros y ultimos dos númberos del"
+ "rango conseguido.\n");
}
public void pedirNumeros() {
int intentos = 3;
boolean ok = false;
int a = 0, b = -1;
while (a > b && !ok) {
System.out.print("Introduce un primer número: ");
a = scanner.nextInt();
System.out.print("Introduce un segundo número: ");
b = scanner.nextInt();
intentos = intentos - 1;
if (intentos < 0) {
ok = false;
}
System.out.println("Error, vuelve a introducir los números!");
}
}
public void mostrarResultado() {
}
}

I have made a few changes in your code.
import java.util.Scanner; //Importar scanner
public class Eac4_001 {
Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Eac4_001 programa = new Eac4_001();
programa.inicio();
}
public void inicio() {
presentarPrograma();
pedirNumeros();
}
public void presentarPrograma() {
System.out.println("El programa pedirá dos números positivos.\n"
+ "El primero tiene que ser más pequeño que el segundo.\n"
+ "Luego enseñará los primeros y ultimos dos númberos del"
+ "rango conseguido.\n");
}
public void pedirNumeros() {
int retry = 0;
int input1, input2;
boolean ok = false;
do {
System.out.print("Introduce un primer número: ");
input1 = scanner.nextInt();
System.out.print("Introduce un segundo número: ");
input2 = scanner.nextInt();
if (input1 > 0 && input2 > 0) {
ok = true;
//call your method from here.
mostrarResultado(input1, input2);
} else {
System.out.print("Invalid Input. Try again.");
if (retry < 3) {
retry++;
} else {
break;
}
}
} while (!ok);
}
public void mostrarResultado(int input1, int input2) {
//Do whatever you want to do, here with these variables
}
}

To send numbers from one method to the other, you can pass them as arguments in to another function.
Example
public void method1(int a, int b){
//code
}
Above method receives two integer values as arguments.
Link to learn about basics of methods in JAVA
Another way to pass numbers from one method to another is by returning the number from the method and then calling that method from another method in which you want to pass the number.
If you only want to pass one number to another method, you can simply return it.
Example
public int method2(){
int a = 20;
return a;
}
or if you want to pass more than one numbers, you can store them in an array and then return that array
Example
public int[] method3( )
{
int[] x;
x = new int[3]; // Create an array of 3 elements
x[0] = 2;
x[1] = 3;
x[2] = 4;
return( x );
}

In Java, a method can only ever return one value. If Java didn't have this restriction, then you could write:
greeting();
int (a, b) = readNumbers();
output(a, b);
But since the second line is not valid Java, you have to do something else. The following comes very close:
greeting();
int[] numbers = readNumbers();
output(numbers[0], numbers[1]);
At the end of the readNumbers method, you can write:
return new int[] { first, second };
Note that the array is only used for the return value of the second method. In particular, it is not passed further to the third method. Doing that would be unnecessary because Java allows multiple parameters.

import java.util.Arrays;
import java.util.Scanner;
public class Test {
public Test() {
}
public static void main(String [] args){
int [] myNumbers = new int[2];
present();
input(myNumbers);
presentResult(myNumbers);
}
public static void present(){
System.out.println("This is my presentation");
}
public static void input(int [] n){
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 2;i++){
n[i] = scan.nextInt();
while(n[i] < 0){
System.out.println("Your number has to be higher then 0");
n[i] = scan.nextInt();
}
if(n[1] < n[0] && i == 1){
System.out.println("The 2:nd number needs to be greater the the first one");
n[i] = scan.nextInt();
}
}
}
public static void presentResult(int [] n){
Arrays.sort(n);
System.out.println(Arrays.toString(n));
}
}
So this works.

Related

Printing an Array as a String with 10 elements per line

// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
char userChoice;
int newVal, index;
IntegerList intList = null;
printMenu();
do {
System.out.print("Please enter a command or type? ");
input = scan.nextLine();
if (input.length() != 0)
userChoice = input.charAt(0);
else
userChoice = ' ';
switch (userChoice) {
case 'a':
System.out.print("How big should the list be? ");
intList = new IntegerList(scan.nextInt());
scan.nextLine();
System.out.print("What is range of the values for each random draw? ");
intList.randomize(scan.nextInt());
scan.nextLine();
break;
case 'b':
System.out.println(intList.toStrng());
break;
The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.
// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {
private int arrSize;
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
public void randomize (int num) {
for(int i = 0;i<IntArray.length;i++) {
IntArray[i] =(int) (Math.random()*(num+1));
}
}
public void addElement(int newVal, int index) {
for(int i = index;i<IntArray.length;i++) {
int temp = IntArray[i];
IntArray[i]=newVal;
IntArray[i+1]=temp;
if(i == IntArray.length){
increaseSize(IntArray);
}
}
}
private static void increaseSize(int[] x) {
int[] temp = new int[2*x.length];
for(int i = 0; i<x.length;i++) {
temp[i]=x[i];
}
x = temp;
}
public void removeFirst(int nextInt) {
// TODO Auto-generated method stub
}
public String range() {
// TODO Auto-generated method stub
return null;
}
public String toStrng() {
String arrayOut = " ";
for(int i = 0; i<IntArray.length; i++ ) {
if(i%10 == 0 ) {
arrayOut+="\n";
}
arrayOut += IntArray[i] + " " ;
}
return arrayOut;
}
}
I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?
Look at how you are creating your array of integers through your current constructor...
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
When you call
intList = new IntegerList(scan.nextInt());
in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following
private int[] IntArray = null;
public IntegerList(int size) {
arrSize = size;
IntArray = new int[arrSize];
}
Everything seems to work because the size of your array was always 0 and your methods just return.
You did not initialize your arrSize
You can modify your constructor to initialize arrSize
public IntegerList(int size) {
arrSize = size;
}
Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length

Subroutine doesn't work

First time writing something here.
Why does my Subroutine not work?
I am trying to open the subroutine in the main function to get a boolean.
import java.util.Scanner;
public class Aufgabe1 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int eingabe = 0;
int zahl = 0;
boolean primzahl = false;
eingabe = scan.nextInt();//Input 1
if (eingabe == 1) {
zahl = scan.nextInt(); //Input 2
unterprogramm1(zahl);
}
public static boolean unterprogramm1(boolean primzahl) {
for (int i = 0; i < zahl; i++) {
if (zahl % i == 0) {
primzahl = true;
}
}
return primzahl;
}
You should write boolean primzahl in the parameter list, instead of just primzahl and move the method outside of the main function.

Java int error cant be int[]

Hey i get the following error int cant be int[] i dont understand it :I
Error is on
int[] cijferStudent = new int [7]; and in the while loop. If someone can help me i will appreciate it.
Thanks you for your help :)
package oefenopdracht6a;
import java.util.Scanner;
/**
*
* #author eazyman
*/
public class Oefenopdracht6a {
public static Scanner input = new Scanner(System.in);
public static int aantalCijfers = 0;
public static void main(String[] args) {
aantalCijfersGeroepen();
}
public static void aantalCijfersGeroepen() {
System.out.println("Hoeveel cijfers wilt u invoeren?");
aantalCijfers = input.nextInt();
for (int i = 0; i >= aantalCijfers;) {
System.out.println("Aantal cijfers moet groter zijn dan 0!");
aantalCijfersGeroepen();
}
int i = 0;
int[] cijferStudent = new int[7];
while (i < aantalCijfers) {
System.out.println("Cijfer student " + i);
cijferStudent = input.nextInt();
i++;
}
System.out.println(cijferStudent);
}
}
cijferStudent = input.nextInt();
should be changed to
cijferStudent[i] = input.nextInt();
The error is because input.nextInt() will return an int, but cijferStudent is an array of int, so you cannot assign an intto int[]. However, you can assign an int to a particular location inside the array (which in this case I am guessing would be the ith location).
Besides the missing index, for every negative value the users enters
aantalCijfersGeroepen will be called, and coming back on a positive number hence N times the array asked to input. So split asking and handling.
public static void main(String[] args) {
aantalCijfersGeroepen();
uitgaveAantalCijfers();
}
public static void aantalCijfersGeroepen() {
System.out.println("Hoeveel cijfers wilt u invoeren?");
aantalCijfers = input.nextInt();
while (aantalCijfers <= 0) {
System.out.println("Aantal cijfers moet groter zijn dan 0!");
aantalCijfersGeroepen();
}
}
public static void uitgaveAantalCijfers() {
int[] cijferStudent = new int[7];
for (int i = 0; i < aantalCijfers; ++i) {
System.out.println("Cijfer student " + i);
cijferStudent[i] = input.nextInt();
//System.out.println(" " + cijferStudent[i]);
}
System.out.println(Arrays.toString(cijferStudent));
}
Also the printing of an array must either be done in a loop too,
or use the handy function Arrays.toString.

how can i use if else if condtion with a loop in searching sorting in JAVA

How to use if else condition in searching (only using one loop and if else if condition) if array is already given e.g {12,13,14,15,16}
if user input 13 so it show it found and if user input 20 it shows not found.
My try :-
import java.util.Scanner;
/** * * #author Waseem */
public class Sear {
public static void main(String[] args) {
int index[] = {12, 13, 14, 15, 16};
Scanner a = new Scanner(System.in);
System.out.println("enter the number");
b = a.next();
for (int i = 0; i < index.length; i++) {
if (b == index[i]) {
System.out.println("found");
break;
} else
System.out.println(index[i]);
}
}
}
The problem you have in your code is that you do not have declared what a type of next is.
When you call
Scanner a = new Scanner(System.in);
System.out.println("enter the number");
b = a.next();
Method Scanner#next() by documentation result with a String type.
When you call b == index[i], you try to compare the references with value. That is not allowed operation and you will get a compile error.
To read a integer from Scanner use method nextInt(), then your program should run.
Regarding the algorithm, whenever you used a brake to control logic of your program should be a hint that this part should be moved to separate method.
Your problem can be divided in two like:
Find the number in array
Display message according to result in step one.
First we will have to write a method that will search an int in arrays of ints.
static int indexOf(int value, int[] values) {
for(int i = 0; i < value.length; i++)
if(value == values[i]) return i;
return -1;
}
The logic is simple, if a value is found then result with it index if not then result -1.
Now we can apply this method in the logic of our program.
public static void main(String[] args) {
int index[] = {12, 13, 14, 15, 16};
Scanner inputReader = new Scanner(System.in);
System.out.println("Enter the a integer:");
int value = inputReader.nextInt();
int position = indexOf(value, index);
if(position > 0) {
System.out.println("found");
} else {
System.out.println("not found");
}
}
Your method has correct logic implemented!I am unsure why are you printing the array values if the user-entered element doesn't match array element...There is no need! Also,to print NOT FOUND,you need to have a variable set for that purpose,say flag variable of type boolean in my code!
Also,what you're missing is end-braces to close the loop,main() and the class. We always have a corresponding closing brace for each respective opening brace!
try this :-
import java.util.Scanner;
/**
* #author Waseem
*/
public class Sear {
public static void main(String[] args) {
int index[] = {12, 13, 14, 15, 16};
boolean flag = false;
Scanner a = new Scanner(System.in);
System.out.println("enter the number");
int b = a.nextInt();
for (int i : index) {
if (flag = b == i) {
break;
} else {
System.out.println(i); // No need for this,but,even then this is fine!
}
} // to close for-loop
if (flag) {
System.out.println("Number Found");
} else {
System.out.println("Number not Found!!!");
}
} // to close main() method
} /// to close class Sear
import java.util.Scanner;
/**
* #author Davide
*/
public class test {
public static void main(String[] args) {
int index[] = {12, 13, 14, 15, 16};
Scanner a = new Scanner(System.in);
System.out.println("enter the number");
int b = a.nextInt();
// one if and else
if (find(index, 0, b)) {
System.out.println("Number Found");
} else {
System.out.println("Number not Found!!!");
}
}
// one loop
public static boolean find(int[] array, int index, int value) {
return index < array.length && (array[index] == value || find(array, ++index, value));
}
}
You got one for-each loop and one if statement
public String findInArray(int[] arrValues, int userInput){
for(int element : arrValues) {
if(element == userInput) {
return "it found";
}
}
return "not found";
}
import java.util.Scanner;
public class Ifelse {
public static void main(String[] args) {
int[] a={12,13,14,15,16};
int b;
for(int i=1;i<=a.length;i++)
{
Scanner input = new Scanner(System.in);
System.out.println("Input Number");
b = input.nextInt();
if (b <= a.length) {
System.out.println("Number Found");
break;
}
else {
System.out.println("Number Not Found");
}
}
}
}

How do I get user input into two separate arrays?

Hi I am having trouble with Scanner to get user input two separate ArrayList. When I run this code I get an IndexOutOfBounds exception after entering the two arrays.
The code adds two binary numbers together using logic of a ripple adder. An example of intended user input would be
Enter A array: 1 0 1 0
Enter B Array: 0 0 0 1
producing: 1 0 1 1
The code works when arrays are hard coded, how can I get the user to enter the arrays?
Code is shown below
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner inputA = new Scanner(System.in);
ArrayList<Integer> aList = new ArrayList<Integer>();
ArrayList<Integer> bList = new ArrayList<Integer>();
int c = 0;
System.out.println("Enter A array");
aList.add(inputA.nextInt());
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
bList.add(inputB.nextInt());
Adder bit1 = new Adder(parseInput(aList.get(3)), parseInput(bList.get(3)), parseInput(c));
Adder bit2 = new Adder(parseInput(aList.get(2)), parseInput(bList.get(2)), bit1.getCout());
Adder bit3 = new Adder(parseInput(aList.get(1)), parseInput(bList.get(1)), bit2.getCout());
Adder bit4 = new Adder(parseInput(aList.get(0)), parseInput(bList.get(0)), bit3.getCout());
if (bit4.getCout() == false) {
System.out.println(bit4.toString() + " " + bit3.toString() + " " + bit2.toString() + " " + bit1.toString());
} else {
System.out.println("overflow!");
}
}
public static boolean parseInput(int i) {
if (i == 1) {
return true;
} else {
return false;
}
}
}
Code for Adder class:
public class Adder {
private boolean a, b, cin, cout, s;
/**
* Full Adder contructor
*/
public Adder(boolean a, boolean b, boolean cin) {
this.a = a;
this.b = b;
this.cin = cin;
s = nand(nand(a, b), cin); //sum bit
cout = or(and(nand(a, b), cin), and(a, b)); // - carry bit
}
/** Half adder constructor */
// public Adder (bloolean a, boolean b) {
//
// this.a = a;
// this.b = b;
//
// s =
//}
/**
* NAND gate
*/
public boolean nand(boolean a, boolean b) {
return a ^ b;
}
/**
* AND gate
*/
public boolean and(boolean a, boolean b) {
return a && b;
}
/**
* OR gate
*/
public boolean or(boolean a, boolean b) {
return a || b;
}
public boolean getCout() {
return cout;
}
public String toString() {
if (s == true) {
return "1";
} else {
return "0";
}
}
public String toStringCout() {
if (cout == true) {
return "1";
} else {
return "0";
}
}
}
Your entire AdderApp class can be simplified and improved to accept any bit length by accepting the input in a slightly different way and then using a for loop to add each bit. The parseInput function can be replaced with a simple boolean comparison:
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter A array");
char[] aIn = input.nextLine().replace(" ", "").toCharArray();
System.out.println("Enter B array");
char[] bIn = input.nextLine().replace(" ", "").toCharArray();
StringBuilder result = new StringBuilder();
Adder bit = new Adder(false, false, false);
for (int i = aIn.length - 1; i >= 0; --i) {
bit = new Adder((aIn[i] == '1'), (bIn[i] == '1'), bit.getCout());
result.append(bit + " ");
}
System.out.println(bit.getCout() ? "overflow!" : result.reverse());
}
}
Scanner.nextInt gets the next integer in the input, and then stops. Each of your lists only contains 1 element.
Use something along these lines instead:
String[] input = inputA.nextLine().split(" ");
for (String s : input)
{
try { aList.add(Integer.parseInt(s)); }
catch(NumberFormatException nfe) { /* handle exception as desired */ }
}
Alternatively, you should be able to use something like:
while (inputA.hasNextInt())
{
aList.add(inputA.nextInt());
}
You should be having a for loop to have an input into your ArrayList.
System.out.println("Enter A array");
for (int i = 0; i < 4; i++) {
aList.add(inputA.nextInt());
}
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
for (int i = 0; i < 4; i++) {
bList.add(inputB.nextInt());
}
The user should input 4 numbers, your one just allow the user to enter 1 number:
int count = 0;
Scanner inputA = new Scanner(System.in);
System.out.println("Enter A array");
while(count < 4){
count++;
aList.add(inputA.nextInt());
}
count = 0;
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
while(count < 4){
count++;
bList.add(inputB.nextInt());
}
If you want to use hasNextInt():
while(inputA.hasNextInt()){
count ++;
aList.add(inputA.nextInt());
if(count == 4){
count = 0;
break;
}
}

Categories

Resources