Java iterate through array [duplicate] - java

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am trying to write a java program with 2 arrays 1 for name (String) and the other representing age (integer) the program should iterate and ask for a max of 10 names and ages of each, then display all array items as well as max and min ages of each, or unless the user enters 'done' or 'DONE' mid-way through.
I have the following code although struggling to loop around and ask user for names and ages x10.
Any suggestions?
Thank you.
import java.util.Scanner;
public class AgeName {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int numTried = 1;
int ageTried = 1;
boolean stop = false;
String name = "";
String[] num = new String[10];
int[] age = new int[10];
while(numTried <= 10 && ageTried <=10 && !stop){
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
if(name.toUpperCase().equals("DONE")){
stop = true;
}else{
num[numTried - 1] = name;
age[ageTried -1] = userAge;
}
numTried ++;
ageTried ++;
}
for(String output : num){
if(!(output == null)){
System.out.print(output + "," );
}
}
input.close();
}
}

You can use a Map<String,Integer>:
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] num = new String[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
num[i] = name;
map.put(name, userAge);
}
for (String output : num) {
if (!(output == null)) {
System.out.print(output + ","+ map.get(output));
}
}
Map as its name suggests allows you to map one object type to another. the .put() method adds a record that contains a pair of String and an integer and maps the string to the int. The String has to be UNIQUE!!

You should ask in any iteration if the user is done. For example you could set a string variable as answer = "NO", and ask the user at the end of any iteration if he is done. If you try this remember to replace stop variable with answer at your iteration block condition.
System.out.println("Are you done: Choose -> YES or NO?");
answer = input.nextLine();
if (answer == "YES")
break;

Related

comparing user inputs in array to make sure they dont have the same name in java

