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]);
}
}
}
Related
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));
I have an array of 8 strings
(Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi")
all referenced by "county"
I'd prompt the user to input a number of 1-8 (iVal), 1 being Carter, 2 being Cocke, etc...
Is there a way I could do this other than using a switch statement?
Also, how would I go about this if the user were to input Washington I'd display "Washington is in the array" and the opposite if the string isn't in the array?
Thanks in advance.
Here is my array.
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
for (int i = 0; i< county.length; i++)
{
System.out.print (county [i]+ "\n");
}
To prompt the user to enter a county, and then display it (without a switch) is simple enough. You could use something like,
String[] county = { "Carter", "Cocke", "Washington", "Greene",
"Hawkins", "Johnson", "Sullivan", "Unicoi" };
Scanner scan = new Scanner(System.in);
for (int i = 0; i < county.length; i++) {
System.out.printf("%d %s%n", i + 1, county[i]);
}
System.out.println("Please select a county from above: ");
int choice = scan.nextInt();
if (choice > 0 && choice <= county.length) {
System.out.println("You selected: " + county[choice - 1]);
} else {
System.out.println("Not a valid choice: " + choice);
}
As for testing if a String array contains a particular String you could write a utility function using the for-each loop like
public static boolean contains(String[] arr, String val) {
if (arr != null) {
for (String str : arr) {
if (str.equals(val)) {
return true;
}
}
}
return false;
}
i was working on the same thing, use ArrayList. this was my code
import java.util.*;
public class Practice{
public static void main(String[] args){
ArrayList<String> mylist = new ArrayList<>();
mylist.add("Maisam Bokhari");
mylist.add("Fawwad Ahmed");
mylist.add("Ali Asim");
mylist.add("Maheen Hanif");
mylist.add("Rimsha Imtiaz");
mylist.add("Mugheer Mughal");
mylist.add("Maaz Hussain");
mylist.add("Asad Shahzada");
mylist.add("Junaid Khan");
System.out.println("Name of the student: "+mylist);
}
}
now if u want a specific name from the list put this in system.out.println
System.out.println("Name of the student: "+mylist.get(1));
now the trick is to let the user enter the number in get( )
for this i made this program, here is the code
first make a scanner
Scanner myScan = new Scanner(System.in);
int a = myScan.nextInt();
System.out.println("Name of the student: "+mylist.get(a));
now it will only print that name depending on what number user have entered !!
I didn't understand well your questions, but I am going to answer on what I have understand.
In case you want to print the value of a given index by the user here is the solution:
Try an i with correct (existing) index and another one which does not exist e.g i=9
public class app
{
public static void main(String[] args)
{
String [] county ={"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
int i = 10; //i is the user input, you should do that using a BufferedReader or Scanner.
try
{
System.out.println(county[i-1]);
}
catch(IndexOutOfBoundsException e)
{
System.out.println("This index doesn't exist");
}
}
}
In case you want to check if a given word exist you can do it that way:
Again try a string which exist and one which does not exist.
public class app
{
public static void main(String[] args)
{
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
String word = "Cocke"; //word is the user input, you should do that using a BufferedReader or Scanner.
boolean found = false;
for(int i=0; i<=7; ++i)
{
if(word == county[i])
{
found = true;
break;
}
}
if(found == true)
{
System.out.println(word + " is in the array.");
}
else
{
System.out.println(word + " is not in the array.");
}
}
}
I have to write a program having 3 parallel arrays one that holds 4 digit student ID the second the student Name and the last one that holds the GPA and the size of the arrays have to be 10
also the program be able to do a Student ID search and if it doesnt exist to show an error message
the first part works fine but when it comes to the searching it doesnt work
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.util.Scanner;
public class StudentIDArray
{
public static void main(String[] args)
{
int option;
String inputString;
inputString = JOptionPane.showInputDialog("Welcome"
+" Choose the option you will like"
+ " \n1. Enter Student Information "
+ "\n2. Search for Student");
option = Integer.parseInt(inputString);
if(option ==1)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the Student");
String[] studentname = new String[10];
for(int i =0; i<studentname.length; i++)
{
studentname[i] = in.nextLine();
}
System.out.println("Enter the 4 digit Student ID");
int[] studentID = new int[10];
for(int x=0; x<studentID.length; x++)
{
studentID[x] = in.nextInt();
}
System.out.println("Enter the Student's Grade Point Average");
int[] gpa = new int[10];
for(int y=0; y<studentID.length; y++)
{
gpa[y] = in.nextInt();
}
}
else
{
searching();
}
}
public static void searching()
{
int idnumber,
results;
int[]studentID = null;
String inputString;
inputString = JOptionPane.showInputDialog("Please Enter the ID number");
idnumber = Integer.parseInt(inputString);
results = sequentialSearch(studentID, idnumber);
if (results == -1)
{
System.out.println("no information");
}
else
{
System.out.println("yeii congrats");
}
}
public static int sequentialSearch(int[] studentID, int value)
{
int index;
int element;
boolean found;
index =0;
element = -1;
found = false;
while(!found && index < studentID.length)
{
if (studentID[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
}
The primary issue is that you are declaring the studentID array locally to your methods.
Make it a class member instead (an instance member would be preferred, but all your methods are static), so that your methods are working on the same array, not on different ones:
public class StudentIDArray
{
private static int[] studentID = new int[10];
...
Note that this limits the number of entries to the size of the array and you will get exceptions if you exceed these limits. Consider using a Vector or an ArrayList instead.
searching(studentID);
Pass the studentID array to the searching method instead of declaring it again.
public static void searching(int[] studentID)
{
int idnumber,
results;
//int[]studentID = null;
String inputString;
inputString = JOptionPane.showInputDialog("Please Enter the ID number");
idnumber = Integer.parseInt(inputString);
results = sequentialSearch(studentID, idnumber);
if (results == -1)
{
System.out.println("no information");
}
else
{
System.out.println("yeii congrats");
}
}
public static int sequentialSearch(int[] studentID, int value)
{
int index;
int element;
boolean found;
index =0;
element = -1;
found = false;
while(!found && index < studentID.length)
{
if (studentID[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
A better approach would be to keep it as a static/class variable as #Andreas pointed out.
These are the Running Steps of Program....
First Step => Enter Size of Array.
Second Step => Enter Member of Array.
Third Step => Enter Searching Integer of Array.
import java.util.Scanner;
public class Searching
{
public static void main(String[] args)
{
int temp =-1;
Scanner user_input=new Scanner(System.in);
System.out.println("Enter Size Of Array ");
int Size=user_input.nextInt();
int[] a=new int[Size];
//Scan input Array.
System.out.println("Enter element Of an Array...");
for(int j=0;j<Size;j++)
{
a[j]=user_input.nextInt();
}
System.out.println("The contents of the Array are :");
//Print input Arrray
for(int i=0;i<a.length;i++)
{
System.out.println("array[" + i + "] = " + a[i]);
}
System.out.println("Enter Integer For Searching..");
int Search=user_input.nextInt();
//Searching in an Array.
for(int index=0;index<a.length; index++)
{
if(a[index]==Search)
{
temp=index;
break;
}
}
if(temp!=-1)
{
System.out.println(" The search element is : " + Search);
System.out.println(" It is found in the array at position : " + temp);
}
else
System.out.println("\n Element not Found..");
}
}
So far, my code looks like this:
package kittensworld;
import java.util.Scanner;
public class KittensWorld {
public static void main(String[] args){
System.out.println("What is the first kitten's name?");
Scanner scan = new Scanner(System.in);
String kitten1 = scan.nextLine();
System.out.println("What is the second kitten's name?");
String kitten2 = scan.nextLine();
System.out.println("And the third kiten's name?");
String kitten3 = scan.nextLine();
System.out.println("The first kitten's name is " + kitten1);
System.out.println("The second kitten is " + kitten2);
System.out.println("And last but not least, " + kitten3);
}
}
How would I go about looping it so that I can ask for the names of 20 kittens, without copying and pasting it 20 times?
Use for loop and array that'll contain the data:
String[] inputs = new String[NUMBER_OF_INPUTS];
Scanner scanner = new Scanner();
for(i=0; i<NUMBER_OF_INPUTS; i++) {
inputs[i] = scanner.nextLine();
}
If you don't know the number of inputs (but you know what symbol will represent the end of the input), you can use a while loop and an ArrayList.
I think you need to look up this tutorial about this proper loop called for-loop:
String[] kitten = new String [size];
for(int i = 0 ; i < kitten.length; i++){
System.out.println("kitten number "+i+" : ");
kitten [i] = scan.nextLine();
}
package kittensworld;
import java.util.Scanner;
public class KittensWorld {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 20; i++){
System.out.println("What is the kitten's name?");
String kitten = scan.nextLine();
System.out.println("That kitten's name was " + kitten);
}
}
}
package kittensworld;
import java.util.Scanner;
public class KittensWorld {
private static final int NUMBER_OF_KITTENS = 20;
public static void main(String[] args){
String[] kittenNames = new int[NUMBER_OF_KITTENS];
Scanner scan = new Scanner(System.in);
for(int i = 0; i < NUMBER_OF_KITTENS; ++i)
{
System.out.println("What is the name of kitten number " + (i+1) + "?");
kittenNames[i] = scan.nextLine();
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> kittenNames = new ArrayList<>();
int number = 3 ; // number of kitten names ( +1 )
for (int i = 1; i < number; i++) {
System.out.printf("What is the %s kitten's name?\n", ordinal(i));
kittenNames.add(scan.nextLine());
}
System.out.println("===============================================");
for (String name : kittenNames) {
System.out.println(name);
}
}
public static String ordinal(int i) {
String[] sufixes = new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
switch (i % 100) {
case 11:
case 12:
case 13:
return i + "th";
default:
return i + sufixes[i % 10];
}
}
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();