Using a single scanner input to assign two variables in Java - java

I'm trying to create a method to search an arraylist for a student number (sNumber) that the user inputs, and then with that same input get the indexOf so it can pull data from other arraylists. The problem I'm having is I can't figure out how to do this using a single input from the user. Right now for it to work they'd have to input the sNumber twice.
while (exit == 0){
System.out.println("Please enter the sNumber of the student you wish to find");
Boolean x = sNumber.contains(kb.nextInt());
int y = sNumber.indexOf(kb.nextInt());
if (x = true){
String a = name.get(y);
int c = sNumber.get(y);
String d = major.get(y);
Double e = gpa.get(y);
System.out.println(a);
System.out.println(c);
System.out.println(d);
System.out.println(e);
}
else if (x = false){
System.out.println("This student does not exist");

Assuming the two kb.nextInt() are returning the same value why don't you just assign it to variable first then use it in the program later.
Boolean x = sNumber.contains(kb.nextInt());
int y = sNumber.indexOf(kb.nextInt());
would turn into
int tmp = kb.nextInt();
Boolean x = sNumber.contains(tmp);
int y = sNumber.indexOf(tmp);

Related

Convert int to string in a loop

I want to ask how to convert an int value to string while runing in loop lets say i got an int value 1 at first running of loop then i got 2 and then 3 in the end i want a string with value "123"..
your answers would be very helpful.. THANKS
int sum = 57;
int b = 4;
String denada;
while(sum != 0)
{
int j = sum % b;
sum = sum / b
denada = (""+j);
}
how to convert an int value to string
String.valueOf function returns the string representation of an int value e.g. String x = String.valueOf(2) will store the "2" into x.
lets say i got an int value 1 at first running of loop then i got 2
and then 3 in the end i want a string with value "123"
Your approach is not correct. You need variables for:
Capturing the integer from the user e.g. n in the example given below.
Store the value of the appended result e.g. sum in the example given below.
Capturing the user's choice if he wants to continue e.g. reply in the example given below.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String reply = "Y";
String sum = "";
while (reply.toUpperCase().equals("Y")) {
System.out.print("Enter an integer: ");
int n = Integer.parseInt(scan.nextLine());
sum += n;
System.out.print("More numbers[Y/N]?: ");
reply = scan.nextLine();
}
System.out.println("Appnded numbers: " + sum);
}
}
A sample run
Enter an integer: 1
More numbers[Y/N]?: y
Enter an integer: 2
More numbers[Y/N]?: y
Enter an integer: 3
More numbers[Y/N]?: n
Appnded numbers: 123
The next thing you should try is to handle the exception which may be thrown when the user provides a non-integer input.

Line by line input evaluation with operators and how to store the changing value until user types "."

