Java While loop condition isn't being exicuted - java

I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code:
import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
arr[0] = input.nextLine();
counter++;
do{
arr[counter] = input.nextLine();
if (input.equals("zzz")){
System.out.println("bleh");
}
counter++;
} while (!input.equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}

Replace
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
}
counter++;
with
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
} else {
counter++;
}
and
while (!input.equals("zzz") && counter <= 14)
with
while (!arr[counter].equals("zzz") && counter <= 14)
Explanation: zzz is a string which you have to compare with the input string stored in arr[counter].
Also, in order to avoid NullPointerException, you should perform sort operation on the copy of the array without any null element. Given below is the complete program:
import java.util.Arrays;
import java.util.Scanner;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
do {
System.out.print("Enter item or type 'zzz' to quit: ");
arr[counter] = input.nextLine();
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
} else {
counter++;
}
} while (!"zzz".equals(arr[counter]) && counter <= 14);
arr = Arrays.copyOf(arr, counter);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
A sample run:
Enter item or type 'zzz' to quit: a
Enter item or type 'zzz' to quit: b
Enter item or type 'zzz' to quit: c
Enter item or type 'zzz' to quit: zzz
bleh
Array is [a, b, c]

import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
arr[counter] = input.nextLine();
counter++;
do{
arr[counter] = input.nextLine();
if (arr[counter].equals("zzz")){System.out.println("bleh");}
counter++;
}while (!arr[counter].equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
You meant to compare the input String, not the Scanner object. I also removed your magic number "0" index that you had , since you already set your counter to 0.

The reason your code isn't working is that input is the scanner object, and the equals method on the scanner object doesn't refer to the data being read by it. A way of doing this so that it works would be:
import java.util.*;
public class Help {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
String inputString = null;
System.out.println("Enter item or type 'zzz' to quit");
do{
inputString = input.nextLine();
arr[counter] = inputString;
if (inputString.equals("zzz")){System.out.println("bleh");}
counter++;
}while (!inputString.equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}

input is a Scanner. It will never equal a String.
Try this
Scanner sc = new Scanner(System.in);
String input; // this is now a proper string to compare
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
input = sc.nextLine();
int counter = 0;
while (counter < arr.length) {
if (input.equals("zzz")) return; // check most recently entered input
arr[counter++] = input; // if not returned, store in the list and increase counter
input = sc.nextLine(); // prompt next line
}
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));

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

How do I test the user's input to see if its words are within a specified range

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 have been asked to make an Create a new integer array with 16 elements

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

How do I remove/not display the null values from two arrays?

My code works fine. However the output seems incorrect when I enter -1 from name or age input. How do I remove null values and "-1" and display the existed array?
import java.util.Scanner;
public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);
public final static int arrayLoop = 5;
public static String[] nameList = new String[arrayLoop];
public static int[] age = new int[arrayLoop];
public static void main(String[] args) {
System.out.println("NAME & AGE SYSTEM\n-----------------\n");
for(int i=0; i<arrayLoop; i++) {
System.out.print("Name: ");
nameList[i] = key.nextLine();
if(nameList[i].equals("-1"))
break;
System.out.print("Age: ");
age[i] = keyNum.nextInt();
if(age[i] < 0)
break;
}
System.out.println("----------");
for(int i=0; i<nameList.length; i++) {
System.out.println(nameList[i] + " " + age[i]);
}
}
}
Currently, when you input -1, the loop exits. That is, as soon as you input -1, the loop is not run again. This is because you use the break statement.
If you'd like to let -1 allow the user to start the current entry again, you'll need to do two things:
if (nameList[i].equals("-1")) {
// Take the loop variable down one.
i--;
// Instead of break, continue to the next iteration.
continue;
}
If you want to keep the loop how it is, but only print non-null values, modify your printing code:
for(int i=0; i<nameList.length; i++) {
if (nameList[i] == null || nameList[i].equals("-1") || age[i] < 0) {
// Invalid; go to the next one.
continue;
} else { // (not strictly necessary)
System.out.println(nameList[i] + " " + age[i]);
}
}
Try to use a List instead a Array, something like this:
import java.util.Scanner;
public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);
public final static int arrayLoop = 5;
public static List<String> nameList = new ArrayList<String>();
public static List<Integer> ages = new ArrayList<Integer>();
public static void main(String[] args) {
System.out.println("NAME & AGE SYSTEM\n-----------------\n");
while (true){
System.out.print("Name: ");
String name = key.nextLine();
if(name.equals("-1"))
break;
System.out.print("Age: ");
Integer age = keyNum.nextInt();
if(age < 0)
break;
nameList.add(name);
ages.add(age);
}
System.out.println("----------");
for(int i=0; i<nameList.length; i++) {
System.out.println(nameList[i] + " " + age[i]);
}
}
}

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