2 Replies - 156 Views - Last Post: 03 October 2012 - 01:41 PM Rate Topic: -----

#1 status90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 24-September 09

output problem

Posted 03 October 2012 - 11:16 AM

not sure how to solve this, always end up getting output "?" :/
i want the user input a string on void method, then uses a char method to find a random character from that particular string.

import java.util.*;

public class randch {
	
	String paces;
	char c;
	
	void setpaces(String faces) {
		Scanner input = new Scanner(System.in);
		System.out.println("Set paces: ");
		paces = input.next();
		System.out.println(paces.length() + " characters");
	}
	
	char rolling(){
		Random random = new Random();
		for(int i = 0; i < paces.length(); i++) {
			c=paces.charAt(i);
		}
		c = (char) random.nextInt();
		System.out.println(c);
		return c;
		
	}
	 
	public static void main(String[] args) {
		
		randch u = new randch();
		u.setpaces(u.paces);
		u.rolling();
	}
}


Is This A Good Question/Topic? 0
  • +

Replies To: output problem

#2 Kakerergodt  Icon User is offline

  • D.I.C Head

Reputation: 87
  • View blog
  • Posts: 201
  • Joined: 01-May 12

Re: output problem

Posted 03 October 2012 - 12:04 PM

Don't know what you are trying to accomplish with the for-loop in the rolling method, the whole for-loop could be replaced by: c = paces.charAt(paces.length()-1); it isnt random at all, it's just the last one.
To get a random number from 0 to paces.length(), you only need to do:
random.nextInt(paces.length());

with that you can probably figure out how to get a random char.
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Re: output problem

Posted 03 October 2012 - 01:41 PM

This statement does not make sense

u.setpaces(u.paces);

you are creating the setter of a just new created object which as parameter an instance variable of that object

Dog fido = new Dog();
fido.setAge(fido.age);

So you actually pass a null String to setpaces()
setapces() ignores that pointer as you fill it with something coming from a Scanner, prints it and exit. The original paces variable is not changed

P.S.
please respect Java convetion: class names start with a Capital letter so RandCh and for methd setPaces()

This post has been edited by pbl: 03 October 2012 - 01:47 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1