I'm trying to store name and address of persons in the form of 2d array, but when I run my code it accepts less values only. For example if I give the array 2 rows and 2 columns, it accepts only 3 values.
I've tried searching on other forums, couldn't get the proper answer.
I also changed the dimension values but it gives wrong result only.
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
You read 4 values but one is an empty line from when you press enter for int addr=scan.nextInt();
A quick fix is to read that empty line
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
---> scan.nextLine();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
Edit:
Or you can use scanner.skip Skip newline character while reading from Scanner class
In addition to the other answer here is how your code should look like:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of people: ");
int iPeople = scanner.nextInt();
System.out.print("Enter the number of address: ");
int iAdresses =scanner.nextInt();
scanner.nextLine();
String data[][] = new String[iPeople][iAdresses];
for(int i=0; i < iPeople; i++)
{
for(int j=0; j < iAdresses; j++)
{
System.out.printf("Enter %d address for person %d:%n", j + 1, i + 1);
data[i][j] = scanner.nextLine();
}
}
And try to follow these conventions:
Use proper Java naming conventions
Make your code more readable by providing appropriate empty lines between lines you feel are too cluttered or belong to different groups based on what operation are they trying to accomplish.
If you want to understand why, the behavior of nextLine is explain here : Java Scanner doesn't wait for user input
You can also replace nextLine by next to avoid this.
Related
I am using a Scanner object to take user input. The Scanner first takes an integer called 'num'. I then create an array of Strings of size 'num' and I fill this array with Strings taken in by the same Scanner via a for-loop. My problem is that when taking the first String value, the Scanner seems to 'skip' it by assigning it an empty String. Why is it doing this?
import java.util.Scanner;
public class KrisKindle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many people are there?");
int num = scan.nextInt();
String[] names = new String[num];
for(int i = 0; i < names.length; i++) {
System.out.println("Enter name of person " + (i +1) + "/" + num);
names[i] = scan.nextLine();
}
}
}
Here's a sample output for when this program is run:
How many people are there?
7
Enter name of person 1/7
Enter name of person 2/7
Adam
Enter name of person 3/7
Eve
Enter name of person 4/7
What I have tried so far:
Creating a separate Scanner object for taking my array of Strings. This causes a separate error that I can share if it might help
Printing the value of name 1/7 (it is empty)
You just need to add scan.nextLine() after scan.nextInt() because the Scanner.nextInt method doesn't read the newline character in your input created by hitting "Enter" and so the call to Scanner.nextLine returns after reading that newline.
You will encounter a similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself)
public class KrisKindle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many people are there?");
int num = scan.nextInt();
scan.nextLine(); // This line you have to add (It consumes the \n character)
String[] names = new String[num];
for(int i = 0; i < names.length; i++) {
System.out.println("Enter name of person " + (i +1) + "/" + num);
names[i] = scan.nextLine();
}
}
}
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);
Ok so i know there is a smilier question but I think mine is slightly different so I'll post and risk getting panned by you all ;)
So i want the user to input a word (Java) and then input a number (4) and the programme then prints in this case JavaJavaJavaJava
Here is what I have got so far
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = sc1.nextLine();
System.out.println(str);
System.out.println(num);
From what i understand i may be scanning in the number the wrong way as i'm currently scanning it in as a String and not an integer but hey.
Any help massively appreciated :)
You have to use a for-loop for this, and scan the number as an integer.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
System.out.print("Enter a number: ");
int num = sc.nextInt();
for (int i=0;i<num;i++) {
System.out.println(str);
}
}
Nearly there. Add the following at the end:
int number = Integer.parseInt(num);
for (int i=0; i<number; i++) {
System.out.print(str);
}
There are a couple things you're going to want to change to do this.
1) You're only calling System.out.println(str); once, so the string will only be printed once. Now, you could just put System.out.println(str); 3 times, but then you'd be stuck with num always being 3. What I'd suggest is using a for loop, like the one found here. Basically, it would look like this assuming num is 10 and str is test string
for(int i=0;i<10;i++)
{
System.out.println("test string");
}
You'll want to change that to fit your exact case, but that should be enough to get you started.
2) You're right here
i may be scanning in the number the wrong way as i'm currently scanning it in as a String and not an integer.
You want to scan it in as an integer, otherwise it's useless for your purposes. For all java knows, you want to print out your string puppy or bacon times rather than 3 or 4.
If you still have any questions about this, lemme know. We've all been there man.
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = sc.nextLine();
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = sc1.nextLine();
int counter = 0;
while (counter < num){
System.out.print(str);
counter ++;
}
I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
I am currently working on a program that requests input for the names and scores of two teams. When I request input for the name and 9 scores of the first team, the scanner accepts input just fine. However, after the for loop, the scanner does not accept input for the name of the second team. This is not the entire program, but I have included all the code up until the point where it is giving me trouble. I suspect that it may have something to do with the for loop because team2 accepts user input just fine when I place it before the for loop.
import java.util.Scanner;
public class sportsGame{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String team1;
String team2;
int team1Scores[] = new int[9]
int team1Total = 0;
int team2Scores[] = new int[9];
int team2Total = 0;
System.out.print("Pick a name for the first team: ");
team1 = input.nextLine();
System.out.print("Enter a score for each of the 9 innings for the "
+ team1 + " separated by spaces: ");
for(int i = 0; i < team1Scores.length; i++){
team1Scores[i] = input.nextInt();
team1Total += team1Scores[i];
}
System.out.print("Pick a name for the second team: ");
team2 = input.nextLine();
}
}
Scanner's nextInt method does not skip a line, only fetches the int. So when the first loop ends, there is still one newline character left and your input.nextLine() returns a blank string. add a input.nextLine() after your loop to skip this blank line and to solve your problem like this:
for(int i = 0; i < team1Scores.length; i++){
team1Scores[i] = input.nextInt();
team1Total += team1Scores[i];
}
input.nextLine();
//rest of your code