Outputting a stored value on the same line with text - java

Need help with this program. I am a very green Java student and am very lost. I want this program to prompt a user to input a number and then have the program decide if it's an odd or even number. I would like the output to display the number and then some text after it on the same line:
e.g.
User prompted: "Enter integer to check if it is odd or even"
User enters a "6"
Program should output "6 is an even number".
This is the program I have so far. It calculates odd/even and outputs text based on result. But every time I try to add something to the System.out.println("is an even number.") or the "odd" line it errors out. Not sure how to get the stored variable to output. If the inputted number stored at all?
import java.util.Scanner;
class OddOrEven
{
public static void main(String args[])
{
int integer;
System.out.println("Enter an integer to check if it is odd or even ");
Scanner in = new Scanner(System.in);
integer = in.nextInt();
if ( integer % 2 == 0 )
System.out.println("is an even number.");
else
System.out.println("is an odd number.");
}
}

You need to convert the int to a String, then concatenate it with the + operator:
System.out.println( Integer.toString(integer) + " is an even number.");

Related

While-loop will not terminate in console after entering numbers

I keep trying to get this to work but when I enter in the numbers and enter them into the console it does not finish. I have to terminate myself.
import java.util.Scanner;
public static void main(String[] args) {
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (keyboard.hasNextInt());
System.out.println(outputSum);
}
Well, yes. The keyboard.hasNextInt() call will return false for two reasons.
The next token is a NOT an integer.
You have reached the end-of-input.
What is (most likely) happening is that you have stopped entering numbers. The program is (patiently) waiting for you to enter ... something.
Solutions:
Tell the user to enter the (OS specific) terminal "end of file" character. On Linux it is CTRL-D. On Windows CTRL-Z.
Tell the user to enter something that isn't an integer.
Pick an integer as meaning that there are no more numbers, and test for that.
You also need to instruct the user how to "end" the sequence; e.g.
System.out.println("Enter sequence of numbers. Enter a non-number to stop.");
This is actually a problem with your application's "user interface" design. If the user is expected to type an arbitrarily long sequence of numbers (or something else), then there needs to be some way for the user to tell the program that the sequence is finished. The program cannot magically distinguish the cases of "there are no more" and "hang on, I'm taking a break from typing".
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
In this case hasNext() won't return true because there is neither any integer nor any whitespace. Therefore the program waits for the next input. Besides use a specific integer to break the loop.
for instance,
System.out.println("Input -1 will end the program!";
do{
int x = keyboard.nextInt();
if(x == -1){
break;
}
//do something
}while(true);
Your code is ok. There is no issue.
But before writing code, we need to think about it. The workflow of your code below:
1st time when we enter do loop, keyboard.nextInt() takes input from us.
Then it calculates the sum and performs string operation.
After that, while's keyboard.hasNextInt() takes next input from you.
Checks your input. If your input is not an integer, while loop will terminate(break).
If your input is an integer then, code loop back to keyboard.nextInt(). But this time, it does not take input from you.
It pases the buffered input(keyboard.hasNextInt()) to keyboard.nextInt() and assign the value to inputNum
So, when you want to terminate while loop, you should input any character like a, b, c, etc.
You haven't specified when the loop will end. Have a condition such as inputting a certain number that will end the program once entered, as currently your program is just going to wait for more input. Something like :
System.out.println("Enter sequence of numbers to add. Enter '0' to end the program");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (inputNum != 0);//Keeps going as long as 0 is not entered
//When zero is entered, program shows the total sum and terminates
if (inputNum == 0) {
System.out.println("The sum of all total numbers: ");
System.out.println(outputSum);
System.exit(0);//Terminates program
}
Basic syntax of do-while Loop:
do{
// do something
}while(terminating condition);
If you are using hasNextInt() method of Scanner object for terminating condition in do-while loop then loop will be terminated once it get input other than an integer value (e.g float, double, char, String etc.. ) as shown in below complete program.
import java.util.Scanner;
public class Cumulative{
public static void main(String[] args){
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do{
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
}while (keyboard.hasNextInt()); // loop will terminated whenever get any value other than valid integer such as float char or String etc..
System.out.println(outputSum);
}
}

How to loop through until user inputs a valid integer?

I'm new to java and am trying to validate numbers being entered into the console. I want an integer, but I know if a letter is entered for example an error would occur, so I thought I'd use try & catch. This works if try and do it first time round, but I want to loop through until the user inputs a valid integer. Got this working, but when I get a valid number and print out the number I get a list of all attempts.... Hope this makes sense
import java.util.Scanner;
public class ConvertStringInt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.print("Enter a whole number: ");
try {
i = sc.nextInt();
} catch (Exception e){
System.out.println("Error");
main(args);
}
System.out.println(i);
}
}
Here is the output from the console....
Enter a whole number: a
Error
Enter a whole number: d
Error
Enter a whole number: 2.0
Error Enter a whole number: 1
1
0
0
0
Could somebody please explain this?
Thanks in advance
Neil
You are seeing outputs for each input because you call main recursively. If you immediately type a correct int, the flow is this:
main
ask for input -> int
print i (1)
But in your case the input is not an int. This is what happens: you type the first input, it fails. You do not print yet because you first call main again, asking for the next input. Only when you get a correct int you print, and then finish and allow the previous main-execution to finish by printing, which then allows the previous... and so on:
main(args)
ask for input -> a !int
main(args)
ask for input -> d !int
main(args)
ask for input -> 2.0 !int
main(args)
ask for input -> 1 int
print 1 (1)
print 0 (2.0)
print 0 (d)
print 0 (a)
Look at Ravi's answer for a proper way to repeatedly ask for input without using try/catch (which is discouraged).
You could check for integer token in loop
while (!sc.hasNextInt()) // loop until next token is integer
{
// do something or print error
System.out.println(sc.next() +"is not number");
}
i = sc.nextInt();

