I want to have an error message appear if a user types more than three integers into the console. So if the console says "Type three integers" and the user types 123 244 242, no matter the numbers size, it should run without a problem. But if the user types 123 244 242 442 then when they press run I would like an error message to appear instead. But not entirely sure how to go about this.
Here is the simple program:
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Type three integers ");
int firstInt = userInput.nextInt();
int secondInt = userInput.nextInt();
int thirdInt = userInput.nextInt();
System.out.println(firstInt + secondInt + thirdInt);
}
}
Thank you
int firstInt = userInput.nextInt();
int secondInt = userInput.nextInt();
int thirdInt = userInput.nextInt();
char run = userInput.next().charAt(0);
if(userInput.hasNext())
{
System.out.println("Error, you need 3 numbers only, and a char");
userInput.nextLine(); //clears the rest of the line
}
give that a shot and see how it goes. I would suggest having this in a while loop so that it will keep priming for numbers until it gets all of them without error.
public static void main(String[] args)
{
boolean getNumbers = true;
int firstInt, secondInt, thirdInt;
Scanner userInput = new Scanner(System.in);
while(getNumbers)
{
firstInt = userInput.nextInt();
secondInt = userInput.nextInt();
thirdInt = userInput.nextInt();
char run = userInput.next().charAt(0);
if(userInput.hasNext())
{
System.out.println("Error message here");
userInput.nextLine(); //clear the rest of line
firstInt = secondInt = thirdInt = 0;
run = '';
}
else
{
getNumbers = false;
}
}
//do calculations with numbers here
}
Related
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int a = sc.nextInt();
boolean aValid = sc.hasNextInt();
System.out.println(aValid);
System.out.println("Enter Second number");
int b = sc.nextInt();
boolean bValid = sc.hasNextInt();
System.out.println(bValid);
if(aValid && bValid){
System.out.println("Sum of number is "+(a+b));
}
else{
System.out.println("Enter integer number");
}
}
}
I try to get input of a and b and validate that a and b are integers. But it takes three input. It gives the sum of the first two numbers and gives the validity of the last two.
you need to place check integer statements before taking input
boolean aValid = sc.hasNextInt();
int a = sc.nextInt();
boolean bValid = sc.hasNextInt();
int b = sc.nextInt();
Running this code makes the error fairly obvious. Some additional debug statements, running the code in debug or testing would also make it clear.
Scanner.nextInt() will throw an exception if it gets a non integer.
Scanner.hasNextInt() on the other hand returns a boolean value to warn you in advance whether it has an integer or not - it does not take the value from the Scanner.
This code has a couple of tiny corrections that will achieve the outcome you stated.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
} else {
sc.next(); //Discard the non-integer input.fr
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
boolean aValid = sc.hasNextInt();
if (aValid) {
a = sc.nextInt();
}
System.out.println(aValid);
System.out.println("Enter Second number");
boolean bValid = sc.hasNextInt();
if (bValid) {
b = sc.nextInt();
}
System.out.println(bValid);
if (aValid && bValid) {
System.out.println("Sum of number is " + (a + b));
} else {
System.out.println("Enter integer numbers only");
}
}
}
I have this program what reads numbers from an input file, then asks the user to enter a number. The program then reads all numbers in the file and if the number entered is in the file, the program prints back, "Number is in file", if the number entered is not in the file, the program prints back, "Number is not in file." I need to also have it be able to quit the program if the user enters 'q', but I am unsure as to how I can do that seeing is that 'q' is a char and the program is looking for an input of an int. I did create a variable char quit = 'q', but I'm not sure where to use it, if this is even the right way to start.
package classwork7_2;
import java.util.*;
import java.io.*;
public class ClassWork7_2 {
public static void main(String[] args)throws IOException {
Scanner s = new Scanner(System.in);
int[] numbers = fileToArray();
Arrays.sort(numbers);
char quit = 'q';
while (true) {
System.out.print("Enter a number in the file: ");
int numb = s.nextInt();
int i = Arrays.binarySearch(numbers, numb);
if (i < 0) {
System.out.print("Number is not in file\n");
} else {
System.out.print("Number is in file\n");
}
}
}
public static int[] fileToArray() throws IOException{
Scanner s = new Scanner(System.in);
int[] array = new int[7];
System.out.print("Enter name of file: ");
String filename = s.nextLine();
File f = new File(filename);
Scanner inputFile = new Scanner(f);
int i = 0;
while(inputFile.hasNext()){
array[i] = inputFile.nextInt();
i++;
}
inputFile.close();
return array;
}
}
You can change the while loop like below:
Here, instead of reading nextInt, reading string and converting to int if it is not q
while (true) {
System.out.print("Enter a number in the file: ");
String ln = s.nextLine();
if("q".equals(ln)) {
break;//exiting as user entered "q"
}
int numb = Integer.parseInt(ln);
int i = Arrays.binarySearch(numbers, numb);
if (i < 0) {
System.out.print("Number is not in file\n");
} else {
System.out.print("Number is in file\n");
}
}
Scanner s = new Scanner(System.in);
String userInput = s.next();
int result = Integer.parseInt(userInput);
You can take the original number inputs as strings then parse them into an integer and use that result when using your binary search.
Check that if scanner has int or letter 'q':
while (true) {
System.out.print("Enter a number in the file: ");
if (s.hasNextInt()) {
int numb = s.nextInt();
int i = Arrays.binarySearch(numbers, numb);
if (i < 0) {
System.out.print("Number is not in file\n");
} else {
System.out.print("Number is in file\n");
}
}
if (s.hasNext("q")) {
return;
}
}
I'm trying to write a program that asks the user to enter the maximum and minimum values of words they would like to be in the essay, and then enter the essay. The program checks to see if the number of words the user inputted is within the range they specified. Is there a way I can turn my code into a method? Here's my code:
Desired output:
Please enter the maximum: 9
Please enter the minimum: 5
enter: hello there
2
YAY!!!!!!!!! YOU'RE WTHIN THE RAAAANGE!!!!!!!!!!!!!!!!!!!!!!!
Here's my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("\t\tPlease enter the maximum: ");
int max = input.nextInt();
System.out.print("\t\tPlease enter the minimum: ");
int min = input.nextInt();
System.out.print("enter: ");
String word = input.next();
int countwords = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == ' ') {
countwords++;
}
}
countwords++;
System.out.println(countwords);
if(countwords<=max && countwords >=min){
System.out.println(
"YAY!!!!!!!!! YOU'RE WTHIN THE RAAAANGE!!!!!!!!!!!!!!!!!!!!!!!"
);
}
}
There are 2 issues in your program:
You get your input text with next() instead of nextLine() such that you only get one word instead of the whole line.
The way you count the words is not correct as you only count the spaces, you should use something like word.split("\\s+").length instead which slips the content of word using a sequence of whitespace characters as separator then get the length to get the total amount of resulting words.
So simply change this:
...
System.out.print("enter: ");
String word = input.nextLine();
int countwords = word.split("\\s+").length;
NB: hello there contains 2 words and 2 is not between 5 and 9 so you won't get the success message with those inputs, try instead with 1 and 5 for example.
we keep the user input in the main.
Scanner input = new Scanner(System.in);
System.out.print("Please enter the maximum: ");
int max = input.nextInt();
System.out.print("Please enter the minimum: ");
int min = input.nextInt();
input.nextLine();
System.out.print("enter: ");
String word = input.nextLine();
if(isInRange(min,max,word)){
System.out.println(
"YAY!!!!!!!!! YOU'RE WTHIN THE RAAAANGE!!!!!!!!!!!!!!!!!!!!!!!"
);
}
now we move the calculation towards a method like this:
static boolean isInRange(int min, int max, String words) {
int length = words.split("\\W+").length;
if (length <= max && length >= min) {
return true;
} else {
return false;
}
}
you will get the desired output, if the amount of words is within the range. the input.readLine(); consumes leftovers from nextInt()
You should use the String's split method with a space-regex (like "\s+" or similar) to handle the word separation.
Before you split the string, you should use the trim method to be sure that there's no space before or after the string to prevent wrong splits.
And like XtremeBaumer already posted, it's nice to wrap it into a method. But I'd make a method like that then:
public static boolean inRange(int min, int max, String str) {
return min <= split.trim().split("\\s+").length <= max;
}
Here it is,
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
wordCountCheck();
}
public static void wordCountCheck() {
Scanner input = new Scanner(System.in);
System.out.print("\t\tPlease enter the maximum: ");
int max = input.nextInt();
System.out.print("\t\tPlease enter the minimum: ");
int min = input.nextInt();
input.nextLine();
System.out.print("enter: ");
String word = input.nextLine();
String[] wordArray = word.trim().split("\\s+");
int countwords = wordArray.length;
System.out.println(countwords);
if(countwords<=max && countwords >=min){
System.out.println(
"YAY!!!!!!!!! YOU'RE WTHIN THE RAAAANGE!!!!!!!!!!!!!!!!!!!!!!!"
);
} else {
System.out.println(
"OOPS!!!!!!!!! YOU'RE NOT WTHIN THE RAAAANGE!!!!!!!!!!!!!!!!!!!!!!!"
);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("\t\tPlease enter the maximum: ");
int max = input.nextInt();
System.out.print("\t\tPlease enter the minimum: ");
int min = input.nextInt();
System.out.print("enter: ");
Scanner lineInput = new Scanner(System.in);
String word = lineInput.nextLine();
String[] lengthword = word.split("\\s+");
int countwords = lengthword.length;
if (countwords <= max && countwords >= min) {
System.out
.println("YAY!!!!!!!!! YOU'RE WTHIN THE RAAAANGE!!!!!!!!!!!!!!!!!!!!!!!");
} else {
System.out
.println("Ohh!!!!!!!!! YOU'RE Not in RAAAANGE!!!!!!!!!!!!!!!!!!!!!!!");
}
}
first finish the last line by calling ".nextLine()".
public class Test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("\t\tPlease enter the maximum: ");
int max = input.nextInt();
System.out.print("\t\tPlease enter the minimum: ");
int min = input.nextInt();
System.out.print("enter: ");
input.nextLine();//finish the last line first
String word = input.nextLine();
System.out.print(word);
int countwords = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == ' ') {
countwords++;
}
}
countwords++;
System.out.println(countwords);
if(countwords<=max && countwords >=min){
System.out.println(
"YAY!!!!!!!!! YOU'RE WTHIN THE RAAAANGE!!!!!!!!!!!!!!!!!!!!!!!"
);
}
}
}
I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!
The only thing i am missing is to use a sentinel value, like zero, to quit the loop when the user wants, even without enter any gussing.
import java.util.Scanner;
import java.util.Random;
public class RandomGuessing {
//-----------------------------------------------------------------------------------------------
//This application prompt to the user to guess a number. The user can still playing until
//guess the number or want to quit
//-----------------------------------------------------------------------------------------------
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Random rand = new Random();
int randNum = rand.nextInt(100) + 1;
System.out.println(randNum);
System.out.println("\t\tHi-Lo Game with Numbers\t\t\n\t Guess a number between 1 and 100!!!\n");
String ans;
int attemptsCount = 0;
do {
System.out.print("Guess the number: ");
int input = scan.nextInt();
while(input != randNum){
attemptsCount++;
if(input < randNum){
System.out.println();
System.out.print("low guessing\nEnter new number: ");
input = scan.nextInt();
}
else{
System.out.println();
System.out.print("high guessing\nEnter new number: ");
input = scan.nextInt();
}
}
System.out.println();
System.out.println("Congrats!!! You guess right\nAttempts: "+attemptsCount);
System.out.println();
System.out.print("You want to play again (yes/no): ");
ans = scan.next();
randNum = rand.nextInt(100) + 1; //generate new random number between same above range,
//if the user wants to keep playing.
}while (ans.equalsIgnoreCase("yes"));
}
}
Here's a simple approach:
// inside do loop
System.out.print("Guess the number (-1 to quit): ");
int input = scan.nextInt();
if (input == -1) {
break;
}
Try using this code for exiting totaly:
System.exit(0);