I've implemented the following code to print a phrase in lower case characters:
import java.util.Scanner;
public class LowerCase{
public static void main (String[] args) {
String input, output = "", inter;
Scanner scan, lineScan;
scan = new Scanner(System.in); // Scan from the keyboard
System.out.println("Enter a line of text: ");
input = scan.nextLine(); // Scan the line of text
lineScan = new Scanner(input);
while (lineScan.hasNext()) {
inter = scan.next();
output += inter.toLowerCase() + " ";
}
System.out.println(output);
}
}
I don't know what is wrong with my implementation! It compiles normally but when I run the code and type the input phrase, it freezes.
Your loop is waiting for lines with one scanner, but reading lines from another Scanner
(thus an infinite loop). This
while (lineScan.hasNext()) {
inter= scan.next();
should be something like
while (lineScan.hasNext()) {
inter= lineScan.next();
You do not need two Scanner Objects to achieve the output this shall work for you
scan= new Scanner(System.in); //scan from the keyboard
System.out.println("Enter a line of text: ");
input=scan.nextLine(); //scan the line of text
System.out.println(input.toLowerCase());
scan.close();
I recommend a different method:
import java.util.*;
public class something
{
static Scanner reader=new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("type something (string)");
String text = reader.next(); // whatever the user typed is stored as a string here
System.out.println(text);
System.out.println("type something (int)");
int num = reader.nextInt(); // whatever the user typed is stored as an int here
System.out.println(num);
System.out.println("type something (double)");
double doub = reader.nextDouble(); // whatever the user typed is stored as double here
System.out.println(doub);
}
}
this is some example code for how I get user input.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.