我一直在爲學校創建一門課程,用戶,學生和老師,但我在創建課程時碰到了一個障礙。在java中讀取字符串
我想要做的是(在終端中)讀取輸入流,例如「CSC 110 Into to java」,並將其全部輸入到字符串中。我正在使用掃描儀進行輸入。並在next()之後嘗試了hasNext()和nextLine()。我想寫一個函數來使用char數組獲取整個字符串,然後將char數組轉換爲字符串。
首先我想知道是否有更簡單的解決方案?
編輯:對不起,我不清楚。沒有進入我的所有代碼。
當前代碼:
System.out.print("Enter the Course Title: ");
title = keyboard.nextLine();
System.out.print("Enter a Brief Course Description: ");
desc = keyboard.nextLine();
if (t != null)
{
do
{
System.out.println("\nPick a teacher\n");
for (int j = 0; j < t.size(); j++)
{
nTeacher = t.get(j);
s += "\t(" + (j+1) + ") " + nTeacher + "\n";
}
System.out.print(s + "\nEnter the Teacher ID: ");
int tId = keyboard.nextInt(); // My error
當前出錯:
Enter the Course Title: CSC 110 Into to java
Enter a Breif Course Description:
Pick a teacher
Enter the Teacher ID:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at Prototype.classCreator(Prototype.java:530)
at Prototype.mainMenu(Prototype.java:181)
at Prototype.login(Prototype.java:121)
at Prototype.main(Prototype.java:48)
當我使用nextLine()
Create Class
Enter the courseID: 27222
Enter the Course Title: Enter a Brief Course Description:
預期的結果:
Create Class
Enter the courseID: 27299
Enter the Course Title: CSC 110 Into to Java
Enter a Brief Course Description: Introduction to programming
Pick a teacher
(1) ID: 1111 Name: Bob
Enter the Teacher ID: 1
Class Created
我知道,當我有三個字符串「CSC 110 Intro」它得到nextInt()的輸入,但我不明白爲什麼nextLine()正在寫我的println是這樣的。
對不起新的SO,無形中。我修正了:) – Jeremy 2011-04-04 06:56:39