我只是想遵循这个条件,但问题是当我输入空的时候,它会继续循环无穷大。
请输入S(供应)或R(补货),然后输入ID和数量。
R p122 10
p125(踏板)的新库存水平为18
S p905 20
未找到ID为p905的部件
空字符串(终止)
显示最终结果。
我也尝试以下代码,但它无法正常工作
if (n.equals("")){
code
}
这是我的代码:
import java.util.*;
public class TestPart {
public static void main(String[] args)
{
Part[] part = new Part[5];
part[0] = new Part("p122", "Chain", 48, 12.5 );
part[1] = new Part("p123", "Chain Guard", 73, 22.0 );
part[2] = new Part("p124", "Crank", 400, 11.5 );
part[3] = new Part("p125", "Pedal", 38, 6.5 );
part[4] = new Part("p126", "Handlebar", 123, 9.50 );
Scanner src = new Scanner(System.in);
String n;
String id;
int qty;
System.out.print("Please Enter either S(supply) or R(replenish) followed by ID and quantity:\n");
int a = 0;
do
{
n = src.next();
id= src.next();
qty= src.nextInt();
boolean found = false;
for(int i = 0; i< part.length; i++)
{
if(part[i].getID().equals(id))
{
found = true;
String name = part[i].getName();
int stockLevel = part[i].getStockLevel();
if(id.equals(part[i].getID()) && n.charAt(0) == 'S')
{
double amount = part[i].supply(qty);
if(amount>0){
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is " + part[i].getStockLevel());
}
else{
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is not available" );
}
}
else if (id.equals(part[i].getID()) && n.charAt(0) == 'R')
{
part[i].replenish(qty);
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is " + part[i].getStockLevel());
}
}
}
if (found == false)
{
System.out.println("No part found with ID " + id );
}
System.out.println("");
for(int i=0; i<part.length; i++)
{
System.out.println(part[i].getID()+ "\t"+part[i].getName()+"\t"+part[i].getStockLevel()+"\t"+part[i].getUnitPrice() );
}
}while(a ==0);
}
答案 0 :(得分:0)
您的代码是:
a = 0;
do {
// ...
}while(a ==0);
这就是它无限循环的原因。
答案 1 :(得分:0)
如果要在输入行为空时终止
do{
String line = src.nextLine();
String [] inputs = null;
if(!line.matches("\\s*")){
String n ;
String id ;
int qty;
inputs = line.split(" ");
if(inputs.length ==3)
{
n = inputs[0];
id = inputs[1];
qty = (int) Integer.parseInt(inputs[2]);
}
else if(inputs.length ==2)
{
id = inputs[0];
qty = (int) Integer.parseInt(inputs[1]);
}
// Your Logic
}
else
break;
}while(a==0)