What am I missing it keeps, coming back false on the first try. What do I need to change to make sure it scans to get rid of duplicates.
final int numPassengers = 4;
final int numShips = 2;
boolean input = false;
String[] travelerNames = new String[4];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < numPassengers; ++i) {
System.out.println("Enter traveler name ");
do {
travelerNames[i] = scanner.nextLine();
if(travelerNames[i].equals(travelerNames[i])) {
System.out.println("Names cannot match enter new name!");
input = false;
scanner.next();
}
else {
input = true;
}
} while(!input);
System.out.println(travelerNames[i]);
A simple solution would be to use an arraylist.
Arraylist has a method called contains.
List<String> names = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if(names.contains(input)){
System.out.println("Name is duplicated");
}
else {
names.add(input);
}
I hope i could help you with your Problem
travelerNames[i] = scanner.nextLine(); Whoops... too late, it's already within the Array and it's in there before you get to check and see if it has been previously entered. Don't save a step here by popping the name into the Array right away, put the name into a String variable first then traverse the Array to see if that name already exists, for example:
for (int i = 0; i < numPassengers; ++i) {
String name = "";
while(name.isEmpty()) {
System.out.print("Enter traveler name #" + (i + 1) + ": -> ");
name = scanner.nextLine().trim();
if (name.isEmpty() || name.matches("\\d+")) {
System.out.println("Invalid Name Supplied! ("
+ name + ") Try again...\n");
name = "";
continue;
}
// Is the name already within the travelerNames[] Array?
for (String nme : travelerNames) {
if (nme != null && nme.equalsIgnoreCase(name)) {
System.out.println("Invalid Entry! The name '" + name
+ "' already exists! Try again...\n");
name = "";
break;
}
}
}
// Everything seems OK so add the name to the Array.
travelerNames[i] = name;
}
System.out.println();
System.out.println("The names contained within the Array:");
System.out.println(Arrays.toString(travelerNames));

Using variables outside while loops in java

I'am trying to write a program in Java that collects users favorite names within an array and then prints these names at the end.
NOTE: the length of the array should be defined by the number of names a user enters.
Please take a look at the code and tell me how to fix it. Here is what I have done so far
Scanner input = new Scanner(System.in);
System.out.println("What are your most favorite names?");
String[] favNames = new String[i];
int i = 1;
while (true){
System.out.print("Please enter favorite name number" + i + ": ");
favNames[i-1] = input.next();
System.out.print("Is that all?");
String ans = input.next().toLowerCase();
if(ans.startsWith("y")){
System.out.print("Here is the completed list of your favorite names:\n" + Arrays.toString(favNames));
break;
}
i++;
}
This is the error code I get:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: variable i
location: class JavaApplication13
at JavaApplication13.main(JavaApplication13.java:52)
Java Result: 1
I tried moving the first parts of the code inside the loop but it only prints one of the names the user enters.
//These parts:
String[] favNames = new String[i];
int i = 1;
If I swap the places between the first and second line. The array gets only 1 entry from the user.
//Only gets one entry
int i = 1;
String[] favNames = new String[i];
Variables should be declared before use. This is why your program is not working.
Change
String[] favNames = new String[i];
int i = 1;
To
int i = 1;
String[] favNames = new String[i];
But, keep in mind that in this case the used can only input 1 time(because arrays have fixed size). If you want to use an arbitrary number of input, you have to use ArrayList or similar types.
declare variables before using them:
int i = 1;
String[] favNames = new String[i];
However, an array of size 1, will only work for 1 entry. If you would like the user to be able to enter more than that you need a bigger array.
I would suggest an arbitrarily large size (say 100), then check that the entry fits in the array; if it doesn't, game over.
String[] favNames = new String[100];
int i = 1;
while (true) {
System.out.print("Please enter favorite name number" + i + ": ");
favNames[i - 1] = input.next();
System.out.print("Is that all?");
String ans = input.next().toLowerCase();
if (ans.startsWith("y")) {
System.out.print("Here is the completed list of your favorite names:\n" + Arrays.toString(favNames));
break;
}
i++;
if (i > favNames.length)
System.out.print("Can't accept more than "+favNames.length+" entries, here is the completed list of your favorite names:\n" + Arrays.toString(favNames));
}
The issue then is that Arrays.toString will print null for the empty entries.
I would make a custom routine to print the array that ends on the first null:
static String printFavNames(String[] favNames) {
String output = "[";
for (String s : favNames) {
if (s==null)
break;
if (output.length() > 1)
output += ", ";
output += s;
}
output += "]";
return output;
}
related question: How to print all non null elements of an array using Array.toString()
full code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What are your most favorite names?");
String[] favNames = new String[100];
int i = 1;
while (true) {
System.out.print("Please enter favorite name number" + i + ": ");
favNames[i - 1] = input.next();
System.out.print("Is that all?");
String ans = input.next().toLowerCase();
if (ans.startsWith("y")) {
System.out.print("Here is the completed list of your favorite names:\n" + printFavNames(favNames));
break;
}
i++;
if (i > favNames.length)
System.out.print("Can't accept more than "+favNames.length+" entries, here is the completed list of your favorite names:\n" + printFavNames(favNames));
}
input.close();
}
static String printFavNames(String[] favNames) {
String output = "[";
for (String s : favNames) {
if (s==null)
break;
if (output.length() > 1)
output += ", ";
output += s;
}
output += "]";
return output;
}
}
Just move the i++ to inside the while loop and all be good!

Program about how many times the number has been repeated

