This program is meant to prompt a user to enter three integers, store the integers in three separate variables, and output the three integers in descending order (highest to lowest values).
import java.util.Scanner;
public class ProgramToo
{
public static void main(String [] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Enter the first number:");
int num1 = kbd.nextInt();
System.out.println("Enter the second number:");
int num2 = kbd.nextInt();
System.out.println("Enter the three number:");
int num3 = kbd.nextInt();
int result = largeSmall(num1, num2, num3);
System.out.println(result);
}
public static int largeSmall(int one, int two, int three)
{
if(one > two && two > three)
{
System.out.println(one + " " + two + " " + three);
}
else if(two > one && one > three)
{
System.out.println(two + " " + one + " " + three);
}
else if(three > two && two > one)
{
System.out.println(three + " " + two + " " + one);
}
else
{
System.out.println(one + " " + three + " " + two);
}
return largeSmall(one, two, three);
}
}
When I run this program, it outputs the integers a million times and crashes. Why?
Your solution is really over-engineered. Just do something like this:
public static void main(String [] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Enter the first number:");
int num1 = kbd.nextInt();
System.out.println("Enter the second number:");
int num2 = kbd.nextInt();
System.out.println("Enter the three number:");
int num3 = kbd.nextInt();
Integer[] arr = new Integer[3]
arr[0] = num1;
arr[1] = num2;
arr[2] = num3;
Arrays.sort(arr, Collections.reverseOrder());
System.out.println(arr[0] + " " + arr[1] + " " + arr[2]);
}
Looks like you almost had it there. I assume you are a new student. If you just change the method to void (doesn't require a return value), you will get the answer you need from just calling the method. You had the method and your main both looping through println. I only deleted a few lines and changed the method signature to get it working.
public class Application {
public void start() {
Scanner kbd = new Scanner(System.in);
System.out.println("Enter the first number:");
int num1 = kbd.nextInt();
System.out.println("Enter the second number:");
int num2 = kbd.nextInt();
System.out.println("Enter the three number:");
int num3 = kbd.nextInt();
largeSmall(num1, num2, num3);
}
public static void largeSmall(int one, int two, int three)
{
if(one > two && two > three)
{
System.out.println(one + " " + two + " " + three);
}
else if(two > one && one > three)
{
System.out.println(two + " " + one + " " + three);
}
else if(three > two && two > one)
{
System.out.println(three + " " + two + " " + one);
}
else
{
System.out.println(one + " " + three + " " + two);
}
}//end start method
}//end application class
blm's solution will work, but I thought it might be useful to know what was wrong with yours. You were constantly calling your same function over and over again. To fix it, do the following
Change the return type to void
Remove the return statement recursion
Replace int result = largeSmall(num1, num2, num3);
System.out.println(result); with largeSmall(num1, num2 num3);.
Scanner k = new Scanner(System.in);
System.out.println("Enter the first number");
int c = k.nextInt();
System.out.println("Enter the second number");
int c2 = k.nextInt();
System.out.println("Enter the third number");
int c3 = k.nextInt();
int max = 0, mid = 0, min = 0;
if (c > c2 && c > c3) {
max = c;
mid = (c2 > c3) ? c2 : c3;
min = (c2 > c3) ? c3 : c2;
System.out.println("In ascending :"+min+","+mid+","+max);
System.out.println("In desascending :"+max+","+mid+","+min);
} else if (c2 > c && c2 > c3) {
max = c2;
mid = (c > c3) ? c : c3;
min = (c > c3) ? c3 : c;
System.out.println("In ascending :"+min+","+mid+","+max);
System.out.println("In desascending :"+max+","+mid+","+min);
} else if (c3 > c && c3 > c2) {
max = c3;
mid = (c > c2) ? c : c2;
min = (c > c2) ? c2 : c;
System.out.println("In ascending :"+min+","+mid+","+max);
System.out.println("In desascending :"+max+","+mid+","+min);
}
int num=0; Scanner kbd = new Scanner(System.in); num = kbd.nextInt(); System.out.println(num); Run this program but enter text instead of an integer. The program should crash and tell you what kind of exception was thrown by the nextInt method. Wrap this code inside a try/catch block where you catch the exception that is thrown. Add a loop so the user must enter the number again if text is entered.
Related
I am trying to make a program that solves for all the 2 number combinations of addition and subtraction that equal a target value.
For example, given the array [12,1,9,11,32,19] and the target value twenty, the answers 1+19, 9+11, and 32-12 must be returned. If there are no possible combinations, the System should print that there are no possible combinations. Also, every combination must be two numbers ONLY. Is it possible to do this only in the main class?
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What length (in a whole number) would you like the array to be? ");
int arraySize = sc.nextInt();
int [] arr = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
int remainingNumbers = arraySize - i;
System.out.println("Please enter " + remainingNumbers + " more integers.");
arr[i] = sc.nextInt();
}
System.out.print("Please enter a target value: ");
int target = sc.nextInt();
System.out.println(Arrays.toString(arr));
// Algorithm here.
}
}
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.println(num1 + " + " + num2 + " = " +
(num1 + num2));
System.out.println(num1 + " - " + num2 + " = " +
(num1 - num2));
System.out.println(num1 + " x " + num2 + " = " +
(num1 * num2));
System.out.println(num1 + " / " + num2 + " = " +
(num1 / num2));
System.out.println(num1 + " mod " + num2 + " = " +
(num1 % num2));
}
}
enter code here
''' Input first number: 32 Input second number: 12 19 + 1 = 20 32 - 12 = 20 9+11= 20'
Yes, it is possible to do it only in the main class. It is even possible to do it only in the main method (despite doing it an own method is better, easier to understand). Just two nested for loops; one for the first value, one for the second value. Inside the inner loop just test if the sum of both values result in the expected result, same for subtraction. Set a boolean to indicate that at least one case was found. At the end print the negative message if the boolean is not set.
Sample:
private static boolean findCombinations(int target, int[] values) { // or ,int... values) {
boolean found = false;
for (int i = 0; i < values.length; i++) {
// second loop
// tests and print
}
return found;
}
I am writing a simple code in Java that is using recursion. I want to show the product of two numbers that a user will enter. I managed to do that using recursion, but stuck at the point where I want to show that the product could be written as (example) 10*5 = 5+5+5+5+5+5+5+5+5+5 (10 times), or 12*3 = 3+3+3+3+3+3+3+3+3+3+3+3 (12 times). Here is my code so far. In the code i put a comment where it should be written (example). Thanks.
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a, b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.println("The product of " + a + " and "
+ b + " is: " + multiRec(a, b));
System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
return x + (multiRec(x, y - 1));
}
}
}
}
A StringBuilder should be defiend as
StringBuilder buf = new StringBuilder (a);
Pass this StringBuilder paramater into multiRec
and then change multiRec to be
public static int multiRec(int x, int y, StringBuilder buf) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
buf.append (" + ").append (x);
return x + (multiRec(x, y - 1, buf));
}
}
}
}
Then when completed simply printout its value
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a , b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.printf("%d %s %d %s",a , "*" , b ,"= ");
System.out.println("\nThe product of " + a + " and "
+ b + " is: " + multiRec(b, a));
// System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
System.out.print(x+" ");
if (y == 1) {
return x;
} else {
System.out.print(" + ");
return x + (multiRec(x, y - 1));
}
}
}
}
I am currently struggling with one thing about this assignment. I would just like a way to make the whole code shorter, even just a little bit (especially the if statement).
package Integers;
import java.util.Scanner;
public class SumOfInt {
public static void main(String[] args) {
int positive = 0;
System.out.println ("-Input ten non-zero integers to calculate their sum. " + "\n" + "-Input the integers at the console and press <Enter>" + "\n");
System.out.println ("Input the 1st integer:");
Scanner input = new Scanner (System.in);
int num1 = input.nextInt ();
System.out.println ("Input the 2nd integer:");
int num2 = input.nextInt ();
System.out.println ("Input the 3rd integer:");
int num3 = input.nextInt ();
System.out.println ("Input the 4th integer:");
int num4 = input.nextInt ();
System.out.println ("Input the 5th integer:");
int num5 = input.nextInt ();
{ if (num1 > 0)
positive++;
}
{ if (num2 > 0)
positive++;
}
{ if (num3 > 0)
positive++;
}
{ if (num4 > 0)
positive++;
}
{ if (num5 > 0)
positive++;
}
System.out.println ("The number of positive integers are: " + positive);
}
}
If you find yourself writing very similar code over and over again (or even copy-pasting stuff), there is always a way to generalise the code and put in into a for loop or an extra method. And that is the way to go.
In your case you could just simply use a for loop.
public static void main(String[] args) {
int positive = 0;
System.out.println("Input the integers at the console and press <Enter>");
Scanner input = new Scanner (System.in);
for (int i = 1; i <= 5; i++) {
System.out.println("Input the " + i + "st integer:");
int x = input.nextInt();
if (x > 0) positive++;
}
input.close();
System.out.println ("The number of positive integers are: " + positive );
}
Try this
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 5; i++) {
String place = i + "th";
if (i == 1)
place = "1st";
if (i == 2)
place = "2nd";
if (i == 3)
place = "3rd";
System.out.println("Input the " + place + " integer:");
if (input.nextInt() > 0)
positive++;
}
input.close();
System.out.println("The number of positive integers are: " + positive);
If you want to store the variable for later use, you can Use array to make it easier.
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int positive = 0;
for (int i = 0; i < 5; i++) {
array[i]=input.nextInt();
if (array[i] > 0)
positive++;
}
System.out.println("Number of positive elements are"+ positive);
I basically want to be able to loop an X + Y = Z equation until the user inputs something other than an integer, like the letter "A" and also when having any number make the loop stop displaying a message.
Also, I am confused on how to randomly position the "?" which the user must input the correct answer.
For example
System.out.println("What is: " + num1 + " + ? = " + answer);
So far:
I am positioning the "?" manually through the IF statements. Can this be done in a more efficient way?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
Here is one way to do it:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
Notes:
I use an inner do-while loop to repeatedly check the input and ask the user for a valid input.
I use 2 arrays: one for storing the numbers and another for storing the display values.
I also added a stop condition since the outer loop is infinite. Always close the Scanner when you finish.
I randomly pick 1 of 3 positions for the "?".
int a;
int b;
int c;
Scanner input = new Scanner (System.in);
//how to read three integers with white space delimiter
System.out.print("Enter the 3 edges of the triangle to be calculated: ");
int numbers = input.nextInt();
//then turn 3 integers into boolean form
//this is only the algorithm
Boolean isTriangle = ((a+b>c) && (b+c > a) && (c+a > b));
System.out.print(isTriangle);
else
System.out.print(isTriangle);
So instead of entering 3 integers in a separate line or in a newline i want them all to be in the same line just separated with whitespace. Do I need to change standard input as string then just parse it after for the boolean part? I am confuse because after entering the integers I don't know where to store them to use for the boolean part.
Edited part:
public static void main(String[] args){
int x;
int y;
int z;
Scanner input = new Scanner(System.in);
System.out.println("Enter three edges: ");
x = input.nextInt();
y = input.nextInt();
z = input.nextInt();
boolean isTriangle = ((x+y>z) && (y+z > x) && (z+x > y));
if (isTriangle){
System.out.print("Can edges " + x + ", " + y + ", " + z + " form a triangle"+ isTriangle);
}
else {
System.out.print("Can edges " + x + ", " + y + ", " + z + " form a triangle"+ isTriangle);
}
}
why is it that when i call x y and z in system.out they don't show the entered input but when i only put the isTriangle on system.out it gives me output
Just call the nextInt three times.
System.out.print("Enter the 3 edges of the triangle to be calculated: ");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
With input
5 5 5
It prints true.
You'll have to check wether there are three numbers available (use input.hasNextInt() before input.nextInt()):
System.out.print("Enter the 3 edges of the triangle to be calculated: ");
if(input.hasNextInt()) {
a = input.nextInt();
} else {
//handle it, you don't have ints!
}
if(input.hasNextInt()) {
b = input.nextInt();
} else {
//handle it, you have just one int!
}
if(input.hasNextInt()) {
c = input.nextInt();
} else {
//handle it, you have just two ints!
}
DEMO
It's better to use below.
String values=scanner.next();//if your input 5 5 5
String numinString[]=values.split(" ");
int a=Integer.parseInt(numinString[0]);//a=5
int b=Integer.parseInt(numinString[1]);//b=5
int c=Integer.parseInt(numinString[2]);//c=5
You can do it this way:
int a;
int b;
int c;
Scanner input = new Scanner(System.in);
// how to read three integers with white space delimiter
System.out.print("Enter the 3 edges of the triangle to be calculated: ");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
// then turn 3 integers into boolean form
// this is only the algorithm
Boolean isTriangle = ((a + b > c) && (b + c > a) && (c + a > b));
if (isTriangle)
System.out.print(isTriangle);
else
System.out.print(isTriangle);