2 Replies - 859 Views - Last Post: 03 May 2014 - 11:10 AM Rate Topic: -----

#1 Loh_Jane   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 02-May 14

How to read a name which has spaces in Java.?

Posted 02 May 2014 - 06:07 AM

Hi Java Professionals,
I do not know how to read a name which has spaces in Java and I wish to learn. The following is my code, please guide me, thanks a lot in advance.

import java.util.*; 
public class Asking 
{ 
public static void main(String []args) 
{ 
Scanner reader = new Scanner(System.in); 
String [] names = new String[20]; 
int [] marks = new int[20]; 
int count =0; 
String target=" "; 
char choice =' '; 
boolean loop=true; 
for(int i=0;i<names.length;i++) 
{ 
names[i]=" "; 
marks[i]=0; 
} 
while(loop) 
{ 
System.out.println("1))Insert Student's Name and Student's mark \n5)Exit"); 
choice=reader.next().charAt(0); 

switch(choice) 
{ 
case '1': 
for(int i=0;i<names.length;i++) 
{ 
if(names[i].equals(" ") && (marks[i] == 0)) 
{ 
System.out.print("Enter a name:"); 
names[i]=reader.nextLine(); 
System.out.print("Enter a mark:"); 
marks[i]=reader.nextInt(); 
count = count+1; 
break; 
} 
} 
break; 
case '5': 
System.out.println("Bye."); 
loop=false; 
break; 
System.out.println("Invalid choice.");
                break;
            }
        }
    }
}


Is This A Good Question/Topic? 0
  • +

Replies To: How to read a name which has spaces in Java.?

#2 javaJarrett   User is offline

  • New D.I.C Head

Reputation: 11
  • View blog
  • Posts: 28
  • Joined: 30-April 14

Re: How to read a name which has spaces in Java.?

Posted 02 May 2014 - 08:07 AM

hello there.

so i copied your code over to my environment and ran though it. It seems your running into a common issue reading data in using the scanner class. When you use the nextLine() method it leaves behind a newline character which needs to be consumed before you can move forward with your program. This is what is causing the issue I experienced when running your program. Basically a newline character is not an int and when your program calls the nextInt() method it fails because of a type mismatch.

i don't have a quick link to any specific documentation on this but a quick google search for consuming nextline() in java
should get you started.
Was This Post Helpful? 0
  • +
  • -

#3 RCBG   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 03-May 14

Re: How to read a name which has spaces in Java.?

Posted 03 May 2014 - 11:10 AM

Try using this code:

System.out.print("Enter a name:"); 
reader.nextLine(); 
names[i]=reader.nextLine();
System.out.print("Enter a mark:"); 
marks[i]=reader.nextInt(); 
count=count+1; 
break; 

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1