如何修改程序以允许用户输入多于1个单词并在输出中每4个数字后输入一次?我是否在while循环结束时创建了另一个循环?我该怎么办?
import java.util.Arraylist;
import java.util.list;
import java.util.Scanner;
{ public static void main (String[] args)
{
Scanner console = new Scanner(System.in);
List<String> input = new ArrayList<String>();
String line = console.nextLine();
while(!line.equals("")) {
input.add(line);
line = console.nextLine();
}
for(String Letter: input)
{
System.out.println("Enter the a word to be converted : ");
String Letter = console.nextLine();
Letter = Letter.replaceAll("\\s", "");
Letter = Letter.toLowerCase();
String Number="";
int count=0;
int i=0;
while(count < Letter.length())
{
switch(Letter.charAt(i)) {
case 'A':case 'B':case 'C': case 'a': case 'b': case 'c':
Number += "2";
count++;
break;
case 'D':case 'E':case 'F': case 'd': case 'e': case 'f': Number += "3";
count++;
break;
case 'G':case 'H':case 'I': case 'g': case 'h': case 'i': Number += "4";
count++;
break;
case 'J':case 'K':case 'L': case 'j': case 'k': case 'l': Number += "5";
count++;
break;
case 'M':case 'N':case 'O': case 'm': case 'n': case 'o': Number += "6";
count++;
break;
case 'P':case 'R':case 'S': case 'p': case 'r': case 's': Number += "7";
count++;
break;
case 'T':case 'U':case 'V': case 't': case 'u': case 'v': Number += "8";
count++;
break;
case 'W':case 'X':case 'Y':case 'Z': case 'w': case 'x': case 'y': case 'z': Number += "9";
count++;
break;
}
if( count==3) { Number += "-";
}
i++;
}
System.out.println( Number );
}
}
}
立即输出
Enter the word to be converted :
callhome
225-54663
预期输出
Enter the words to be converted :
callhome
hereherehereherehere
comecomecomecomecome
225-5466-3
437-3437-3437-3437-3437-3
266-3266-3266-3266-3266-3
答案 0 :(得分:0)
请更新以下代码:
for($i=0;$i<count($items['units']);$i++){
$bookdetails = new BookingDetails;
$bookdetails->article_group = $items['article_group'][$i];
$bookdetails->article = $items['article'][$i];
$bookdetails->description_en = $items['description_en'][$i];
$bookdetails->units = $items['units'][$i];
$bookdetails->unit_price = $items['unit_price'][$i];
$bookdetails->discount = $items['discount'][$i];
$bookdetails->show_invoice = $items['invoice'][$i];
$bookdetails->show_picklist = $items['delivery_note'][$i];
$bookdetails->save();
}
答案 1 :(得分:0)
在循环中使用console.nextLine()
将所有单词放入数组列表中。然后,您可以遍历数组列表以执行逻辑。关于代码的多条评论:
(count-3)%4 == 0
来查看是否在第4个字符边界。这是您将输入输入数组列表的方法。
List<String> input = new ArrayList<String>();
String line = console.nextLine();
while(!line.equals("")) {
input.add(line);
line = console.nextLine();
}
完成此操作后,您可以按如下方式遍历数组:
for(String Letter: input) {
// Whole of your code goes here.
}
注意语法错误。我只是直接在浏览器中输入。