If work.length is 4 ,
I have to check the AResult in for loop
If 4 AResult all are true ,set result.setstatus("success");
or result.setstatus("fail");
What can I do ??
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start"); //true or false
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
//result.setstatus("success"); //all true
//result.setstatus("fail");
Add a counter. Increment it when your condition is true. Check the value of the counter after your loop. Something like
int counter = 0;
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start");
if (AResult) {
counter++;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
if (work.length == 4 && counter == 4) {
result.setstatus("success");
} else {
result.setstatus("fail");
}
You could optimize the above (and reduce the code size) with something like
int counter = 0;
if (work.length == 4) { // <-- check the length first
for (int i = 0; i < work.length; i++) {
if (!work[i].contains("#")) {
CommandLineInterface CLI = new CommandLineInterface();
try {
if (CLI.Setting(work[i], "start")) {
counter++; // <-- increment the counter.
} else {
break; // <-- break on any fale.
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
result.setstatus(counter == 4 ? "success" : "fail"); // <-- setstatus
try this, you really don't need to iterate the loop till end when a false condition is encountered in between
//initially set success
result.setstatus("success");
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
try {
if(CLI.Setting(work[i],"start"))
{
result.setstatus("fail");
//no need to iterate further
break;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
You can also try the following code
boolean statusFlag = true;
for(int i = 0;i < work.length;i++){
if(!work[i].contains("#")){
CommandLineInterface CLI = new CommandLineInterface();
String IP = null;
boolean AResult;
try {
AResult = CLI.Setting(work[i],"start"); //true or false
if(!AResult){
statusFlag = false;
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
}
}
if(statusFlag){
result.setstatus("success");
}else{
result.setstatus("fail");
}
}
Related
I am facing a issue when fatch the value from xl after that print under the for loop scope then printed. when declare the in return statement and call the method only first cell value print. I want 8 cell value.
public String Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row =0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath,"Course 7");
} catch (IOException e) {
e.printStackTrace();
}
for (Row = 20; Row<28; Row++) {
try {
s = XLUtils.getCellData(excelPath,"Course 7", Row,1);
return s;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("sss="+s);
}
return s;
}
You can use if(condition) to break/return the required value. For ex, I have a for loop interating upto 10. At value 6 I want to stop and return the value. It can be done as:
private test() {
for (int i = 10; i > 10; i++) {
if(i==5) {
return i;
}
}
}
If you want all the 8 cell values then you will have to hold those values in a list/array. You can do it as:
public List<String> Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row = 0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath, "Course 7");
} catch (IOException e) {
e.printStackTrace();
}
List<String> items = new ArrayList<String>();
for (Row = 20; Row < 28; Row++) {
try {
s = XLUtils.getCellData(excelPath, "Course 7", Row, 1);
items.add(s);
return s;
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("sss="+s);
}
return items;
}
So, I'm trying to create a function (If not pretty) IRC client using no libraries, written in Java. I've gotten almost everything working, the only problem is that I'm currently getting user input using System.in. And if someone else in the channel sends a message while I'm in the middle of typing, it cuts off what I currently have, and I need to guess where I am in the string. I want to know if there's a way to separate user input from the output of the program, so that this doesn't happen. This is the code in question:
new Thread(() -> {
while(connected[0]) {
String output = sc.nextLine();
if(!output.startsWith("~") && !output.startsWith("/")) {
try {
writeToSocket("PRIVMSG " + focused[0] + " " + output);
} catch (IOException e) {
e.printStackTrace();
}
}
if(output.substring(1).toLowerCase().startsWith("quit")) {
String[] split = output.substring(5).split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
if(i == 0) {
sb.append(split[i]);
}
sb.append(" ").append(split[i]);
}
try {
writeToSocket("QUIT " + sb.toString());
connected[0] = false;
} catch (IOException e) {
e.printStackTrace();
}
}else if(output.substring(1).toLowerCase().startsWith("focus")) {
String get = output.substring(7);
if(!channels.contains(get)) {
print("Not connected to channel");
}else {
try {
writeToSocket("PART " + focused[0]);
writeToSocket("JOIN " + get);
} catch (IOException e) {
e.printStackTrace();
}
focused[0] = get;
}
}else if(output.substring(1).toLowerCase().startsWith("join")) {
String get = output.substring(6);
channels.add(get);
}
if(output.startsWith("/") && output.substring(1).toLowerCase().startsWith("msg")) {
String[] split = output.substring(5).split(" ");
String username = split[0];
StringBuilder msg = new StringBuilder();
for(int i = 1; i < split.length; i++) {
if(i == 1) {
msg.append(split[i]);
continue;
}
msg.append(" ").append(split[i]);
}
try {
writeToSocket("PRIVMSG " + username + " " + msg.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
I have written the following method to validate an input String and output it as an int array. The method works completely as I need it to but I would like to add some extra validation to it so that it only allows integers and commas in the input so there are no errors.
An example correct input would be:
"7,23,62,8,1130"
The method is:
public static int[] validator (String [] check) {
int [] out = new int[5];
try
{
if (0 < Integer.parseInt(check[0]) && Integer.parseInt(check[0]) < 100)
{
out[0] = Integer.parseInt(check[0]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
try
{
if (0 < Integer.parseInt(check[1]))
{
out[1] = Integer.parseInt(check[1]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
try
{
if(0 < Integer.parseInt(check[2]))
{
out[2] = Integer.parseInt(check[2]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
try
{
if (0 <= Integer.parseInt(check[3]) && Integer.parseInt(check[3]) < 256)
{
out[3] = Integer.parseInt(check[3]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
try
{
if(0 < Integer.parseInt(check[4]))
{
out[4] = Integer.parseInt(check[4]);
}
else
{
throw new InvalidMessageException();
}
}
catch (InvalidMessageException ex)
{
System.err.println("Invalid instruction message");
return null;
}
return out;
}
I have considered doing something like:
inputText = inputText.replace(".", "");
inputText = inputText.replace(":", "");
inputText = inputText.replace(";", "");
inputText = inputText.replace("\"", "");
etc... but it does not seem a particularly great solution. If anyone has a better idea, please let me know. Thanks very much for any help!
I'd say something like this should replace your method, without having read your code, just your requirements:
String input = "7,23,62,8,1130";
if (input.matches("(?:\\d+(?:,|$))+")) {
int[] result = Arrays.stream(input.split(",")).mapToInt(Integer::parseInt).toArray();
} else {
throw new InvalidMessageException("");
}
You can use a regex expression to validate your input:
[0-9]+(,[0-9]+)*,?
Check it with the String matches(regex) method as:
if (yourString.matches("[0-9]+(,[0-9]+)*,?")) {
}
This is exactly what regular expressions are for:
return inputText.matches("\\d+(,\\d+)*");
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}
First I instantiate a gamestate
class GameState extends state{
ArrayList<Level> levels;
int currentLevelID;
public GameState() {
stateID = 2;
levels = new ArrayList<Level>();
createLevels();
currentLevelID = 0;
}
which creates levels
public void createLevels(){
try {
this.levels.add(new NormalLevel(0, 10, 10, null, null, new EmptyTile(1, 1, 1, 1, null) ));
} catch (IOException e) {
e.printStackTrace();
}
}
using this bit of code (forgot the technical term lol)
//level is the superclass of normallevel or whatever i named the default level
public Level(int id, int height, int width, ArrayList<TileEntity> tiles, ArrayList<MobileEntity> mobiles, TileEntity fillBlock){
this.height = height;
this.levelID = id;
this.width = width;
if(tiles != null){
this.tiles = tiles;
} else {
tiles = new ArrayList<TileEntity>();
try {
tiles.add(new EmptyTile(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
try {
mobiles.add(new DefaultEntity(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fillBlock != null){
this.tiles = new ArrayList<TileEntity>();
this.fillWith(fillBlock);
}
}
public void fillWith(TileEntity tile){
for(int i = 0; i < this.height; i++){
for(int j = 0; j < this.width; j++){
for(int k = 0; k < this.tiles.size(); k++){
if (this.tiles.get(k).y == i && this.tiles.get(k).x == j){
break;
}
if(k == this.tiles.size()){
tile.x = j;
tile.y = i;
this.tiles.add(tile);
}
}
}
}
}
Then I try to update the level
public void update(){
this.draw();
for(int i = 0; i < this.tiles.size(); i++){
this.tiles.get(i).update();
}
for(int i = 0; i < this.mobiles.size(); i++){ //nullpointerexception here
this.mobiles.get(i).update();
}
this.specialUpdate();
}
But I get an error on the commented line. I'm confused as hell, help would be appreciated :)
Your mobiles object is null because in the following code
if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
in the else case your assigning the local variable mobiles rather than this.mobiles
if(mobiles != null){
this.mobiles = mobiles;
} else {
mobiles = new ArrayList<MobileEntity>();
try {
mobiles.add(new DefaultEntity(-50,-50,1,1,null));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
If mobiles != null you assign the instance variable (this.mobiles), yet if they are, you create a new List, but assign it to the local variable (mobiles), which is why the list never reaches the instance variable.