English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Below is my program code:

public class TestLagi
{
public static void main (String [] args)
{

Test myTest= new Test("what an ordinary world");

myTest.coba();








Here is my class code:
import java.util.Scanner;

public class Test
{

private String word;
private Scanner input;

public Test (String word)
{
word = "";
input = new Scanner(word);
}


public void coba()
{
while (input.hasNext())
{
String word = input.next();
System.out.println(word);
}



Iam trying to print several words on different line based on the string using the hasNext() method here, but why it wont work? Where did I make a mistake? I only can use the hasNext() and the next() method..

Thanks
System.out.println("failed");
}

}

}
}

2006-10-27 05:30:47 · 2 answers · asked by ? 1 in Computers & Internet Programming & Design

2 answers

your problem is with

public Test (String word)
{
word = "";
input = new Scanner(word);
}

you are setting word to "" which is wiping out your string in the constructor then you are trying to scan. if you simply remove the

word = "";

it should work

public Test (String word)
{
input = new Scanner(word);
}

2006-10-27 06:23:24 · answer #1 · answered by nalamf 2 · 1 0

First i ll tel wat i understood from ur question(then my answer ll be correct to some extent):-
You want to get as string but print word by word.

Answer:-

When u are using next() it will fetch till the end of the line.
Note that u are holding the content in a string.
If u want to fetch and print word by word, split the string using
split(). This is the better way.
Note:- Always next() and nextLine() will fetch whole line.

2006-10-27 12:56:56 · answer #2 · answered by Sudha P 2 · 0 0

fedest.com, questions and answers