This is a program that prints out all the even numbers between any given integer.
import java.util.*;
public class Question1
{
private int i;
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Give me a number!");
int i = scanner.nextInt();
if ((i % 2) != 0)
{
i = i - 1;
do
{
System.out.println(i);
i = i - 2;
} while (i != -2);
}
}
}
So, if I give the number 11, it will print out 10, 8, 6, 4, 2. Why won't it print 0 as well, since my while statement contains i!= -2 and 0 counts as an even number?
Because after scanner.nextInt(); you must put scanner.nextLine(); else, the last element the scanner gets from nextInt(); will be ignored.
Even so, your algorithm is extremely dizzy. why not try:
Scanner in = new Scanner( System.in );
int number = in.nextInt(); in.nextLine();
for( int i = 0; i <= number; i += 2 ) {
System.out.println( i );
}
?
Related
We have an NxM grid, grid have one element named Bob. Bob can travel diagonally blocks only. The grid has some blocked blocks on which Bob can not travel. Write a function that returns on how many possible positions Bob can move. Solve this problem using BFS and submit the executable code in any programming language. In the following image example, Bob's positioning is at 9,3, and it can visit the places where Y is marked; hence your method should return 30.
Anybody any pseudocode or approach on how to solve this using BFS
Following solution is modified version of solution given by ( https://stackoverflow.com/users/10987431/dominicm00 ) on problem ( Using BFS to find number of possible paths for an object on a grid )
Map.java:
import java.awt.*;
public class Map {
public final int width;
public final int height;
private final Cell[][] cells;
private final Move[] moves;
private Point startPoint;
public Map(int[][] mapData) {
this.width = mapData[0].length;
this.height = mapData.length;
cells = new Cell[height][width];
// define valid movements
moves = new Move[]{
new Move(1, 1),
new Move(-1, 1),
new Move(1, -1),
new Move(-1, -1)
};
generateCells(mapData);
}
public Point getStartPoint() {
return startPoint;
}
public void setStartPoint(Point p) {
if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");
startPoint.setLocation(p);
}
public Cell getStartCell() {
return getCellAtPoint(getStartPoint());
}
public Cell getCellAtPoint(Point p) {
if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");
return cells[p.y][p.x];
}
private void generateCells(int[][] mapData) {
boolean foundStart = false;
for (int i = 0; i < mapData.length; i++) {
for (int j = 0; j < mapData[i].length; j++) {
/*
0 = empty space
1 = wall
2 = starting point
*/
if (mapData[i][j] == 2) {
if (foundStart) throw new IllegalArgumentException("Cannot have more than one start position");
foundStart = true;
startPoint = new Point(j, i);
} else if (mapData[i][j] != 0 && mapData[i][j] != 1) {
throw new IllegalArgumentException("Map input data must contain only 0, 1, 2");
}
cells[i][j] = new Cell(j, i, mapData[i][j] == 1);
}
}
if (!foundStart) throw new IllegalArgumentException("No start point in map data");
// Add all cells adjacencies based on up, down, left, right movement
generateAdj();
}
private void generateAdj() {
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
for (Move move : moves) {
Point p2 = new Point(j + move.getX(), i + move.getY());
if (isValidLocation(p2)) {
cells[i][j].addAdjCell(cells[p2.y][p2.x]);
}
}
}
}
}
private boolean isValidLocation(Point p) {
if (p == null) throw new IllegalArgumentException("Point cannot be null");
return (p.x >= 0 && p.y >= 0) && (p.y < cells.length && p.x < cells[p.y].length);
}
private class Move {
private int x;
private int y;
public Move(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}}
Cell.java:
import java.util.LinkedList;
public class Cell {
public final int x;
public final int y;
public final boolean isWall;
private final LinkedList<Cell> adjCells;
public Cell(int x, int y, boolean isWall) {
if (x < 0 || y < 0) throw new IllegalArgumentException("x, y must be greater than 0");
this.x = x;
this.y = y;
this.isWall = isWall;
adjCells = new LinkedList<>();
}
public void addAdjCell(Cell c) {
if (c == null) throw new IllegalArgumentException("Cell cannot be null");
adjCells.add(c);
}
public LinkedList<Cell> getAdjCells() {
return adjCells;
}}
MapHelper.java:
class MapHelper {
public static int countReachableCells(Map map) {
if (map == null) throw new IllegalArgumentException("Arguments cannot be null");
boolean[][] visited = new boolean[map.height][map.width];
// subtract one to exclude starting point
return dfs(map.getStartCell(), visited) - 1;
}
private static int dfs(Cell currentCell, boolean[][] visited) {
visited[currentCell.y][currentCell.x] = true;
int touchedCells = 0;
for (Cell adjCell : currentCell.getAdjCells()) {
if (!adjCell.isWall && !visited[adjCell.y][adjCell.x]) {
touchedCells += dfs(adjCell, visited);
}
}
return ++touchedCells;
}}
Grid.java:
public class Grid{
public static void main(String args[]){
int[][] gridData = {
{0,0,0,0,0,0,0,0},
{0,1,0,0,0,1,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,1,0,0,1,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,1,0},
{0,0,1,0,0,1,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,2,1,0,0,0}}; //2 is bobs position, 1 is blocked, 0 can be visited
Map grid = new Map(gridData);
MapHelper solution = new MapHelper();
System.out.println(solution.countReachableCells(grid));
}}
For original answer of similar problem visit (Using BFS to find number of possible paths for an object on a grid) for original answer.
Here's my code, i do not know what I'm doing wrong seriously. I tried many different things like taking the public modifier away from get. but I still get the same thing. This program is supposed to print out the Nth number line in the pascal triangle do to that I am using recursion a little bit.
import java.util.*;
public class Triangle{
private int lineNumber, count;
private int[] num;
public Triangle(){
lineNumber = 1;
}
public Triangle(int n){
set(n);
}
public void set(int n){
if(n < 1){
lineNumber = 1;
}
else{
lineNumber = n;
}
public int get()//Triangle.java:26: error: ';' expected //
{
return lineNumber;
}
private void pascal(int[] row){ //Triangle.java:30: error: illegal start of expression
if(count >= lineNumber){
return;
}
num = new int[row.length + 1];
num[0] = 1;
for(int i = 1; i < row.length; i++){
num[i] = row[i - 1] + row[i];
}
num[row.length] = 1;
count ++;
pascal(num);
return;
}
public int[] output(){
count = 1;
num = new int[count];
num[0] = 1;
pascal(num);
return num;
}
public static void main(String[] args){
int i,userNum;
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a number to get the nth line of"+
" Pascal's Triangle." );
userNum = input.nextInt();
PascalTriangle triangle = new Triangle(userNum);
int[] result = triangle.output();
System.out.println("\n Line " + triangle.get() + " of "
+ "Pascal's Triangle is ");
for(i = 0; i < result.length; i++){
System.out.println(result[i] + " ");
}
}
}
}
You need one more closing bracket after the else statement in the set() method.Try to add the closing } before
else{
lineNumber = n;
}
}
public int get()//Triangle.java:26: error: ';' expected //
i use aparapi for parallelize and i wante to convert this java code:
public static void main(String[] args) {
float res = 0;
for (int i = 2; i < 5; i++) {
for (int j = 3; j < 5; j++) {
res += i * j;
}
}
System.out.println(res);
}
to its equivalent in aparapi:
Kernel kernel = new Kernel() {
#Override
public void run() {
int i = getGlobalId();
...
}
};
kernel.execute();
kernel.dispose();
There are a few issues here.
First your code is not data parallel. You have a 'race' condition on 'res' so this code cannot be computed on the GPU.
Secondly the range of execution is way too small. You are trying to execute 6 threads (x [2,3,4] * y [ 3,4]). This will not really gain any benefit from the GPU.
To answer the question regarding how you might implement over the 2 dim grid above.
Range range = Range.create2D(3, 2) ; // A two dimension grid 3x2
Kernel kernel = new Kernel() {
#Override
public void run() {
int x = getGlobalId(0)+2; // x starts at 2
int y = getGlobalId(1)+3; // y starts at 3
...
}
};
kernel.execute(range);
kernel.dispose();
Hey StackOverflow Community,
So, I have this line of information from a txt file that I need to parse.
Here is an example lines:
-> date & time AC Power Insolation Temperature Wind Speed
-> mm/dd/yyyy hh:mm.ss kw W/m^2 deg F mph
Using a scanner.nextLine() gives me a String with a whole line in it, and then I pass this off into StringTokenizer, which then separates them into individual Strings using whitespace as a separator.
so for the first line it would break up into:
date
&
time
AC
Power
Insolation
etc...
I need things like "date & time" together, and "AC Power" together. Is there anyway I can specify this using a method already defined in StringTokenizer or Scanner? Or would I have to develop my own algorithm to do this?
Would you guys suggest I use some other form of parsing lines instead of Scanner? Or, is Scanner sufficient enough for my needs?
ejay
oh, this one was tricky, maybe you could build up some Trie structure with your tokens, i was bored and wrote a little class which solves your problem. Warning: it's a bit hacky, but was fun to implement.
The Trie class:
class Trie extends HashMap<String, Trie> {
private static final long serialVersionUID = 1L;
boolean end = false;
public void addToken(String strings) {
addToken(strings.split("\\s+"), 0);
}
private void addToken(String[] strings, int begin) {
if (begin == strings.length) {
end = true;
return;
}
String key = strings[begin];
Trie t = get(key);
if (t == null) {
t = new Trie();
put(key, t);
}
t.addToken(strings, begin + 1);
}
public List<String> tokenize(String data) {
String[] split = data.split("\\s+");
List<String> tokens = new ArrayList<String>();
int pos = 0;
while (pos < split.length) {
int tokenLength = getToken(split, pos, 0);
tokens.add(glue(split, pos, tokenLength));
pos += tokenLength;
}
return tokens;
}
public String glue(String[] parts, int pos, int length) {
StringBuilder sb = new StringBuilder();
sb.append(parts[pos]);
for (int i = pos + 1; i < pos + length; i++) {
sb.append(" ");
sb.append(parts[i]);
}
return sb.toString();
}
private int getToken(String[] tokens, int begin, int length) {
if (end) {
return length;
}
if (begin == tokens.length) {
return 1;
}
String key = tokens[begin];
Trie t = get(key);
if (t != null) {
return t.getToken(tokens, begin + 1, length + 1);
}
return 1;
}
}
and how to use it:
Trie t = new Trie();
t.addToken("AC Power");
t.addToken("date & time");
t.addToken("date & foo");
t.addToken("Speed & fun");
String data = "date & time AC Power Insolation Temperature Wind Speed";
List<String> tokens = t.tokenize(data);
for (String s : tokens) {
System.out.println(s);
}
Here is the sample code:
class MailBoxSampleListField extends MainScreen implements FolderListener, StoreListener {
private static final int COLUMN_WIDTH_STATUS = 10;
private static final int COLUMN_WIDTH_DATE = 150;
private static final int COLUMN_WIDTH_NAME = 150;
public ListField myList;
private ListCallback myCallback;
public Vector sampleList = new Vector();
public Vector sampleVector;
private class ListCallback implements ListFieldCallback {
public Vector myVector = new Vector();
public Bitmap LIST_IMAGE = Bitmap.getBitmapResource("New.PNG");
public void drawListRow (ListField list, Graphics g, int index, int y,int w) {
displayList(g,0,y,w,(( Message )myVector.elementAt( index )), LIST_IMAGE); // for drawing the list row
for( int ii = 0; ii < sampleVector.size(); ii++) {
String text = ( String )sampleVector.elementAt(ii);
int liney = y + ( ii * list.getFont().getHeight() );
g.drawText( text, LIST_IMAGE.getWidth() + 5, liney, Graphics.ELLIPSIS, w );
}
}
public Object get( ListField list, int index ) {
return myVector.elementAt(index);
}
public int indexOfList( ListField list,String p, int s ) {
return myVector.indexOf(p,s);
}
public int getPreferredWidth ( ListField list ) {
return Graphics.getScreenWidth();
}
public void insert(Message _message, int index) {
myVector.addElement(_message);
}
public void erase () {
myVector.removeAllElements();
}
}
MailBoxSampleListField() {
ListCallback myCallback = new ListCallback();
try {
Store store = null;
store = Session.getDefaultInstance().getStore();
store.addStoreListener( this );
// retrieve Folder object fow which we want to receive message notification
try {
Folder[] folders = store.list();
Folder[] f1 = store.findFolder( "inbox" );
Folder vinbox = f1[0];
for (int i =0; i < f1.length; i++) {
f1[i].addFolderListener( this );
}
Message[] vmessages = vinbox.getMessages();
for ( int j = 0; j < vmessages.length; ++j ) {
if(vmessages[j] != null){
sampleList.addElement( vmessages[j] );
}
}
myList = new ListField(); // initialize the ListField
for ( int k = 0; k < sampleList.size(); k++ ) {
myList.insert(k);
myCallback.insert(vmessages[k], k);
}
myList.setCallback( myCallback );
add( myList );
}
catch( Exception e ){
}
}
catch ( Exception se ) {
}
}
public void displayList( Graphics g, int x, int y, int width, Message _message, Bitmap LIST_IMAGE ) {
g.drawBitmap(0, y, LIST_IMAGE.getWidth(), LIST_IMAGE.getHeight(), LIST_IMAGE, 0, 0);
sampleVector = new Vector();
Date d = _message.getReceivedDate();
Calendar c = Calendar.getInstance();
c.setTime(d);
StringBuffer sb = new StringBuffer();
sb.append( c.get( Calendar.MONTH ) );
sb.append('-');
int digit = c.get( Calendar.DAY_OF_MONTH );
if ( digit < 10 ) sb.append(0);
sb.append( digit );
sb.append(' ');
sb.append( c.get( Calendar.HOUR_OF_DAY ) );
sb.append(':');
digit = c.get( Calendar.MINUTE );
if ( digit < 10 ) sb.append( 0 );
sb.append( digit );
sb.append( ' ');
x += LIST_IMAGE.getWidth()+5;
x += COLUMN_WIDTH_DATE;
try {
String name = "<noname>";
if ( _message.isInbound() ) {
Address a = _message.getFrom();
if ( a != null )
{
name = a.getName();
if ( name == null || name.length() == 0 ) name = a.getAddr();
}
}
else
{
//get the first Recipient address
Address[] set = _message.getRecipients(Message.RecipientType.TO);
if ( set != null && set.length > 0 )
{
name = set[0].getName();
if ( name == null || name.length() == 0 ) name = set[0].getAddr();
}
}
sampleVector.addElement(name +" " + sb.toString());
} catch (MessagingException e) {
System.err.println(e);
}
x += COLUMN_WIDTH_NAME;
int remainingColumnWidth = Graphics.getScreenWidth() - x;
//get the subject, or if that doesn't exist, the first line of the body
String textToDisplay = _message.getSubject();
if ( null == textToDisplay) //no subject! get the first line of the body if present
{
Object o = _message.getContent();
if ( o instanceof String )
{
textToDisplay = (String)o;
}
else if ( o instanceof Multipart )
{
Multipart mp = (Multipart)o;
int count = mp.getCount();
for (int i = 0; i < count; ++i)
{
BodyPart p = mp.getBodyPart(i);
if ( p instanceof TextBodyPart )
{
textToDisplay = (String)p.getContent();
}
}
}
}
sampleVector.addElement(textToDisplay);
} public void messagesAdded(FolderEvent e) {} public void messagesRemoved(FolderEvent e) { } public void batchOperation( StoreEvent se) { }
}
I'm not sure what you mean, could you please post a screenshot so that we can see the problem?
I'll try to help out the best I can. In my limited experience, I have noticed that in a listfield, if you have not set the row height (with setRowHeight()) to a big enough height, graphics (including text) that overflow over the size of the row will not be displayed. Have you tried setting the row height to 2 * list.getFont().getHeight() or more?
If not all rows are displayed, then I think you've missed to call myList.setSize(myVector.size());
I'm not sure what you mean by "wrapping not happening"...
The drawListRow() will be called repeatedly (for the amount of times set by the setSize() that I've suggested above).
In your current code you iterate through the whole myVector on each drawListRow() call - this is wrong.
You must use the value y which is declare in drawListRow (ListField list, Graphics g, int index, int y,int w)
like
g.drawText( text, LIST_IMAGE.getWidth() + 5, y+liney, Graphics.ELLIPSIS, w )
I am facing this issue for long time finally i got the solution.
As Alex say, you need to implement your own wrapper class, something that looks like:
TextWrapper theWrapper = new TextWrapper();
String[] wrappedText = theWrapper.textWrap(longText, wrappingWidth , 2);
//
// now draw text line by line
//
g.drawText(wrappedText[0], x, y, DrawStyle.LEFT, width);
if (wrappedText.length > 1) {
g.drawText(wrappedText[1], x, y + textFont.getHeight(), DrawStyle.LEFT | DrawStyle.ELLIPSIS, width);
}
where
public class TextWrapper {
... // put here methods used by textWrap method
//
// textWrap splits input String in lines having width as maxWidth
//
public String[] textWrap(String s, int maxWidth, int maxLines)
{
String[] result;
... // do here the wrap job on input string s
return result;
}
}