I'm trying to make a program that evaluates a mathematic equation that's written one character or value per line at a time. The user will enter alternating numbers and operators, line by line, terminating with a ‘.’. That means I'm not trying to evaluate from a single string (and assume input will always alternate between number and operator).
I don't know how to make it so that it keeps taking input until the user types ".'
I also am not sure how to keep the value continuously changing as the user types the formula and how to store that.
Sample input:
1
+
6
-
3
.
The solution to your equation is: 4
import java.util.Scanner;
class Evaluator {
static int add (int a, int b)
{
return a + b;
}
static int multiply (int a, int b)
{
return a * b;
}
static int divide (int a, int b)
{
return a / b;
}
static int subtract (int a, int b)
{
return a - b;
}
static int modulus (int a, int b)
{
return a % b;
}
public static void main(String [] args)
{
Scanner input = new Scanner (System.in);
int a,b,c;
System.out.println("Enter the equation:");
a = input.nextInt();
String c = input.next();
b = input.nextInt();
if (c.contains("+")) {
int result = add (a,b);
}
else if (c.contains("*")) {
int result = multiply (a,b);
}
else if (c.contains("/")) {
int result = divide (a,b);
}
else if (c.contains("-")) {
int result = subtract (a,b);
}
else if (c.contains("%")) {
int result = modulus (a,b);
}
else if (c.contains(".")) {
break;
}
System.out.print("The solution to your equation is: " + result);
}
}
Your code is very close, in that you use Scanner next() and nextInt() in the correct order (to match the input rules). Here a while(true) loop is added around the pair of inputs; either a user enter a '.' and the loop breaks, or the user enters an operator followed by the next number. The result is kept up to date by using it repeatedly in the various math operators.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int b, result;
System.out.println("Enter the equation:");
result = input.nextInt();
while (true) {
String c = input.next();
if (c.contains(".")) {
break;
}
b = input.nextInt();
if (c.contains("+")) {
result = add(result, b);
} else if (c.contains("*")) {
result = multiply(result, b);
} else if (c.contains("/")) {
result = divide(result, b);
} else if (c.contains("-")) {
result = subtract(result, b);
} else if (c.contains("%")) {
result = modulus(result, b);
}
}
input.close();
System.out.print("The solution to your equation is: " + result);
}
Here is a simple while loop you can use to get input from the user. I have a check if it's a digit or something else. You can use this skeleton to grab input from the user and exit when someone presses "."
Scanner input = new Scanner (System.in);
int a,b,currentTotal = 0;
String inputFromUser = "nothing";
while(!inputFromUser.equals("."))
{
inputFromUser = input.nextLine(); //grab line by line
if(inputFromUser.matches("\\d+")){
//parse the number and set it to a value like a...
System.out.println("You entered a number: " + inputFromUser);
}
else if(!inputFromUser.equals(".")){
//check if you have value and try to apply your number to your current total
System.out.println("You entered something other than a number: " + inputFromUser);
}
}
If the user enters a number, set a variable to that number, perhaps a
If the user enters something other than a number and not a period then check if the input is a valid operation with your provided logic and apply it like operatorMethod(a, currentTotal)

Using a while loop to show an error message if multiple inputs on the same line are not valid?

