//to display second smallest number out of three
import java.util.*;
public class Prog
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);
int a,b,c,d,e;
System.out.println("Enter three numbers");
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
d = Math.min(a, b);
e = Math.max(d,c);
System.out.println(+e);
}
}
I have made this code but I want that when the user inputs the numbers they are unequal, how can I do so with this program?
This is according to your question and comments in the question that you will have only 3 inputs and you want to find 2nd smallest and you have to use min and max only.
If it is not the case update the question for the correct answer to your intended question.
int d=a+b+c;
int e=Math.max(a,Math.max(b,c));
int f=Math.min(a,Math.min(b,c));
System.out.println(d-(e+f));
What you have is close, but in order to ensure you get 3 unique numbers and that you accurately return the middle number, I'd suggest using something like the following.
public static void main(String[] args) {
List<Integer> enteredValues = getEnteredValues();
if (enteredValues.size() != 3) {
// something went terribly wrong, but just to be safe
} else {
int a = enteredValues.get(0);
int b = enteredValues.get(1);
int c = enteredValues.get(2);
int min = Math.min(a, Math.min(b, c));
int max = Math.max(a, Math.max(b, c));
if (a > min && a < max) {
// a is mid
} else if (b > min && b < max) {
// b is mid
} else {
// c is mid
}
}
private static List<Integer> getEnteredValues() {
Scanner in = new Scanner(System.in);
List<Integer> enteredValues = new LinkedList<>();
System.out.println("Enter 3 unique numbers");
while (enteredValues.size() < 3) {
Integer enteredValue = in.nextInt();
if (enteredValues.contains(enteredValue)) {
// probably prompt them to enter another number
} else {
enteredValues.add(enteredValue);
}
}
return enteredValues;
}
So what this does is first get the 3 numbers from the user. It'll force them to enter 3 unique numbers by only adding their input to the collection if it's unique.
After it fetches the numbers from the user, it'll use Math.min and Math.max to get the min and max between all 3 numbers. Then, it's just a simple if/else tree to figure out which one lies in between the calculated min/max.
I hope this helps!
Related
I'm struggling with an exercise to find the max input of N values. I'm being able to print the max value but the exercise asks to print ONLY the max value and I'm not being able to return it from outside the IF statement.
Exercise's instructions:
Write a program that:
reads a number N (must be greater than 0) from the console
reads N numbers from the console
Displays the maximum of the N entered numbers.
My code:
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i=0;
int count=1;
int max=Integer.MIN_VALUE;
for (i=0; i<count; i++) {
int cur = sc.nextInt();
count++;
if (cur>0){
if (cur>max) {
max=cur ;
System.out.println(max);
}
}
}
}}
In the console I'm getting the desired inputs plus this error
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
First of all, you must import java.util.Scanner when you using Scanner class.
I changed some lines of your code, I think this is what you want:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // get N (how many numbers)
int number;
int max = Integer.MIN_VALUE;
if (n > 0) {
for (int i = 0; i < n; i++) {
number = sc.nextInt(); // get numbers
if (number > max)
max = number;
}
System.out.println(max); // print the maximum number
} else
System.out.println("Please enter greather than 0 number"); // when n is negative or zero
}
}
You should read the exercise carefully. First, you must read the N number to determine how many numbers should be read from the console in total.
Also you must handle the exception cases with try-catch blocks that might be thrown during reading or parsing. Try this one:
Playground: https://repl.it/repls/OrnateViolentSoftwaresuite (it might take some time to load).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 1. reads a number N (must be greater than 0) from the console
int N = 0;
while(N == 0) {
try {
System.out.print("Enter N: ");
// Use sc.nextLine() instead of .next() or .nextInt()
N = Integer.parseInt(sc.nextLine());
} catch (Exception ignored) {}
}
// 2.reads N numbers from the console
int max = Integer.MIN_VALUE;
for (int i = 0; i < N; i++) {
while(true) {
try {
System.out.printf("Enter %d. number: ", i + 1);
// determine the max during reading
max = Math.max(max, Integer.parseInt(sc.nextLine()));
break; // cancels while(true)
} catch (Exception ignored) {}
}
}
// 3. Displays the maximum of the N entered numbers
System.out.printf("The max number is %d\n", max);
System.out.println("Goodbye!");
sc.close(); // don't forget to close the resource
}
Update
If you really haven't learned the try / catch yet, then you don't have to use it either. You can simply remove the try-catch blocks from the above code, which should also work (for valid integer inputs only)
e.g. instead of
try {
System.out.print("Enter N: ");
// Use sc.nextLine() instead of .next() or .nextInt()
N = Integer.parseInt(sc.nextLine());
} catch (Exception ignored) {}
just use
System.out.print("Enter N: ");
// Use sc.nextLine() instead of .next() or .nextInt()
N = Integer.parseInt(sc.nextLine());
Ok, this is how I solved it. Initially I wasn't understanding that the first input was the number of inputs. Once I understood that, it became a bit easier.
Basically I had to tell the program to only print the max number after the last input (n-1). Thanks to all that helped.
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // get N (how many numbers)
int number;
int max=Integer.MIN_VALUE;
for (int i=0; i<n; i++) {
number = sc.nextInt();
if (number>max) {
max=number ;
}
if (i==n-1)
System.out.print(max);
}
}
}
Here's a step by step explanation.
Read in a number N (N > 0)
int n = sc.nextInt();
Check for N > 0
if (n <= 0) {
System.out.println("Must be > 0, please try again.");
}
To continually do this, use a while loop.
int n = -1;
while (n <= 0) {
n = sc.nextInt();
if (n <= 0) {
System.out.println("Must be > 0, please try again.");
}
}
Now find the max.
// initialize to first value
int max = sc.nextInt();
Now get the others
// start from 1 since we already have a value
for(i = 1; i < n; i++) {
int v = sc.nextInt();
// if current value is greater than max
// replace max with current value
if (v > max) {
max = v;
}
}
Print the answer.
System.out.println("max = " + max);
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)
again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot
write a program input an integer in the range 100 to 200 inclusive. If the user enters invalid input then your algorithm should re-prompt the user until the input is valid. Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input. Finally, the count should be output to the user. You should make good use of sub-modules.
Here my code
import java.util.*;
public class Exam3
{
public static void main(String args[])
{
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while(input < 100 || input > 200)
{
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count ++;
}
System.out.println("count is: " + count);
}
public static void int getCount(int input, int count)
{
for(int i = 499;i <= 1000; i++ )
{
if(i % input==0)
{
count++;
}
}
return count;
}
}
The algorithm should be:
Having correct input, find all multiples of it that are in range [500, 1000]. Count them.
It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.
Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.
public static void main(String args[]) {
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while (input < 100 || input > 200) {
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count++;
}
System.out.println(input + " fits " + count(input) + " times");
}
private static int count(int input) {
int result = 0;
int temp = input;
while (temp <= 1000) {
if (temp >= 500) {
result++;
}
temp += input;
}
return result;
}
According to your code, I see some issues. I'll point them out, as it is important for practicing Java.
Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,
It's important to stick to Java styling. Don't put too many empty lines, keep indents.
Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.
import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]
import java.util.*;
public class multiple {
public static int userNumber;
public static int userChoice;
static Stack<Object> stack = new Stack<Object>();
static int[] list = new int[100];
public static void main(String[] args) {
introduction();
multiple();
printStack(stack);
}
public static void introduction() {
Scanner input = new Scanner(System.in);
System.out.print("Welcome to the program, please enter the number less than 100 that you would like "
+ "to find whoes number \nbelow have muliples of 3 and 5: ");
userNumber = input.nextInt();
System.out.println();
// System.out.println("Ok, now that youve entered," + userNumber +
// " we will find out which numbers of you number are three and five. "
// +
// "would you like the result published as a:\n 1.alist \n 2.A sum of the result \n 3.Or both?");
// userChoice = input.nextInt();
// if (userChoice >=1 && userChoice <=3)
// System.out.println( "The Computer will now program for" +
// userChoice);
// else
// System.out.println("incorrect entry for menu. Please try again");
}
public static void multiple() {
for (int i = 1; i < userNumber; i++) {
if (i % 3 == 0 || i % 5 == 0) {
stack.push(i);
}
}
}
// public static addElementsofstac
private static void printStack(Stack<Object> s) {
if (s.isEmpty())
System.out.println("You have nothing in your stack");
else
System.out.println(s);
}
}
I am trying to make a simple program that will take input for a user, find out the multiples of 3 & 5, then return the sum of the multiple. I have all the multiples discovered. I have a hunch that i need to convert the stack to an array. if so, would i just use stack.toArray()? then i would add them in a for loop?
Alternative without the need for intermediary counter variable:
int sum = 0;
while (stack.size() > 0) sum += stack.pop();
Why would you need an array?
You just need to do something along the lines of:
int sum = 0;
for(i=0;i<stack.size();i++){
sum = sum + stack.pop();
}
Though I agree with the others in that there's really no purpose of the stack itself.
EDIT: your clarification is only more confusing. How are 3, 6 and 9 multiples of 10? Are you talking about integers less than an inputted number that are multiples of 3 and 5?
I usually do this way:
ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
int ans = 0;
<...>
for (Integer n : stack) {
ans += n;
}