Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copyValueOf in Java?

Tags:

java

string

import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
    Scanner keyboard = new Scanner(System.in);
    char[] course; //course code format: ABCDE##
    String code;
    //int num; 
    System.out.println("Input Course: ");
    course = keyboard.next();
    System.out.println(course);
    code = String.copyValueOf(course, 0, 4);
    System.out.println(code);       
   }    
}

I don't know how I should let the user input the course when I'm using a character array instead of string. In short, how do I use the "scanner" on character arrays?

The instruction is the user will input a course code in the format: ABCDE## Then, the program must split it into the course name and the course number. So, I had to use the copyValueOf method but it doesn't seem to work because from all the articles I read online, they used a char[] array but initialized the array with some value. So I was wondering how I could use the scanner on character arrays.

like image 654
nutellafella Avatar asked Sep 17 '26 23:09

nutellafella


1 Answers

Why not just read a string from the scanner and then call String.toCharArray? It's not even clear why you need a char array here...

like image 188
Jon Skeet Avatar answered Sep 20 '26 12:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!