How to read from one line separated with only whitespace? - java

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);

Related

How to remove repetitive operations in a separate method?

My code has to guess the hidden number from 0 to 100 in 7 attempts. And every time I need to call the same operations again. How can I move these operations into a separate method and call them from there?
public class Main {
public static void main(String[] args) throws IOException {
int min = 0;
int max = 100;
int midrange = Math.round((min + max)/2);
String strInput = "";
Scanner scan = new Scanner(System.in);
while (!strInput.equals("1")){
System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
strInput = scan.nextLine();
}
while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
"Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
strInput = scan.nextLine();
}
if (strInput.equals("=")) System.out.println("Great! Thank you for the game.");
else if (strInput.equals("+")){
// reduce the range
min = midrange;
// find a new midrange
midrange = Math.round((min + max)/2);
} else if (strInput.equals("-")){
max = midrange;
midrange = Math.round((min + max)/2);
}
strInput = "";
while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
System.out.println("Is this number greater than, less than or equal to " + midrange + "? ");
strInput = scan.nextLine();
}
// ... and so on until the correct number is found.
}
}
You don't need multiple while loops. Just check for equality and put your if-else-block into the while loop. If you guessed the number correct just break out of the loop.
public static void main(String[] args) throws IOException {
int min = 0;
int max = 100;
int midrange = Math.round((min + max) / 2);
String strInput = "";
Scanner scan = new Scanner(System.in);
System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
strInput = scan.nextLine();
while (!strInput.equals("=")) {
System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
"Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
strInput = scan.nextLine();
if (strInput.equals("=")) {
System.out.println("Great! Thank you for the game.");
break;
} else if (strInput.equals("+")) {
min = midrange;
midrange = Math.round((min + max) / 2);
} else if (strInput.equals("-")) {
max = midrange;
midrange = Math.round((min + max) / 2);
}
}
}

Java validating input

is it possible in Java to check if a certain input is between a certain range and also an integer?
I have written the following code:
public void getBetAmountFromUser() {
//Get Amount of Bet
int x = 0;
System.out.println("Your current pot is: " + potAmount);
System.out.println("Enter your bet amount: ");
x = input.nextInt();
//Error message if bet is larger than pot and less than 0
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
//Bet should be less than or equal to pot if 0 user quit
if (x > 0 && x <= potAmount) {
betAmount = x;
potAmount = potAmount - betAmount;
} else if (x == 0) {
System.out.println("You end the game with pot " + potAmount);
System.exit(0);
}
}
The following loop did not work on validating Integer
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
You can try to use String in lieu of int. Then, you can go ahead with again int using Integer.parseInt(x) because it's already been verified as being valid integer after do-while
String x;
String regex = "[0-9]+"; // to check the string only is made up of digits
int potAmount = 10;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
x = input.next();
} while (!x.matches(regex) || Integer.parseInt(x) > potAmount || Integer.parseInt(x) < 0);
int validBet = Integer.parseInt(x);
/* .
.
. *\

How can i make it so that if user inputs 0 a output line says that you cannot divide by zero in java

I'm trying to not have the user input be 0 for "a" since this would cause the equation to divide by zero, which outputs an error, i would to be able to have a println saying that you cannot divide by zero if the user inputs 0 for "a" Here is my code, I'm not sure what I'm doing wrong, I'm still new at this, just need help:
import java.util.Scanner;
class a3main{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the value of a");
int a = keyboard.nextInt();
System.out.println("Enter the value of b");
int b = keyboard.nextInt();
System.out.println("Enter the value of c");
int c = keyboard.nextInt();
double R1, R2, dis;
dis = b * b - 4 * a * c; // This is the discriminant formula
if(dis > 0 )
{
System.out.println("The roots are both real numbers and unequal");
R1 = (-b + Math.sqrt(dis))/(2*a);
System.out.println("The first root is: " + R1);
R2 = (-b - Math.sqrt(dis))/(2*a);
System.out.println("The second root is: " + R2);
}
else if(dis == 0)
{
System.out.println("The roots are both equal and are equal");
R1 = (-b + Math.sqrt(dis))/(2*a);
System.out.println("The root is: " + R1);
}
else if (a == 0)
{
System.out.println("You cannot divide by 0");
}
else
{
System.out.println("The roots are imaginary");
}
}
}
You need to put your if(a == 0) check before your checks that look at dis.

Program that will output three integers in descending ordrer

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.

How do I turn this into a simple program to take in 5 numbers and tell the least and greatest?

I thought I was on to something for a while but then I had an issue with the result line being printed infinitely. Now I just can't get it to work at all. Does anyone have an idea how to turn this code style into something functional for my stated goals?
import java.util.Scanner;
public class Numerical
{
public static void main (String [ ] args )
{
Scanner scan = new Scanner (System.in);
System.out.println("Please enter 5 numbers one after another");
{
int a = scan.nextInt ( ); // First number input by user
int b = scan.nextInt ( ); // Second number input by user
int c = scan.nextInt ( ); // Third number input by user
int d = scan.nextInt ( ); // Fourth number input by user
int e = scan.nextInt ( ); // Fifth number input by user
// Check if a is the greatest number
if (a > b);
while(a > c);
while(a > d);
while(a > e);
System.out.println ("The highest number is " +a);
// Check if b is the greatest number
else if (b > a);
while(b > c);
while(b > d);
while(b > e);
System.out.println ("The highest number is " +b);
// Check if c is the greatest number
else if(c > a);
while(c > b);
while(c > d);
while(c > e);
System.out.println ("The highest number is " +c);
// Check if d is the greatest number
else if(d > a);
while(d > b);
while(d > c);
while(d > e);
System.out.println ("The highest number is " +d);
// Check if e is the greatest number
else if(e > a);
while(e > b);
while(e > c);
while(e > d);
System.out.println ("The highest number is " +e);
}
}
}
No need to do all of that. Read the inputs to an array*, use Arrays#sort, the first element is the smallest, the last is the greater.
I don't understand your code, what are those while and if statements? I advise you to go through a basic tutorial to better understand how things work. If you find yourself stuck, there is nothing better than debugging your code, not only you'll find the problem, but you'll understand why you had it.
* You might want to use ArrayList if you don't know the input's length
The best way would be to use an array and implement a sorting method; however, this example will be much easier for you to understand. We're simply comparing each number to the current largest number the user has entered:
import java.util.Scanner;
public class Blahh
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int largest = 0;
int a = scan.nextInt(); // First number input by user
int b = scan.nextInt();
largest = largest(a, b);
int c = scan.nextInt();
largest = largest(largest, c);
int d = scan.nextInt();
largest = largest(largest, d);
int e = scan.nextInt();
System.out.println("The largest number is: " + largest(largest, e));
}
public static int largest(int num1, int num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
}
use the benefits of arrays! they make your code shorter, variable and they have a lot of helpful functions.
import java.util.Arrays;
import java.util.Scanner;
public class Numerical {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter 5 numbers one after another");
int[] inputs = new int[5];
for (int i = 0; i < inputs.length; i++) {
inputs[i] = scan.nextInt();
}
Arrays.sort(inputs);
System.out.println("The highest number is " + inputs[inputs.length - 1]);
}
}

Categories