我必须编写一个名为Checkers的Java方法,它接受两个整数参数,并使用这些值来打印散列标记符号的棋盘图案。例如,值3和4将产生以下输出:
# #
# #
# #
除了创建方法的参数之外,我不确定如何创建此方法。我怀疑最简单的方法是创建两个for循环,但我不确定如何编写它们。
答案 0 :(得分:1)
|#O#O#O#O|# #O#O#O#O
#|O#O#O#O#| O#O#O#O#
|#O#O#O#O|# => #O#O#O#O
#|O#O#O#O#| O#O#O#O#
|#O#O#O#O|# #O#O#O#O
#O#O#O#O
和O#O#O#O#
。#O#O#O#O
或O#O#O#O#
height
次。public static void printCheckerBoard(int height, int width) {
// build patterns
String pn1 = "";
String pn2 = "";
for (int j = 0; j < width; j++) {
if (j % 2 == 0) {
pn1 += '#';
pn2 += '0';
} else {
pn1 += '0';
pn2 += '#';
}
}
// draw rows
for (int i = 0; i < height; i++) {
System.out.println(i % 2 == 0 ? pn1 : pn2);
}
}
答案 1 :(得分:1)
这不是一个布尔标志,而是一个简单的问题逻辑:只为每个具有偶数/奇数行和列的单元格打印MainViewModel
字符,否则打印空格。
(奇数rownum和偶数列数)和(甚至rownum和Odd列名称)打印空间。
(甚至rownum和Even列号)和(奇数rownum和Odd列名称)打印哈希。
public class MainViewModel : ViewModelBase
{
//add instances to all the ViewModels you want to switch between here, and add templates for them in your resources specifying the x:type and the view or data template to be used
public ObservableCollection<ViewModelBase> ViewModels { get; set; } = new ObservableCollection<ViewModelBase>();
private ViewModelBase _currentViewModel;
public ViewModelBase CurrentViewModel {
get { return _currentViewModel; }
set { SetField(ref _currentViewModel, value); }
}
private ICommand _nextViewModel;
public ICommand NextViewModel
{
get
{
return _nextViewModel = _nextViewModel ?? new RelayCommand(p =>
{
CurrentViewModel = ViewModels[ViewModels.IndexOf(CurrentViewModel) +1];
}, p =>
{
return ViewModels.IndexOf(CurrentViewModel) + 1 != ViewModels.Count && CurrentViewModel != null;
});
}
}
public ICommand _prevViewModel;
public ICommand PrevViewModel
{
get
{
return _prevViewModel = _prevViewModel ?? new RelayCommand(p =>
{
CurrentViewModel = ViewModels[ViewModels.IndexOf(CurrentViewModel) - 1];
}, p =>
{
return ViewModels.IndexOf(CurrentViewModel) != 0 && CurrentViewModel!=null;
});
}
}
private ICommand _switchToViewModel;
public ICommand SwitchToViewModel
{
get
{
return _switchToViewModel = _switchToViewModel ?? new RelayCommand(p =>
{
CurrentViewModel = this.ViewModels.FirstOrDefault(vm=>vm.GetType()==p as Type);
}, p =>
{
return this.ViewModels.FirstOrDefault(vm => vm.GetType() != p as Type) != null;
});
}
}
}
输出:
#
答案 2 :(得分:0)
看到问题已经回答,但我想试试看。
public class checkers {
public static void checker(int rows, int columns){
boolean odd = false;
for(int y=1; y<=rows; y++){
for(int x=1; x<=columns; x++){
if(odd){System.out.print("# ");}
else{System.out.print(" #");}
}
if(odd){odd=false;}
else{odd=true;}
System.out.println("");
}
}
public static void main(String[] args) {
checker(4,3);
}
}