Currently I'm working on a simple algebraic formula calculator to get a little better at some Java basics, but I am running into an issue.
One of my methods is the Quadratic Formula. It asks the user to input A, B, and C on the same line and then the program performs the calculation. But when I make a while loop to check if the input is a double, I get an error when I put in an incorrect value(for example, 3 5 x).
Do I need to perform a loop for each individual variable, or is there a quicker way to check if all 3 variables in one input are acceptable?
public static void quadraticFormula() {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the values(in order) for A, B and C: ");
while(!sc.hasNextDouble()) {
System.out.println("Error! One or more of your inputs are not acceptable. Please try again: ");
sc.nextDouble();
}
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
int discriminant = (int) (Math.pow(b, 2) - 4 * a * c);
double rootPlus = (-1 * b + Math.sqrt(discriminant)) / (2 * a);
double rootMinus = (-1 * b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Your answers are as follows: ");
System.out.println("\tB + : " + rootPlus);
System.out.println("\tB - : " + rootMinus);
}
The code you posted tries to read 6 values, 3 in the loop and three after that.
I would read in the values as strings and then parse them inside a try catch block (one for each variable). In that way you can validate that the inputs represent doubles and that you can do the calculation.
try this. I used a boolean flag and parse for testing double.
Its calculations do not know if they are correct, however the question of the input is right.
import java.util.Scanner;
public class Teste {
public Teste() {
Scanner sc = new Scanner(System.in);
String[] input = null;
boolean flag = true;
double a = 0;
double b = 0;
double c = 0;
while (flag) {
System.out.print("Please enter the values(in order) for A, B and C: ");
String str = sc.nextLine();
input = str.split(" ");
System.out.println("You entered: " + str);
if (input.length == 3) {
try {
a = Double.parseDouble(input[0].trim());
b = Double.parseDouble(input[1].trim());
c = Double.parseDouble(input[2].trim());
flag = false;
} catch (NumberFormatException e) {
flag = true;
System.out.println("Input an integer");
}
} else {
flag = true;
System.out.print("Please enter the values(in order) for A, B and C: ");
}
}
sc.close();
int discriminant = (int) (Math.pow(b, 2) - 4 * a * c);
System.out.println(discriminant);
double rootPlus = (-1 * b + Math.sqrt(discriminant)) / (2 * a);
double rootMinus = (-1 * b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Your answers are as follows: ");
System.out.println("\tB + : " + rootPlus);
System.out.println("\tB - : " + rootMinus);
}
public static void main(String[] args) {
Teste app = new Teste();
}
}
I have a few thoughts on your issue. I think you can only iterate over a scanner once, so you want to grab the values you want when you get them. While getting the input, you can just check to make sure it's a double. If not, throw a controlled error in a try/catch and just prompt the user again.
You already know that exactly 3 doubles are needed, so creating a list to store your a, b, c might be a good option where index 0 = a, index 1 = b and index 2 = c. I created a method below that might help using this strategy:
public static void scannerPractice() {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the values(in order) for A, B and C:
");
//create list to store your a, b, c
ArrayList<Double> doubles = new ArrayList<Double>();
//iterate over doubles until it has 3 elements (a, b, c)
while (doubles.size() < 3) {
//You can use a try to make sure the user is entering doubles
try {
doubles.add(sc.nextDouble());
//found a mismatch, so print error message, enter method to try
//try again and break
} catch (InputMismatchException e) {
System.out.println("Not a double. Please try again: ");
scannerPractice();
break;
}
}
//list now has a, b, c
if (doubles.size() == 3) {
//iterate over the list to make sure you're getting what's
//expected
for (int i = 0; i < doubles.size(); i++) {
System.out.println(doubles.get(i));
}
//enter math logic here
}
//good practice to close scanner when through
sc.close();
}

Program to decide whether second number is a multiple of the first not working properly

This program should be returning True if the second number is a multiple of the first. False if it is not, and it should do it three times.
The output is just giving whatever answer is correct for the first one.
How can I get the return to include the variables f, and g?
Or if that is not the correct way to go about it what is? I need to have them all come from the same method, otherwise I'd just make more methods, but as it is I'm stumped.
Any help is greatly appreciated. Sorry for my noobiness.
import java.util.Scanner;
public class Numbers3 {
// starts execution of java application
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int firstnumber = 0; // initialize integer first number
int secondnumber = 0; // initialize integer second number
int third = 0;
int fourth = 0;
int fifth = 0;
int sixth = 0;
// First input field
System.out.print("Input first number ");
firstnumber = input.nextInt();
// Second input field
System.out.print("Input second number ");
secondnumber = input.nextInt();
// makes result equal the Boolean output of isMultiple method
Boolean result = isMultiple(firstnumber, secondnumber, third, fourth,
fifth, sixth);
System.out.println("" + result);
System.out.println();
System.out.print("input first number ");
third = input.nextInt();
System.out.print("input second number ");
fourth = input.nextInt();
System.out.println("" + result);
System.out.println();
System.out.print("input first number ");
fifth = input.nextInt();
System.out.print("input second number ");
sixth = input.nextInt();
System.out.println("" + result);
}
// creates method using the user input
public static Boolean isMultiple(int a, int b, int w, int x, int y, int z) {
Boolean e = null; // initialize boolean
Boolean f = null;
Boolean g = null;
if (a % b != 0) // what the function does if the result is not 0
e = false;
// what the function will do if the function does result in 0
if (a % b == 0)
e = true;
if (w % x != 0)
f = false;
if (w % x == 0)
f = true;
if (y % z != 0)
g = false;
if (y % z == 0)
g = true;
return e;
// returns e as the result of this method.
} // end program
} // end class
For every run, there's two inputs.
Objective: Check if the first input is a multiple of the second input using isMultiple().
To run it 3 (or any #) times, put the repeating code in a for loop.
# of times to repeat the loop is stored in the constant NUM_RUNS.
Code:
import java.util.Scanner;
public class Numbers3 {
private static final int NUM_RUNS = 3;
// starts execution of java application
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < NUM_RUNS; i++) {
// First input field
System.out.print("Input first number: ");
int firstNumber = input.nextInt();
// Second input field
System.out.print("Input second number: ");
int secondNumber = input.nextInt();
System.out.printf("%d is a multiple of %d: %s%n%n",
firstNumber, secondNumber,
isMultiple(firstNumber, secondNumber));
}
}
public static boolean isMultiple(int a, int b) {
return (a % b == 0);
}
} // end class
Example Input/Output:
Input first number: 8
Input second number: 2
8 is a multiple of 2: true
Input first number: 7
Input second number: 3
7 is a multiple of 3: false
Input first number: 18
Input second number: 6
18 is a multiple of 6: true
I'm not sure what's with f and g, but here's a program that asks for two numbers, three times, and prints true or false if the second is a multiple of the first:
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 3; i++) {
System.out.print("Enter first number : ");
int first = Integer.parseInt(reader.
System.out.print("Enter second number : ");
int second = Integer.parseInt(reader.readLine());
boolean secondMultipleOfFirst = second % first == 0;
System.out.println(secondMultipleOfFirst);
}
}
And I know what's wrong with your method, as well. You are calculating the values correctly, but every time you are returning e, which is the first result. So, the next two inputs give the first result.
Instead of setting up more methods, or a way to see which value to return, use a loop. That way, you take two values and see if n2 is a multiple of n1.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dump_me;
import java.util.Scanner;
public class Numbers3
{
// starts execution of java application
public static void main( String[] args)
{
Scanner input = new Scanner (System.in );
int firstnumber = 0; // initialize integer first number
int secondnumber = 0; // initialize integer second number
// makes result equal the Boolean output of isMultiple method
String loop = "N";
do{
// First input field
System.out.print("Input first number ");
firstnumber = input.nextInt();
// Second input field
System.out.print("Input second number ");
secondnumber = input.nextInt();
Boolean result = isMultiple(firstnumber, secondnumber);
System.out.println("" + result );
System.out.println();
System.out.println("Do you wan to continue? Press y to continue or n to exit" );
loop = input.next();
}while(loop.equalsIgnoreCase("y"));
}
// creates method using the user input
public static Boolean isMultiple( int a, int b)
{
if(a==0 || b==0)
{
return false;
}
else
{
if(b % a ==0)
{
return true;
}
else
{
return false;
}
}
// returns e as the result of this method.
} // end program
} // end class
User input have been put in the loop. This program will accept the user input and check the values.