For example i want to find how many times 1 repeated in number 123900148
It must be write 2 times but i get wrong values for everytime
Scanner input = new Scanner(System.in);
#author Başar Ballıöz
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
for (int i = 0; i < number.length() - 1 ; i++) {
if (number.substring(i , i+1).equals(repeat))
counter++;
}
System.out.println(repeat + " number " + counter + " repeated.");
i would like to see my output like:
number : 134211
number i want to find how many times repeated: 1
your number has repeated 3 times
You are comparing a String (returned by number.substring(i , i+1) to an Integer, so of course it will always return false.
Either compare two ints or two Strings. Since you are essentially comparing two digits, comparing ints would be more efficient.
for (int i = 0; i < number.length(); i++) {
if (Character.getNumericValue(number.charAt(i)) == repeat) {
counter++;
}
}
Scanner input = new Scanner(System.in);
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
while (tmp > 0) {
if (tmp % 10 == repeat) {
counter++;
}
tmp = tmp/10;
}
System.out.println(number + " number " + counter + " repeated.");
You're comparing a String against an Integer via equals hence you're not getting the expected result. instead convert the integer to a string prior to comparison:
if (number.substring(i , i+1).equals(String.valueOf(repeat)))
Further, you could cache the result of String.valueOf(repeat) into a variable before the for loop to prevent a string object construction in each iteration of the loop.
Try this. I added some helpful output so you can see how it's indexed.
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
public class CountChars {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter A String: ");
Map<String, Integer> map = indexString(input.nextLine());
while (true) {
System.out.print("Enter A Character You Want To Count (ENTER to exit): ");
String repeat = input.nextLine();
if (repeat == null || repeat.isEmpty()) {
break;
}
System.out.println(String.format("'%s' was repeated %d time(s).", repeat, (map.containsKey(repeat)) ? map.get(repeat):Integer.valueOf(0)));
}
}
private static Map<String, Integer> indexString(String s) {
Map<String, Integer> map = new HashMap<>();
System.out.println(String.format("'%s' has %d characters. Indexing now.", s, s.length()));
for (int i = 0; i < s.length() ; i++) {
String c = String.valueOf(s.charAt(i));
if (!map.containsKey(c)) {
map.put(c, 0);
System.out.println(String.format("Indexing %s", c));
}
System.out.print(String.format("Incrementing '%s' from %d ", c, map.get(c)));
map.put(c, map.get(c) + 1);
System.out.println(String.format("to %d.", map.get(c)));
}
return map;
}
}

How do I set the conditional statement in this program?

So this code asks for a name and a number 1-20, but if you put in a number over 20 or below 1 the program still runs and I know I need a conditional statement right around figuring out the amount for "ano" to stop and re-ask the statement and re-run the segment but I don't know how to implement it into the code.
// library - for interactive input
import java.util.Scanner;
//---------------------------------
// program name header
public class feb24a
{
//--------FUNCTION CODING ---------------
// FUNCTION HEADER
public static void seeit(String msg, String aname, int ano)
{
// statement to accomplish the task of this function
System.out.print("\n The message is " + msg + "\t" + "Name is:" + aname + "\t" + "number is: " + ano);
// return statement without a variable name because it is a void
return;
}
//------------------- MAIN MODULE CODING TO CALL FUNCTIONS ----------------
// Main module header
public static void main (String[] args)
{
String msg, aname;
int ano, again, a, b;
msg = "Hello";
a = 1;
b = 20;
//Loop control variable
again = 2;
while(again == 2)
{
System.out.print("\n enter NAME: ");
Scanner username = new Scanner(System.in);
aname = username.nextLine();
System.out.print("\n enter number 1-20: ");
Scanner userno = new Scanner(System.in);
ano = userno.nextInt();
seeit(msg, aname, ano);
//ask user if they want to do it again, 2 for yes any other for no
System.out.print("\n do you want to do this again? 2 for yes ");
Scanner useragain = new Scanner(System.in);
again = useragain.nextInt();
} //terminate the while loop
}
}
Replace your while loop with this:
Scanner scanner = new Scanner(System.in);
while (again == 2) {
ano = 0;
System.out.print("\n enter NAME: ");
aname = scanner.nextLine();
while (ano < 1 || ano > 20) {
System.out.print("\n enter number 1-20: ");
ano = scanner.nextInt();
}
seeit(msg, aname, ano);
System.out.print("\n do you want to do this again? 2 for yes ");
again = scanner.nextInt();
}
Try to surround your ano = userno.nextInt() in a while loop. (i.e., while(ano < 1 || ano > 20)) and put a prompt inside that while loop. That way, it will keep reading a new number until it finally no longer fulfills the while loop and will break out.

Java Scanner class reading strings

