I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.
Question
Given a string S of length N, that is indexed from 0 to N-1, print it's even indexed and odd indexed characters as 2 space separated strings on a single line.
Assume input starts at index position 0(which is considered even)
Input
The first line contains an integer, T (the number of test cases).
Each line i of the T subsequent lines contain a String, S.
Output
For each string S, print it's even-indexed characters, followed by space, followed by odd-indexed characters.
Sample Input
2
Hacker
Rank
Sample Output
Hce akr
Rn ak
The Code I Wrote
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
scan.nextLine();
for(int i=0 ; i<T ; i++)
{
String myString = scan.nextLine();
int evn = 0,
odd = 0,
len = myString.length();
char strE[] = new char[50],
strO[] = new char[50];
for(int j=0 ; j<len ; j++)
{
if(j%2 == 0)
{
strE[evn] = myString.charAt(j);
evn++;
}
if(j%2 == 1)
{
strO[odd] = myString.charAt(j);
odd++;
}
}
System.out.print(strE);
System.out.print(" ");
System.out.println(strO);
}
}
My Output
Hce akr
Rn ak
The Problem
As you can see, my program successfully meets the test case, and other test cases (using custom input) but every time the HackerRank compiler tells me that my program did not meet the test case.
Clearly, my program is producing the required output but every time the HackerRank compiler tells me that I got the solution wrong.
Could anyone please tell me where I am making a mistake?
Further Modifications
I then decided to change the last 3 lines of print statements into one statement as follows:
System.out.println(strE + " " + strO);
However, this time the program did not produce the desired output and rather printed some garbage values as follows:
[C#5c3f3b9b [C#3b626c6d
[C#3abc8690 [C#2f267610
My Doubts
1. In the first case, when I was printing the two strings separately using 2 print statements, I was getting a correct output everytime but the HackerRank compiler rejected it. Why?
2. In the second case, when I modified the program by using one print statement instead of 3 to get the desired result, the program gave a completely different output and rather printed garbage values! Why?
Here is a link to the HackerRank problem for more info:
hackerrank.com/challenges/30-review-loop
All help and guidance is greatly appreciated and thanks a lot in advance!
Try to submit this:
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
scan.nextLine();
for (int i = 0; i < T; i++) {
String myString = scan.nextLine();
String even = "";
String odd = "";
for (int j = 0; j < myString.length(); j++) {
if (j % 2 == 0) {
even += myString.charAt(j);
} else {
odd += myString.charAt(j);
}
}
System.out.println(even + " " + odd);
}
i get the right output and it should meet all the requirements. i think your code fails because its not a real string you print in the end and you have empty spots in your arrays
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the no.of test-cases:");
int t = scanner.nextInt();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String(s)");
for (int i = 0; i < t; i++) {
String myString = br.readLine();
String even = "";
String odd = "";
for (int j = 0; j < myString.length(); j++) {
if (j % 2 == 0) {
even += myString.charAt(j);
} else {
odd += myString.charAt(j);
}
}
System.out.println(even);
System.out.println(odd);
}
scanner.close();
int T = scan.nextInt();
This reads quantity of test cases, which we're going to process.
String string[] = new String[T];
for(int i = 0; i<T; i++){
string[i] = scan.next();
}
Next we're creating an array named "string" (BTW, this a bad name for variables/objects) which has size T and in the for loop reading test cases from the input T times and saving them in the array.
for(int temp = 0; temp<T; temp++){
Now, for each of test cases we do the following...
for(int j = 0; j<string[temp].length(); j = j+2)
{
System.out.print(string[temp].charAt(j));
}
We create a local variable j, which is visible only in this for loop. j holds index of the string (=string[temp]), which we're processing. So, we're printing a character on position j (by using standard method "charAt" of String class, which returns character of given index of the string) and then increasing it by 2. So, this code will print every even character. For string "example", it will print "eape" (j=0, j=2, j=4, j=6).
System.out.print(" ");
Separating sequences with a space.
for(int j = 1; j<string[temp].length(); j = j+2){
System.out.print(string[temp].charAt(j));
}
System.out.println();
We're doing the same (creating index j, running though all characters of the string), but starting from "1", so it will print all odd characters of the string. For string "example", it will give you "xml" (j=1, j=3, j=5). and After this, it will end the string. I hope, it will help you to understand. :)
I can solve your the second question:
---> System.out.print(strE);-->At the bottom, the method is called( public void print(char s[]));
-->System.out.println(strE + " " + strO);-->At the bottom, the method is called (public void println(String x) )
For your first answer I am unable to answer you as I have no idea about how the compiler works, but I can answer your second question.
The reason why System.out.print(strE); System.out.print(" "); System.out.println(strO); works is because System.out.print(char[]) and System.out.println(char[]) automatically turn the char arrays into a readable string before printing it.
However, in the second case System.out.println(strE + " " + strO);, what you are doing is directly turning the char array into strings, which just prints the class and the hash code of the array object because the toString() method is not overriden in the array class. What you want to do is System.out.println(new String(strE) + " " + new String(strO));. It will give you the result you want.
import java.io.*;
import java.util.*;
public class Solution {
private static void f(String s) {
// TODO Auto-generated method stub
char c[]=s.toCharArray();
int i,j;
for (i = 0; i <c.length;i++){
System.out.print(c[i]);
i+=1;
}
System.out.print(" ");
for (j = 1; j<c.length;j++){
System.out.print(c[j]);
j+=1;
}
}
public static void main(String[] args){
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int s=sc.nextInt();
while(hasNext()){
//for loop for multiple strings as per the input
for(int m=0;m<= s;m++){
String s1=sc.next();
f(s1);
System.out.println();
}
}
}
}
I've solved this question in 2 ways & both are producing correct output.
Have a look & let me know if you've any problem.
Instead of using char array, you can use String
//char[] even = new char[10000];
String even = "";
Let's look at the code
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String s = scanner.next();
char[] array = s.toCharArray();
int count=0;
//char[] even = new char[10000];
//char[] odd = new char[10000];
String even = "";
String odd = "";
for(char ch : array){
if(count%2 == 0){
even = even + ch;
}else{
odd = odd + ch;
}
count++;
}
count = 0;
System.out.println(even + " " + odd);
}
Output:
hacker
hce akr
No need of extra char[] or String to store even & odd position characters, we can directly print them using appropriate condition.
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
String s = scanner.next();
char[] array = s.toCharArray();
int count=0;
for(char ch : array){
if(count%2 == 0){
System.out.print(ch);
}
count++;
}
count = 0;
System.out.print(" ");
for(char ch : array){
if(count%2 != 0){
System.out.print(ch);
}
count++;
}
count = 0;
}
Output:
hacker
hce akr
Try this:
public static void main(String[] args) {
System.out.println("Enter string to check:");
Scanner scan = new Scanner(System.in);
String T = scan.nextLine();
String even = "";
String odd = "";
for (int j = 0; j < T.length(); j++) {
if (j % 2 == 0) { //check the position of the alphabet by dividing it by 0
even += T.charAt(j);
} else {
odd += T.charAt(j);
}
}
System.out.println(even + " " + odd);
scan.close();
}
** JavaScript version **
function processData(input) {
for (let i = 1; i < input.length; i++) {
printOutput(input[i]);
}
}
function printOutput(input) {
var result = [];
input.length % 2 == 0 ? result[input.length / 2] = ' ': result[Math.ceil(input.length / 2)] = ' ';
for (let i = 0; i < input.length; i++) {
if (i % 2 == 0) {
result[i / 2] = input[i];
}
else {
result[Math.ceil(input.length / 2) + Math.ceil(i / 2)] = input[i];
}
}
console.log(result.join(''));
}
process.stdin.on("end", function () {
processData(_input.split('\n'));
});
import java.io. * ;
import java.util. * ;
public class Solution {
String myString;
public Solution(String myString) {
this.myString = myString;
int len = myString.length();
for (int j = 0; j < len; j++) {
if (j % 2 == 0) {
System.out.print(myString.charAt(j));
}
}
System.out.print(" ");
for (int j = 0; j < len; j++) {
if (j % 2 == 1) {
System.out.print(myString.charAt(j));
}
}
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System. in );
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
String word = sc.next();
Solution sol = new Solution(word);
System.out.println();
}
sc.close();
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int T;
T = s.nextInt();
String[] str = new String[T];
int i;
for(i=0;i<T;i++) {
str[i] = s.next();
}
for(i=0;i<T;i++) {
char[] even = new char[5000];
char[] odd = new char[5000];
int ev =0,od=0;
for(int j= 0;j< str[i].length();j++) {
if(j%2== 0) {
even[ev] = str[i].charAt(j);
ev++;
}else {
odd[od] = str[i].charAt(j);
od++;
}
}
String strEven = new String(even);
String strOdd = new String(odd);
System.out.print(strEven.trim());
System.out.print(" ");
System.out.println(strOdd.trim());
}
s.close();
}
}
I am sure that this will work You've forgotten to convert it to a string and also increase the size of the character array
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
int n= scan.nextInt();
for(int i=0;i<n;i++){
String s= scan.next();
int len= s.length();
StringBuffer str_e= new StringBuffer();
StringBuffer str_o= new StringBuffer();
for(int j=0;j<len;j++){
if(j%2==0)
str_e= str_e.append(s.charAt(j));
if(j%2==1)
str_o= str_o.append(s.charAt(j));
}
System.out.println(str_e+" "+str_o);
}
}
}
Try this:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner pp=new Scanner(System.in);
int n=pp.nextInt();
for(int i=0; i<n; i++)
{
String ip=pp.next();
String re1="",
re2="";
for(int j=0; j<ip.length(); j++)
{
if(j%2 == 0)
{
re1+= ip.charAt(j);
}
if(j%2 == 1)
{
re2+= ip.charAt(j);
}
}
System.out.print(re1+" "+re2);
System.out.println("");
}
}
}
public class PrintCharacters{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int noOfTestCases = sc.nextInt();
sc.nextLine();
String []inputStrings= new String[noOfTestCases];
for(int i=0;i<noOfTestCases;i++) {
inputStrings[i]=sc.nextLine();
}
for(String str: inputStrings) {
String even ="";
String odd ="";
for(int i=0;i<str.length();i++) {
if(i%2==0) {
even+=str.charAt(i);
}else {
odd+=str.charAt(i);
}
}
System.out.println(even+" "+odd);
}
sc.close();
}
}
Input:
2
Hacker
Rank
Output:
Hce akr
Rn ak
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
while(n>0) {
String str=scan.next();
for(int i=0;i<str.length();i++) {
if(i%2==0) {
System.out.print(str.charAt(i));
}
}
System.out.print(" ");
for(int i=0;i<str.length();i++) {
if(i%2==1) {
System.out.print(str.charAt(i));
}
}
n--;
System.out.println();
}
}
}
package jellyProblem;
import java.util.*;
public class jellyProblem {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
int studentNumbers = input.nextInt();
input.nextLine();
String [] name =new String [100];
int [] volume=new int[100];
while(true){
if (studentNumbers==0)
break ;
else
for(int i=0;i<studentNumbers;i++){
name[i]=input.next();
int length =input.nextInt();
int width =input.nextInt();
int height =input.nextInt();
System.out.printf("\n%s %d %d %d\n",name[i],length,width,height);
volume[i]=length*height*width;
}
int minimum=0,maximum=0;
for(int i=1;i<studentNumbers;++i){
if (volume[i]<volume[minimum])
minimum=i;
if (volume[i]>volume[maximum])
maximum=i;
}
if(volume[minimum]==volume[maximum])
System.out.println("\nno child lost his jelly\n");
else
System.out.printf("\n%s has lost jelly to %s.\n",name[minimum],name[maximum]);
studentNumbers = input.nextInt();
input.nextLine();
}
}
}
First request I don't know how to:
Prevent string duplicates in names[] array like
I want to stop array if characters of name[] is more than past (names[i].length<=10) it doesn't work with me
Maybe you can do it like this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int studentNumbers = input.nextInt();
input.nextLine();
List<String> names = new ArrayList<String>();
int[] volume = new int[100];
// clear all data to make it clean
names.clear();
while (true) {
if (studentNumbers == 0)
break;
else
for (int i = 0; i < studentNumbers; i++) {
String studentName = input.next();
// here is how prevent string duplicates in names[] array like
if (names.contains(studentName)) {
continue;
}
if (studentName.length() > 10) {
break;
}
names.add(studentName);
int length = input.nextInt();
int width = input.nextInt();
int height = input.nextInt();
System.out.printf("\n%s %d %d %d\n", names.get(i), length, width, height);
volume[i] = length * height * width;
}
int minimum = 0, maximum = 0;
for (int i = 1; i < studentNumbers; ++i) {
if (volume[i] < volume[minimum])
minimum = i;
if (volume[i] > volume[maximum])
maximum = i;
}
if (volume[minimum] == volume[maximum])
System.out.println("\nno child lost his jelly\n");
else
System.out.printf("\n%s has lost jelly to %s.\n", names.get(minimum), names.get(maximum));
studentNumbers = input.nextInt();
input.nextLine();
}
}
}
a. Instead of using an Array of string you can use an ArrayList. The ArrayList will give you the power to perform various function over the list of String. Incase you want to write your own method and only allow non duplicates to be inserted into the Array then u can iterate over the array and check whether you encounter the same value. eg.
String newName = input.nextLine();
boolean checkDuplicate = dupliacteFunction(newName,name);
boolean dupliacteFunction(String newName , String []nameArray) {
for(String nameValue : nameArray) {
if(newName .equals(nameValue))
return true;
}
else return false;
}
b. String newName = input.nextLine();
newName.length();// This will give u the size of the string being read.
Please try and implement these changes and then we can suggest further alternatives. Happy Coding!!!
To answer your first question, there is no real way to prevent duplicates in an array. I would use an ArrayList object. If it is absolutely impossible to use an ArrayList, you could create a method like this:
public static String[] removeDupes(String[] array){
ArrayList<String> uniqueItems = new ArrayList<String>();
for(String s : array){
if(uniqueItems.contains(s) == false)
uniqueItems.add(s);
}
array = uniqueItems.toArray(array);
return array;
}
And to answer your second question, I don't know what you mean by "stop array" but it seems like all you need is a simple if-statement with exactly the condition you described.
How do can I exit a loop if a non int value is entered?
Should I do this in the main class?
package testing;
//importing java scanner
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
//importing scanner for user input
Scanner input = new Scanner(System.in);
//variable for how many positions to shift indexes in array
int shift;
//Object for Shifter, passing 20 as parameter
Shifter numbers = new Shifter(20);
//Call Display method
numbers.display();
//how many positions to shift
System.out.print("\nYou want to shift how many positions? ");
//Assigning user input to shift variable
shift = input.nextLine();
numbers.shift();
}
Now the Shift Class:
package Testing;
import java.util.*;
public class Shifter
{
private int numbers[];
Shifter(int totalSize)
{
int index = 1;
numbers = new int[totalSize];
//Loop for assigning values to array indexes
for(int i= 0; i < data.length; i++)
{
data[i]= firstIndex;
firstIndex++;
}
}
public void shift(int position)
{
//method variable assigned value of pos parameter
int shiftNum = position;
//Array to hold new arrangement of elements
int dataHolder[] = new int[numbers.length];
**//I want to put a while loop here that will exit the loop when a letter is entered**
**//I tried using .isNaN but can't get it to work
while()
{
if(shiftNum > 0)
{
}
}
}
Is the code working? As per the specifications Scanner.nextLine returns a string.
So, if you change it to shift = input.nextInt();. That should serve the purpose
Have you tried this:
while (...) {
String inputString = "..";
try {
int i = Integer.parseInt(inputString); // try to parse the input string as an integer
} catch (NumberFormatException e) {
break; // not an integer, exiting loop
}
}
Or you may also be interested in Scanner.nextInt():
while (...) {
if (input.hasNextInt()) {
int i = input.nextInt();
} else {
break; // not an integer, exiting loop
}
}
I am having trouble understanding how to remove a letter from a char array here is my code
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String [] args)
{
start();
}
public static void start()
{
Scanner scan = new Scanner(System.in);
Random rand = new Random();
String [] Words = {"Dog","cat","Food","Bacon","Turkey","hood","poo","Good","look"};
String RandomWord = Words[rand.nextInt(Words.length)];
char [] array = RandomWord.toCharArray();
boolean [] parrallelArray = new boolean[array.length];
int i = 0;
int placeholder = 0;
System.out.println(findUniqueLetters(array));
char input = 0;
while(i<findUniqueLetters(array)){
i++;
System.out.println("You have a "+RandomWord.length()+" Word "+RandomWord);
System.out.println("Guess a letter : ");
input = scan.next().charAt(0);
for(int j = placeholder; j<array.length;j++){
if(input == array[j]){
j++;
placeholder = j;
System.out.println("You got it right");
break;
}
else if(!(input ==array[j])){
j++;
placeholder = j;
System.out.println("You got it wrong");
break;
}
}
}
System.out.println("You have wasted all your tries!");
}
public static int findUniqueLetters(char [] a){
int Unique = 1;
for(int i = 1; i<a.length;i++){
if(!(a[i] == a[i-1])){
Unique++;
}
}
return Unique;
}
}
Is there another way to do this or is deleting it the only way to do this?
I have tried to switch the repeated letter in the array with the non repeated one in the array but that only works for some words.
Please use a Set. more here - > http://docs.oracle.com/javase/7/docs/api/java/util/Set.html