Java - Issues parsing a string for a simple calculator program

I have code that takes input and then figures out what you are wanting to do with it
eg. You would type in "x (+,-,..etc) y" and it would calculate it for you.
Im currently using a Scanner and splitting it up such that
double x = input.nextDouble();
String z = input.next();
double y = input.nextDouble();
Now I have run into a problem. Say I want to do a factorial I would then input "x !" but the code is still wanting the last input.nextDouble();
How would I go about (using what I am doing, if possible) checking to see if all 3 have inputs and then selecting between the methods using an if statement or if only 2 have inputs.
Relative code
System.out.print("> ");
double x = input.nextInt();
String z = input.next();
double y = input.nextInt();
if (x == 0) {
running = false;
} else if (z.equalsIgnoreCase("+")) {
System.out.println(addition(x, y));
}
Instead of getting three different inputs, just input a single line of string, parse the string accordingly and type cast them to the necessary types. This way you can determine from the string is a factorial (1 variable) or any other operation on it is necessary.
Using scanner.
boolean binary = true;
Scanner input = new Scanner(System.in);
double x = input.nextInt();
String z = input.next();
//check if z is a unary operator ie.
if(z=='!')
binary = true;
if(binary)
double y = input.nextInt();
If you have two inputs, then your code will throw NoSuchElementException. To avoid that you should use input.hasNext().
double x = input.nextInt();
String z = input.next();
if (input.hasNext()) {
// input has y
y = input.nextInt();
// perform operation on two elements
} else {
// no y
// perform operation on one element
}
Add an extra if statement and ask for 'y' only if z = '+'.
System.out.print("> ");
double x = input.nextInt();
String z = input.next();
if (x == 0) {
running = false;
} else if(z.equalsIgnoreCase("!")){
factorial(x);
}
else if (z.equalsIgnoreCase("+")) {
double y = input.nextInt();
System.out.println(addition(x, y));
}
try this code
double y = 0.0;
if(!z.contains("!")){
y = sc.nextDouble();
}
you must get the input as a string so you must use String.indexof() and divide the main string in two string you must parse the first part like this:
int a=Integer.parse(someString);
and the second part of your string would show you what you must to do with that.

Categories

Resources