Using ints/doubles and Strings in the same Scanner variable

So I'm new to java programming, coming from Python, and there's a few concepts that I can't quite understand.
I'm writing a program which allows the user to enter as many numbers as they want and the program should output the average of all of the numbers. I used a while loop to loop through the inputs by the user as many times as they wanted, but I needed a way of exiting the loop so that the program could proceed with calculating the average of all of the inputs. I decided that if the user enters an "=" sign instead of a number, then the program would break out of the loop, but since the Scanner variable was looking for a double, and the "=" sign is not a number, I would have to make it a String. But because the Scanner is looking for a double, the program threw an error when it encountered the "=".
How can I get the program to exit the loop when the user types "="? I know I could just allow the user to enter a number that breaks the loop, but if it was a real world program and the user entered a number, it would count that number along with the previous ones when calculating the average. The code I have so far is as follows:
import java.util.Scanner;
// imports the Scanner class
public class Average{
public static void main(String[] args){
double num, total = 0, noOfInputs = 0, answer;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.print("Enter number: ");
//Prompts the user to enter a number
num = scanner.nextDouble();
/*Adds the number inputted to the "num" variable. This is the
source of my problem*/
if(num.equals("=")){
break;}
/*The if statement breaks the loop if a certain character is
entered*/
total = total + num;
//Adds the number inputted to the sum of all previous inputs
noOfInputs++;
/*This will be divided by the sum of all of the numbers because
Number of inputs = Number of numbers*/
}
answer = total / noOfInputs;
System.out.print(answer);
}
}
Several ways to do this.
You could read every number as a string, and then if it is a number, parse it to get the value.
Integer.parseInt(String s)
Or you could check what comes next and read accordingly:
while (scanner.hasNext()) {
if (sc.hasNextInt()) {
int a = scanner.nextInt();
} else if (scanner.hasNextLong()) {
//...
}
}
Or you could just catch the InputMismatchException, and work from there.
try{
...
} catch(InputMismatchException e){
//check if '=' ...
}

How to use multiple Input Dialogs (New to Java)

I am trying to create a program that asks a user for a sentinel value (a value to enter when they want to end the list). It then asks the user to enter numbers until they re-enter the sentinel value. It then figures out the max number in the list. I'm very new to Java, and whenever I run the program is just asks for the sentinel value then does nothing else (never pops up the second input dialog). I'm sure it's something simple that I'm doing wrong, but I can't figure it out. Thanks for any help.
import java.util.*;
import javax.swing.JOptionPane;
public class HW1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
int max;
int sentinel;
int count=0;
JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel=input.nextInt();
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
max = number;
while (number!=sentinel){
count +=1;
if (number>max)
max=number;
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
}
if (count!=0){
JOptionPane.showMessageDialog(null, "The max is:" + max);
}
}
}
You are mixing the ways to input data to your program. Let's begin:
Scanner input = new Scanner(System.in);
The line above allows you to catch data in the command line from the keyboard.
JOptionPane.showInputDialog("Please enter a sentinel value: ");
This Option Pane is showing correctly, you put a value and then nothing happens. This is because your program is waiting to input something in the command line
sentinel=input.nextInt();
When your program arrives to the line above, the input.nextInt() stops the program until you put something in the command line.
The correct way should be something like this:
sentinel = Integer.parseInt(JOptionPane.showInputDialog("Please enter a sentinel value: "));
number = Integer.parseInt(JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" value to end."));
And remove:
number = input.nextInt();
sentinel=input.nextInt();
I think the confusion is this:
the JOptionPane opens with an input dialog
when the option pane closes, whatever you put there is ignored
then the code goes to this line sentinel=input.nextInt();
which waits for input from the console (e.g. you need to go back to the console, type the number there and press enter, only then the program will advance, it will block untill you do)
I would change it to something like this:
String sentinelInput = JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel= Integer.parseInt(sentinelInput);
(repeat for all places where you expect input)
An alternative solution is
Don't use the JOptionPane, and instead just System.out.println to print the user a request for input (instead of the popup dialog). Then you can and keep the existing input.nextInt() calls to collect it.
Just note that all interaction will be in the console, without any popup dialogs (which I actually prefer in terms of user experience, and also it will be working in non GUI machines such as a linux terminal...)

Scanner not detecting empty line and Counter not accurate

This should be a very basic program but I'm new to Java. I want to be able to input multiple strings into the console using Scanner to detect them. So far I've been able to get the input part right, I wanted the program to run in such a way that the results are displayed when an empty space is entered as opposed to a string. Strangely enough I've only been able to get results when i hit return twice, however, when there are more than 4 inputs hitting return once works. My counter should count the number of "Courses" entered and display them in the results but it gives inaccurate readings.
import java.util.Scanner;
public class Saturn
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("For each course in your schedule, enter its building");
System.out.println("code [One code per line ending with an empty line]");
String input;
int counter = 0;
while (!(userInput.nextLine()).isEmpty())
{
input = userInput.nextLine();
counter++;
}
System.out.println("Your schedule consits of " + counter + " courses");
}
}
You're calling Scanner#nextLine twice - once in the while loop expression and again in the body of the loop. You can just assign input from the while loop expression. In addition you can use Scanner#hasNextLine to defend against NoSuchElementException occurring:
while (userInput.hasNextLine() &&
!(input = userInput.nextLine()).isEmpty()) {
System.out.println("Course accepted: " + input);
counter++;
}

Categories

Resources