For java practice, i am trying to create a program that reads integers from the keyboard until a negative one is entered.
and it prints the maximum and minimum of the integer ignoring the negative.
Is there a way to have continuous input in the same program once it runs? I have to keep running the program each time to enter a number.
Any help would be appreciated
public class CS {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = keys.nextInt();
while(true)
{
if(n>0)
{
System.out.println("Enter again: ");
n = keys.nextInt();
}
else
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
}
Here is a part of my code - It works, but i think there is an easier way of doing what i want but not sure how!
import java.util.Scanner;
public class ABC {
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Feed me with numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Keep Going!");
}
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
You could do something like:
Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
//do something
}
This will make num equal to the next integer, and check if it is greater than 0. If it's negative, it will fall out of the loop.
A simple loop can solve your problem.
Scanner s = new Scanner(System.in);
int num = 1;
while(num>0)
{
num = s.nextInt();
//Do whatever you want with the number
}
The above loop will run until a negative number is met.
I hope this helps you
Related
I'm trying to make a simple program where you can put integers in, and it will tell you if it increased or decreased from the previous integer input. But when I run the code, I have to put an integer value twice, but I only want it put once.
The input and output should look like (numbers typed by me, words output by the program):
Starting...
5
Increasing
4
Decreasing
6
Increasing
etc. etc.
But instead it looks like:
Starting...
5
5
Increasing
Input Number:
1
2
Not Increasing
etc. etc.
This is my code:
import java.util.Scanner;
public class Prob1 {
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (!(scan.nextInt() <= 0)) {
input = scan.nextInt();
if (input > previousInput) {
System.out.println("Increasing");
previousInput = input;
} else {
System.out.println("Not Increasing");
previousInput = input;
}
System.out.println("Input Number:");
}
scan.close();
}
}
Why does this problem occur, and how can I fix it?
The loop behavior you are describing is:
read a numeric input value
do something with it (print a message)
if the loop value meets a condition (input is 0 or less), exit the loop
otherwise, repeat
Here's a "do-while" loop that reads like those steps above:
Scanner scan = new Scanner(System.in);
int input;
do {
input = scan.nextInt();
System.out.println("input: " + input);
} while (input > 0);
System.out.println("done");
And here's input+output, first entering "1", then entering "0":
1
input: 1
0
input: 0
done
while (!(scan.nextInt() <= 0)) { takes an int and then input = scan.nextInt(); takes another one. You need to change the while loop to use input.
modified based on your code
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Input Number:");
input = scan.nextInt();
if (input <= 0) {
System.out.println("app shut down");
break;
}
if (input > previousInput) {
System.out.println("Increasing");
} else {
System.out.println("Not Increasing");
}
previousInput = input;
}
scan.close();
}
I am trying to write a program to read a series of numbers from the user until -1 is entered. It should then print the average (with decimals) of those numbers (not including the -1). This is what I have so far, but it does not seem to work properly whenever I input -1. This is what I have thus far:
import java.util.Scanner;
import java.util.*;
public class Tute1
{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many numbers you want: ");
int numb = sc.nextInt();
int i =0;
int total =0;
while (i <= numb) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer ");
int myChoice=scan.nextInt();
total=total+myChoice;
i=i+1;
if(myChoice == -1) {
System.out.println("The average is "+ (total+1)/numb);
break;
}
}
System.out.println("The average is "+ total/numb);
}
}
Your code seems a bit odd. Here is how I would do it
import java.util.Scanner;
import java.util.*;
public class Tute1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int total = 0;
while (true) {
System.out.println("Enter an integer ");
int myChoice = scan.nextInt();
if (myChoice != -1) {
total = total + myChoice;
i += 1;
} else {
break;
}
}
float average = total / i;
System.out.println("The average is " + average);
}
Hope this helps. You can add try-catch and stuff to make it so that user does not exploit this
Few things:
first of all you dont need to create a new scanner as your code inside the while loop. Its because the while loop is inside you function scope so every thing you declare on you function the while loop knows about. (It does not work the other way around)
second your breaking condition should be inside the while loop the if with break is redundant and unnecessary.
third thing you should get rid of numb as its doing nithung
import java.util.Scanner;
import java.util.*;
public class Tute1 {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int numb = sc.nextInt();
int i =0;
int total =0;
while (numb != -1)
{
total=total+numb;
i=i+1;
int numb = sc.nextInt()
}
System.out.println("The average is "+ total/i);
}
}
I think this solution is smaller and more elegant
This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 3 years ago.
The goal of this is to let the user enter a number per line and when the user no longer wish to continue they should be able to enter a empty line and when that happens the program should you give you a message with the largest number.
Problem is I can't make the loop break with an empty line. I'm not sure how to. I've checked other questions for a solution but I couldn't find anything that helped. I also can't assign scan.hasNextInt() == null....
I'm sure there is a quick and logical solution to this that I'm not thinking of.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
while(scan.hasNextInt()){
int n = scan.nextInt();
if (n > x){
x = n;
}
}
System.out.println("Largets number entered: " + x);
}
}
This should solve your problem:
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
try {
while(!scan.nextLine().isEmpty()){
int num = Integer.parseInt(scan.nextLine());
if(num > x) {
x = num;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Largest number entered: " + x);
scan.close();
}
}
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
String str = scanner.nextLine();
int x = 0;
try {
while(!str.isEmpty()){
int number = Integer.parseInt(str);
if (number > x){
x = number;
}
str = scanner.nextLine();
}
}
catch (NumberFormatException e) {
System.out.println("There was an exception. You entered a data type other than Integer");
}
System.out.println("Largets number entered: " + x);
}
}
I'm working on a question and I'm new to programming, so I'm not that familiar with a few concepts. The question asks the user to input an initial number, followed by a list of that many numbers. The program should then print back how many of the numbers entered were negative.
For example, I first input 5, followed by 5 other random numbers.
5
6,-9,28,-32,-1
The output should be
3
So far all I have is:
class main
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++)
{
System.out.println(i);
if(i<0)
{
c++;
}
}
System.out.println(c);
}
}
I'm really confused. Can someone offer an explanation as to how the code works?
You can read the positive integers inside for loop from the given inputs and then check if that each input integer is greater than or equal to zero:
scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int c=0;
for(int i = 1; i <= input; i++) {
int num = scan.nextInt();
if(num>=0)
{
System.out.println(num);
}
}
I'm writing some Java code that'll make a guessing game, where a random number is generated based on your maximum value and you have to guess the correct number. You can also set the amount of attempts you can get. This is where the problem occurs.You see, you can set a number of attempts in number form or write out "unlimited". I have an example of the code that does this here with comments to help you out:
import java.util.Scanner;
public class Game{
public static int processMaxAttempts;
public static Scanner maxAttempts;
public static String processMaxAttempts2;
public static void main(String args[]){
//Prints out text
System.out.println("Fill in your maximum attempts OR write \"unlimited\".");
//Creates a scanner
maxAttempts = new Scanner(System.in);
//Looks at the scanner "maxAttempts" and reads its integer value
processMaxAttempts = maxAttempts.nextInt();
//Looks at the scanner "maxAttempts" and reads its string value
processMaxAttempts2 = maxAttempts.nextLine();
//Prints out "unlimited" if "maxAttempts" has a string value and "set" if it has an integer value
if(processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}//Close else
}//Close main method
}//Close class
What happens is a get an error that says this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at com.pixelparkour.windows.MainGameWindow.main(MainGameWindow.java:34)
That error targets this line of code:
processMaxAttempts = maxAttempts.nextInt();
So... yeah. I have no idea. I'm very new to Java (I've been learning it for only 3 days) and I'm a bit helpless. I'd love to know what my problem is so I can apply to it the future and program some cool games!
You need to put a check on content type before reading the content.
What you need is :
if(maxAttempts.hasNextInt()){ // this will check if there is an integer to read from scanner
processMaxAttempts = maxAttempts.nextInt();
} else {
processMaxAttempts2 = maxAttempts.nextLine();
}
if(processMaxAttempts2!=null && processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}
I think this is what you are looking for
public class Test
{
private int guessableNumber;
private Integer maxAttempts;
public Test()
{
maxAttempts = 0;
}
public void doYourStuff(){
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("Please enter your amount of guesses or type unlimited for unlimited guesses");
String s = scan.next();
if(s.toUpperCase().equals("UNLIMITED")){
guessableNumber = random.nextInt(100);
}
else {
try{
maxAttempts = Integer.parseInt(s);
guessableNumber = random.nextInt(100) + Integer.parseInt(s);
}catch(Exception e){
System.out.println("You did not enter a valid number for max attempts");
}
}
int counter = 0;
System.out.println("Type in a guess");
while(scan.nextInt() != guessableNumber && counter <=maxAttempts){
System.out.println("You did not guess correctly try again");
++counter;
}
if(counter > maxAttempts){
System.out.println("You have exceeded your max attempts");
}
else {
System.out.println("Correct you guessed the correct number: "+ guessableNumber);
}
}
public static void main(String[] args)
{
Test test = new Test();
test.doYourStuff();
}
}
One little trick that always works for me is just going ahead and making a second scanner, i.e. num and text, that way you can always have one looking for int values and the other dealing with the Strings.