I've created a scanner class to read through the text file and get the value what I'm after. Let's assume that I have a text file contains.
List of people: length 3
1 : Fnjiei : ID 7868860 : Age 18
2 : Oipuiieerb : ID 334134 : Age 39
3 : Enekaree : ID 6106274 : Age 31
I'm trying to get a name and id number and age, but everytime I try to run my code it gives me an exception. Here's my code. Any suggestion from java gurus?:) It was able to read one single line....... but no more than a single line of text.
public void readFile(String fileName)throws IOException{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
try {
while (input.hasNextLine()){
int howMany = 3;
System.out.println(howMany);
String userInput = input.nextLine();
String name = "";
String idS = "";
String ageS = "";
int id;
int age;
int count=0;
for (int j = 0; j <= howMany; j++){
for (int i=0; i < userInput.length(); i++){
if(count < 2){ // for name
if(Character.isLetter(userInput.charAt(i))){
name+=userInput.charAt(i); // store the name
}else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 2){ // for id
if(Character.isDigit(userInput.charAt(i))){
idS+=userInput.charAt(i); // store the id
}
else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 3){ // for age
if(Character.isDigit(userInput.charAt(i))){
ageS+=userInput.charAt(i); // store the age
}
}
id = Integer.parseInt(idS); // convert id to integer
age = Integer.parseInt(ageS); // convert age to integer
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
userInput = input.nextLine();
}
}
}finally{
if (input != null){
input.close();
}
}
}
My appology if my mere code begs to be changed.
Edited It gives me a number format exception!!!
I dont know how many empty space would be there between these values.
Here's a solution that uses only Scanner API, the important one being findInLine. It can handle minor syntactic variations in the input format, and yet it's very readable, requiring no need for fancy regex or magic array indices.
String text =
"List of ##%^$ people : length 3 !#%# \n" +
"1 : Fnjiei : ID 7868860 ::: Age 18\n" +
" 2: Oipuiieerb : ID 334134 : Age 39 (old, lol!) \r\n" +
" 3 : Enekaree : ID 6106274 => Age 31\n";
Scanner sc = new Scanner(text);
sc.findInLine("length");
final int N = sc.nextInt();
for (int i = 0; i < N; i++) {
sc.nextLine();
sc.findInLine(":");
String name = sc.next();
sc.findInLine("ID");
long id = sc.nextLong();
sc.findInLine("Age");
int age = sc.nextInt();
System.out.printf("[%s] %s (%s)%n", id, name, age);
}
This prints:
[7868860] Fnjiei (18)
[334134] Oipuiieerb (39)
[6106274] Enekaree (31)
API links
Scanner.findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern ignoring delimiters.
Use this Pattern.compile overload if performance is an issue
This seems to be shorter:
public void readFile(String fileName)throws IOException
{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
String userInput;
try
{
while (input.hasNextLine())
{
userInput = input.nextLine().trim();
if (userInput.length() > 0)
{
String[] userInfo = userInput.split(":");
int count = Integer.parseInt(userInfo[0].trim());
String name = userInfo[1].trim();
int id = Integer.parseInt(userInfo[2].trim().split("\\s+")[1].trim());
int age = Integer.parseInt(userInfo[3].trim().split("\\s+")[1].trim());
System.out.println("Count: " + count + " Name: " + name + " ID:" + id + " Age:" + age);
}
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
}
finally
{
if (input != null)
{
input.close();
}
}
}
For the input you have us, it prints this:
Count: 1 Name: Fnjiei ID:7868860 Age:18
Count: 2 Name: Oipuiieerb ID:334134 Age:39
Count: 3 Name: Enekaree ID:6106274 Age:31
More information about the split method can be found here. I basically first split the line by using the : as delimiter, then, I split again using the \\s+, which basically splits a string and return an array containing the words that were separated by white spaces.
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader("filename")));
try{
while(input.hasNextLine()){
String userInput = input.nextLine();
String[] data = userInput.split(":");
System.out.println("Name: "+data[1]+" ID:"+data[2].split("\\s+")[2]+
" Age:"+data[3].split("\\s+")[2]);
}
}finally{
if(input != null)
input.close();
}
Above snippet shows the basic idea.Also please keep in mind that this might not be the optimal solution.

Categories

Resources