how to prompt user to break in a for loop? - java

package task;
import java.util.*;
public class Task {
public static void main(String[] args) {
System.out.println("Enter \"t\" to terminate.");
for(;;){
Scanner input = new Scanner(System.in);
int i;
double I = Double.POSITIVE_INFINITY;
for(i = 0; i <= I; i++){
System.out.println("Integer " + i);
String a = input.next();
if(a.equals("c")){
break;
}
}
}
}
}
I am having trouble in prompting the user to enter "t" to end the for loop. I basically want the for loop to print out every single positive integer, and when I decide to end, I enter "t".
If I could get some help, I'd appreciate it. Thanks!

You could simply use a do while instead of a for+break
Do while :
System.out.println("Enter \"t\" to terminate.");
Scanner input = new Scanner(System.in);
String pressed;
int i = 0;
while (true) {
i=0;
do {
System.out.println("Integer " + i);
pressed = input.next();
i++;
} while (!pressed.equals("t"));
}
Note that you are not testing if the input is an integer.

Related

Scan a number of names, print names (number==amount of names) and print Hello to each of them

I am new to Java and have a task: Scanner a number of "strangers' " names, then read these names and print "Hello+name" to the console. If number of strangers is zero, then print "Looks empty", if the number is negative, then print "Looks negative to me".
So the input and output to console should look like this:
3
Den
Ken
Mel
Hello, Den
Hello, Ken
Hello, Mel
So I have this code edited from someone with some related task, but it seems I miss something as I am new to Java...
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
while (num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
} while (num<0) {
System.out.println("Seriously? Why so negative?");
break;
}
String[] numbers = new String[num];
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +input.nextLine());
}
With using do while loop you can ask the number to the user again and again if it is negative number.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int num;
String name;
Scanner scan = new Scanner(System.in);
//The loop asks a number till the number is nonnegative
do{
System.out.print("Please enter the number of strangers: ");
num = scan.nextInt();
if(num<0) {
System.out.println("It cannot be a negative number try again.");
}else if(num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
}else{
String[] strangers = new String[num];
//Takes the names and puts them to the strangers array
for(int i=0;i<num;i++) {
System.out.print("Name " + (i+1) + " : ");
name = scan.next();
strangers[i] = name;
}
//Printing the array
for(int j=0; j<num; j++) {
System.out.println("Hello, " + strangers[j]);
}
break;
}
}while(num<0);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
if(num==0) {
System.out.println("Oh, it looks like there is no one here");
}
else if(num<0) {
System.out.println("Seriously? Why so negative?");
}
else {
String numbers[] = new String[num];
input.nextLine();
for (int i=0; i< num;i++) {
numbers[i]=input.nextLine();
}
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +numbers[i]);
}
}
}
}
This is how your code will look and you'll need to add member function input.nextLine(); to read newline character, so there can't be problem regarding input

get script to run again if user input is yes in java

I need help making it so that the entire script will loop from the beginning if the user types y at the end and the script ends if the user types n at the end. Thanks for any help.
package test123;
import java.util.Scanner;
public class test321 {
public static void main(String[] args) {
int n = 1;
int c;
String playAgain;
do {
System.out.println("Enter a number");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
if ( n < 0 )
System.out.println("Number cant be a negative.");
else
{
int x=n*(n-1)*(n-2);
System.out.println("Factorial= "+x);
System.out.println("Do you want to continue? (y/n):");
playAgain = scanner.nextLine();
}while (!playAgain.equals("y"));
}
}
}
package test123;
import java.util.Scanner;
public class test321 {
public static void main(String[] args) {
int n = 1;
int c;
String playAgain;
do {
System.out.println("Enter a number");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
if ( n < 0 )
System.out.println("Number cant be a negative.");
else
{
int x=n*(n-1)*(n-2);
System.out.println("Factorial= "+x);
System.out.println("Do you want to continue? (y/n):");
playAgain = scanner.nextLine();
} // end else
} // end do
while (playAgain.equals("y"));
}// end main
} // end class
Change
while (!playAgain.equals("y"));
to
while (!playAgain.equals("n"));

Using a for loop, display the number of entries and the sum in Java

