So i got a programm that asks the user to type in the 3 favorite cities ,
it stores them in Array and prints them later out to the user. What im trying to do now is
making the programm ask the user for how many favorite cities he/she got?the user types in
a number wich will give the user the oppertunity to type in that ammount of favorit cities
and later on print them out.
Problem is i really have no idea how to do this could anyone help?
Please explain the code incase you help so i can understand :) , Sorry for my bad English not my
primary language!
My code atm looks like this :
package com.example.array.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
String[] favoritCity = new String [3];
Scanner scanner1 = new Scanner (System.in);
System.out.println("skriv in 3 favoritstäder");
String userIn1 = scanner1.nextLine();
String userIn2 = scanner1.nextLine();
String userIn3 = scanner1.nextLine();
favoritCity[0] = userIn1;
favoritCity[1] = userIn2;
favoritCity[2] = userIn3;
System.out.println(userIn1);
System.out.println(userIn2);
System.out.println(userIn3);
}
}
First take a integer input from user, that how many favorite cities does he/she have?
Scanner#nextInt(); which could help you get integer input from console. Create a array with that size Then write loop like -
String[] favoritCity = new String [noOfFabCities];
for(int i=0;i<maxFavCities;i++){
...
}
Now inside the loop get the input from user Enter your i+1 (as i starts with 0) favorite city and capture the input like Scanner#nextLine();. and keep the value into your array like -
favoritCity[i] = userInput;
Once you get all the user input, now can you print in console all the user's favorite cities.
That should be the code which are you looking for. I don't tested it, but it should works.
package com.example.array.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
int cityNumb;
Scanner scanner1 = new Scanner (System.in);
System.out.println("How many favorite cities do you have?");
cityNumb = scanner1.nextInt();
//creat the array with the size of cityNumb
String[] favoritCity = new String [cityNumb];
System.out.println("skriv in "+cityNumb+" favoritstäder");
//for loop for the input of the cities
for(int i = 0; i < cityNumb; i++)
{
String city = scanner1.nextLine();
favoritCity[i] = city;
}
//for loop for the output of the cities
for(int i = 0; i < cityNumb; i++)
{
System.out.println(favoritCity[i]);
}
}
}
Before to define your Array size, you can use your scanner to ask for the number of cities, for example:
Scanner scanner = new Scanner(System.in);
System.out.println("How many cities?");
int nberCities = scanner.nextInt();
String[] favoriteCities = new String[nberCities];
for(int i = 0; i < nberCities;i++){
favoriteCities[i] = scanner.nextLine();
}
Related
Java is my first programming language, and I'm still unfamiliar with how arrays work. However, I was able to make this program, which accepts user-input for an integer array; it then outputs indexes and values, to show how arrays store numbers. I would like to recreate this program using a string array, to make a table containing a list of friends.
The .length property also confuses me...
Could someone explain the .length property and help me make the string array program work?
Thank you very much.
Here is the working code for the integer array table program
import java.util.*;
public class AttemptArrayTable
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Let me show you how arrays are stored ");
System.out.println("How many numbers do you want your array to
store? ");
int arrayInput [] = new int[scan.nextInt()];
System.out.println("Enter numbers ");
for (int count = 0; count<arrayInput.length; count++)
arrayInput[count] = scan.nextInt();
System.out.println("");
System.out.println("Index\t\tValue");
for (int count2=0; count2<arrayInput.length; count2++)
System.out.println(" [" + count2 + "]"+"\t\t " + arrayInput[count2]);
}
}
Here is the code for the string array program I'm working on
import java.util.*;
public class ArrayTableofFriends
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many female friends do you have? ");
String arrayOfFriendsFem [] = new String [scan.nextInt()];
System.out.println("List the name of your female friends");
for(int countF = 0; countF<arrayOfFriendsFem.length; countF++)
arrayOfFriendsFem[countF]= scan.nextLine();
System.out.println("How many male friends do you have? ");
String arrayOfFriendsMale [] = new String [scan.nextInt()];
System.out.println("List the name of your male friends");
for(int countM = 0; countM<=arrayOfFriendsFem.length; countM++)
arrayOfFriendsMale[countM]= scan.nextLine();
System.out.println("How many alien friends do you have? ");
String arrayOfFriendsAliens [] = new String [scan.nextInt()];
System.out.println("List the name of your alien friends");
for(int countA = 0; countA<=arrayOfFriendsFem.length; countA++)
arrayOfFriendsAliens[countA]= scan.nextLine();
{
System.out.println("Female\t\t\t" + "Male\t\t\t" + "Aliens");
for(int countF2 = 0; countF2<arrayOfFriendsFem.length; countF2++)
System.out.println(arrayOfFriendsFem[countF2]);
for(int countM2 = 0; countM2<=arrayOfFriendsMale.length; countM2++)
System.out.println("\t\t\t" + arrayOfFriendsMale[countM2]);
for(int countA2 = 0; countA2<=arrayOfFriendsAliens.length; countA2++)
System.out.println("\t\t\t\t\t\t" +arrayOfFriendsAliens[countA2]);
}
}
.length property stores number of elements in the array. But elements are starting from 0. So, when .length = 1, then there is only one element in the array, with index 0.
It seems in your String arrays program in the for loop the <= should be changed to <
Like this:
for (int countA = 0; countA < arrayOfFriendsFem.length; countA++)
I am trying to create an Array that asks the user for it's length, and then asks the user to input many single words into the array one at a time. However my code sentences.add(s); does not add my "S" variable into my ArrayList called sentences.Could you please take a look at my code to see what I am doing incorrectly. EDIT When running, after entering the length of the array the program the program asks me to enter a word but immediately
prints on the line below it with two brackets [] and stops the program there. If anyone know why this was happing I would appreciate it so much!
import java.util.Scanner;
import java.util.ArrayList;
public class UsingWords
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an array length ");
int lengthArray = scan.nextInt();
ArrayList<String[]> sentences = new ArrayList<String[]>();
for (int i=0; i <= lengthArray; i++); {
System.out.println("Please enter a word: ");
String s = scan.nextLine();
sentences.add(s);
}
System.out.println(Arrays.toString(sentences));
}
}
It does not work because you declared an ArrayList of String[] and you try to add a String into it.
I.E. sentences should be a of ArrayList<String> type.
I have no idea why you are using arrays in combination with ArrayList.
I suspect you want something like this:
//remove the "[]" here
ArrayList<String> sentences = new ArrayList<String>();
for (int i=0; i <= lengthArray; i++); {
System.out.println("Please enter a word: ");
String s = scan.nextLine();
sentences.add(s);
}
//..and the Arrays.toString here
System.out.println(sentences);
System.out.println("Please enter a coefficients of a polynomial’s terms:");
String coefficents = keyboard.nextLine();
String[] three = coefficents.split(" ");
int[] intArray1 = new int[three.length];
for (int i = 0; i < intArray1.length; i++) {
System.out.print(intArray1[i]);
}
//Does anyone know how i can make this work because right not it builds but when i run it, it gives me 0
//if someone could show me or explain to me what's wrong that would help
The problem was that you created the array intArray1 and you printed it without adding any elements to it. That's why it gives 0 as the result.
Instead of creating intArray1, print out the array three in the following way:
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter the coefficients of a polynomial’s terms:");
String coefficents = user_input.nextLine();
String[] three = coefficents.split(" ");
for (String i: three) {
System.out.print(i);
}
}
}
For my homework, I had to write a program that prompts the cashier to enter all prices and names, adds them to two arrays lists, calls the method that I implemented, and displays the result and use 0 as the sentinel value. I am having difficulty coming up with a for loop in the method, I believe I have the condition right but I am having trouble with the statements. Any help would be greatly appreciated! Thanks.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
System.out.print("Enter Number of Customers");
double salesAmount;
System.out.print("Enter Sales for First Customers");
salesAmount = in.nextDouble();
while(salesAmount != 0)
{
sales.add(salesAmount);
System.out.println("Enter Name of Customer: ");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales, ArrayList<String> customers)
{
String name = "";
double maxSales;
for (int i = 0; i < sales.size(); i++)
{
sales.size(name.get); <== it keeps saying "cannot find the symbol variable get"
}
return name;
}
Don't use maxSales as the maximum in your loop. Use the count of number of customers. Inside the loop, check if sales.get(i) is greater than your current maxSales, and if it is...
(I will edit this and more if you still need. But this should go a long way.)
There are a couple possible issues here, but I'll stick to answering what I think is the question that you've asked.
In your nameOfBestCustomer method, you'll want to loop from 0 to the end of either of your ArrayLists (as they both should be the same size).
for (int i = 0; i < sales.size(); i++)
{
...
}
I hate Arrays
So I've been doing some coding and I've come up with an error (out of bounds exception) that I just can't seem to fix. I believe where I am saying 'array1[counter2][counter] = input2.nextLine();' is the problem but I don't know what is wrong! Help, I can't stand these Out of Bounds exceptions
The Idea for the program is an online phone book that you can add contacts, view them, and search by their first name, surname, and phone number.
Here's the code I'm using:
import java.util.Scanner;
import java.awt.*;
public class testMattWalker {
//
public static void main (String[] args){
//Declare all your variables here. Make sure to provide a comment explaining the purpose of each variable
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
boolean go = true;
//Temp VAriables for entry
String firstNameOfEntry = "";
String lastNameOfEntry = "";
String personPhoneNumber = "";
//
//create array
String [][] array1 = new String[5][3];
while (go) {
String choice = "";
System.err.println("\n\n\n\n\n\n\n\n\nDIDGITAL PHONE BOOK 2013");
System.out.println("1- Create phone book\n2- Display phone book\n3- Find person(s) by last name\n4- Find person(s) by first name\n5- Find person(s) by phone number\n6- Exit application");
choice = input.nextLine();
if (choice.equals("1") && counter2 != 6) {
System.err.println("\n\n\n\n\nPHONE BOOK ENTRY CREATOR:");
System.out.println("Please enter the first name of the person you wish to enter: ");
array1[counter2][counter] = input2.nextLine();
counter++;
System.out.println("Please enter the last name of the person you wish to enter: ");
array1[counter2][counter] = input3.nextLine();
counter++;
System.out.println("Please enter the phone number of this person: example:9057773344");
array1[counter2][counter] = input4.nextLine();
counter++;
counter2++;
}else if (choice.equals("2")) {
}else if (choice.equals("3")) {
}else if (choice.equals("4")) {
}else if (choice.equals("5")) {
}else if (choice.equals("6")) {
}
}
}// end of main
}// end of class
I know it's not close to done but I'm the kind of guy who likes to fix everything before moving on so any help would be appreciated! (:
You set the second dimension of your array as 3, but in your code you add 1 to counter 3 times, meaning it goes out of bounds of the array after the first iteration of the code.
As ljgw said array indexes start at 0, so a dimension of 3 means the corresponding indexes are 0,1 and 2.
Remember that array indexes start with 0. So: 5 is already out-of-bounds for counter2.