so I was asked to create a program in which the user enters four integers and then displays the number of entries and the sum of the integers using a for loop. This is what I came up with.
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int sum = 0;
int count = 0;
for (int i = 0; i != 4 ; i++)
{
System.out.println(" Enter an integer: ");
int num = in.nextInt();
sum = sum + num;
count = count + 1;
}
System.out.println("Number of entries: " + count);
System.out.println("Total sum of entries: " + sum);
}
}
I was wondering what a cleaner way was to ask the user for the four numbers using a for loop, and what other people might suggest be best for this situation. Thanks for any input, p.s. (I have just started learning!)
i think you are looking something like this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum=0;
for(int i=0;i<4;i++){
System.out.println("ENter Number"+(i+1));
sum += sc.nextInt();
}
System.out.println("the Sum is "+sum);
sc.close();
}
You can check with enter. If user presses enter, you can break.
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey.equals("")){
break;
}
Have a look at this solution. I cleaned it up a bit. Maybe you will find some design decisions I made which will help you in the future:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int sum = 0;
for (int count = 1; count <= 4; count++) {
System.out.print(String.format("Please enter %d. integer: ", count));
sum = sum + readNumber(scanner);
}
System.out.println("The sum of numbers entered is: " + sum);
}
}
private static int readNumber(Scanner scanner) {
do {
String input = scanner.nextLine();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.print(String.format("Input %s is not a valid integer. Try again: ", input));
}
} while (true);
}
As you're a beginner it's the best way for getting input from the user in console. But you are for the condition should be like:
for ( int i =0;i < 4 ; i ++){}

Strict integer-only if/then loops

Using Java to compile a code that takes in any input, from strings to doubles, floats, integers, etc., but can only process based on integers. If it receives a double, float, or a string, it will just produce a message prompting the user to try again. I'm not sure exactly how to get this rolling, so here's my current code.
import java.util.Scanner;
public class Sand
{
public static void main(String[] args)
{
int firstInt, secondInt, thirdInt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hi. I'm going to be asking you for three integers in just a moment.");
System.out.println("An integer is defined as a WHOLE number that's not a fraction or decimal.");
System.out.println("I swear to you, I will go off if you put in a non-whole number...");
System.out.println("Okay go ahead and type in the first of the three integers:");
if (keyboard.hasNextInt())
{
firstInt = keyboard.nextInt();
System.out.println("Red.");
System.out.println("So the first integer is " + firstInt);
System.out.println("Okay go ahead and type in the second of the three integers: ");
if (keyboard.hasNextInt())
{
secondInt = keyboard.nextInt();
System.out.println("Green.");
System.out.println("So the first and second integers are " + firstInt + " and " + secondInt);
}
else
{
System.out.println("Orange.");
System.out.println("Please try again.");
}
}
else
{
System.out.println("Blue.");
System.out.println("Please try again.");
}
}
}
I have orange and blue representing times in which there are some input errors, but it's not complete. I'm not sure how to approach this, be it a while loop or a for loop or a try/catch. I'm new when it comes to learning Java so some #notes would be helpful along the way. The code is to designed to read three numbers that are integers from the user in a string. That's straightforward, but analyzing the input is where I'm struggling.
This is not meant to answer your question totally but to point you in the right direction. There should be enough here to help you figure out what else is needed for your program.
import java.util.Scanner;
public class Sandbox {
// arguments are passed using the text field below this editor
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = 0;
System.out.println("enter an integer");
while (true) { //keep prompting the user until they comply
try {
num = Integer.parseInt(keyboard.nextLine());
keyboard.close();
break;
} catch (NumberFormatException e) {
System.out.println("You must enter an integer");
}
}
System.out.println("num: " + num);
}
}
I, personally, would use an array or arrayList (based on your needs) to store the int values and then use a while loop to check and accept the numbers. while (array.length < 3) do {int checking}. This way the script will not run if there are already 3 values in the array and will run until you get 3 values.
this should do the job..
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] intArray = new int[3];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
System.out.print("input integer #"+(i+1)+": ");
if (keyboard.hasNextInt()) {
intArray[i] = keyboard.nextInt();
System.out.println("value for #"+(i+1)+": " + intArray[i]);
} else
{
System.out.println("not an integer");
break;
}
}
keyboard.close();
}
}
or maybe another solution that asks again when the number was no integer
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
int[] intArray = new int[3];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
boolean isInputCorrect = false;
do {
System.out.print("input integer #" + (i + 1) + ": ");
if (keyboard.hasNextInt()) {
intArray[i] = keyboard.nextInt();
System.out.println("value for #" + (i + 1) + ": " + intArray[i]);
isInputCorrect = true;
} else {
System.out.println("not an integer, try again");
keyboard.nextLine();
}
} while (!isInputCorrect);
}
keyboard.close();
}
}

how to take user input in Array using java?

how to take user input in Array using Java?
i.e we are not initializing it by ourself in our program but the user is going to give its value..
please guide!!
Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
See also:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
import java.util.Scanner;
class bigest {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("how many number you want to put in the pot?");
int num = input.nextInt();
int numbers[] = new int[num];
for (int i = 0; i < num; i++) {
System.out.println ("number" + i + ":");
numbers[i] = input.nextInt();
}
for (int temp : numbers){
System.out.print (temp + "\t");
}
input.close();
}
}
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.
Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.
If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.
Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();

Categories

Resources