I'm doing an assignment and I am done. This is a simple program that prints out pyramids of chars. However, I can't figure out why the program prints a newline when I never specified it with some input, even if it's meant to: https://i.imgur.com/gPs5oC5.png
Why do I have to have an extra newline when printing the pyramid upside down? Where is the newline printed?
import java.util.Scanner;
public class Test23 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean state = true;
String messageL = "Length: ";
String messageD = "Position: ";
String messageS = "Shutdown!";
while(state) {
int limit = 0;
int degree;
System.out.print(messageL);
int length = input.nextInt();
while ((length < 1 && length == -1) || length > 26) {
if (length == -1 ) {
System.out.println(messageS + "\n");
state = false;
break;
} else {
System.out.print(messageL);
length = input.nextInt();
}
}
if (!state)
break;
System.out.print(messageD);
degree = input.nextInt();
while((degree > 1) || (degree < 0)) {
System.out.print(messageD);
degree = input.nextInt();
}
if (degree == 0)
//No newline is needed here for some reason.
length++;
else if (degree == 1)
limit = length;
//New line here for the pyramids to print symmetrically.
//System.out.println("");
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
System.out.print(letter);
}
if (degree == 0)
limit++;
else if (degree == 1)
limit--;
System.out.println("");
}
System.out.println("");
}
}
}
Small java program prints invisible newline?
In your program the last System.out.println(""); causes an extra line at the end of your program, i.e while(state) is true at the end, So either you comment the print statement or make your state=false at end.
while(state) {
...
System.out.println("");
}
The most inner loop won't run if the input is 0. limit will be 0, and hence the loop condition is false. As of this it will print en empty line, proceeding to add 1 too limit and then print chars.
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
Related
Why is this code not ending. I have given the required string input and k input, but I don't know why it is not ending. Please provide some insights.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int k = sc.nextInt();
ArrayList<Character> l = new ArrayList<>();
for(int i=0; i<s.length(); i++){
l.add(s.charAt(i));
}
int count = 0;
int first = 0;
int last = s.length() - 1;
while(first < last){
if(l.get(first) + l.get(first + 1) == k || l.get(first) == k){
count++;
}
}
if(count % 2 == 0){
System.out.println("B");
}
System.out.println("A");
}
}
Your input is fine for now. The issue is first and last stays same throughout the iteration. Add first++; in your while loop, so that at each iteration first value increments.
while(first < last){
if(l.get(first) + l.get(first + 1) == k || l.get(first) == k){
count++;
}
first++;
}
Heres my code. I'm not sure whats wrong. My project is to create a program that checks if a word is a palindrome.
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
// Open Scanner
Scanner input = new Scanner(System.in);
// Prompt User for word
System.out.println("Enter word to check if it is a Palindrome:");
// Scan in the word
String word = input.nextLine();
int a = 0; // used to extract word from array (small)
int b = 0; // used to extract word from array (large)
int c = 0; // used to stop when
int d = (word.length());
int e = d / 2;
int f = e - 2;
int x = word.length(); // set cap of array pulling
char[] array = word.toCharArray(); // create array of chars
if (array[a] == array[x] && c != f) {
a++;
x--;
c++;
} else {
b = 1;
}
if (b == 1) {
System.out.println("This word is not a Palindrome!");
} else if (b == 0) {
System.out.println("This word is a Palindrome!");
}
}
}
The error is at the
if (array[a] == array[x] && c!=f)
I'm not exactly sure what went wrong but when you put in a non-palindrome it skips over. I'd be more than glad to have some advice as to what to do in this situation.
Because arrays are 0-based, the index of the last entry is length -1.
int x = word.length() - 1
You are also missing a loop for checking all the characters in a word. And finally, you seem to have a lot of redundant variables. Here's how you could fix your code:
boolean isPalindrome = true;
for (int n = 0; n < array.length / 2; n++){
if (array[n] != array[array.length - n - 1]) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println("This word is a Palindrome!");
} else {
System.out.println("This word is not a Palindrome!");
}
I need to find the last digit in a array and see if it is equal to zero. Here is the code I'm using;
import java.util.Scanner;
public class NrOccurrence
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the integers between 1 and 100: ");
int[] numbers = new int[100], times = new int[100];
boolean zero = false;
while (zero == false)
{
for (int a = 0; a <= numbers.length; a++)
{
numbers[a] = scan.nextInt();
times[a]++;
if (numbers.equals(0))
{
zero = true;
}
}
}
for (int b = 0; b <= numbers.length; b++)
{
System.out.println(numbers[b] + " occurs " + times[b] + " times");
}
scan.close();
}
}
Create a method like this:
private boolean isLastItemZero(int[] numbers)
{
boolean isLastItemZero = false;
if ((numbers != null) && (numbers.length > 0))
{
isLastItemZero = numbers[numbers.length - 1] == 0;
}
return isLastItemZero;
}
And call it once you're done reading in all of the numbers from the user.
First of all for (int a = 0; a <= numbers.length; a++) will give youIndexOutOfBoundsException .Java uses 0 bases indexing which means that an array of size n has indices up to and including n-1. Change it tofor (int a = 0; a < numbers.length; a++) . Same thing here for (int b = 0; b <= numbers.length; b++)
Second i am not sure what you are trying to check here :
if (numbers.equals(0))
{
zero = true;
}
but you could simply do :
if(numbers[i] == 0);
Now if you wanna check if the last element in the array is 0you can simply do:
if(numbers[numbers.length - 1] == 0)
//do something
By definition, if the remainder of a number divided by 10 is 0, then the last digit must be 0. So you just need;
if(numbers[i] % 10 == 0) { zero = true; }
Hope this helps.
I am trying to finish my assignment but I can't seem to find the bug in my code. It is not a compiler error, and I have been looking at it for hours.
This code is for a game called Mastermind. These are the guidelines (a bit long, I know, but all necessary info for the assignment):
Computer chooses a random 4 digit number, and no digit may repeat itself. (ex: 0462, 2930, 6103 are valid numbers)
The user's goal is to try and guess the computer's chosen number
Once the user makes a guess, the computer will tell the user how class that guess was by giving the following information:
The number of digits matched perfectly (are in the right place)
The number of digits that are off place
When you scan the input from the user, use a String to store it. Your
program must have 4 methods in addition to the main method:
One method named isValidNumber that checks if a given String corresponds to a valid 4 digit number.
One method named perfectMatches that returns the number of perfect matches between two Strings that represent valid 4 digit numbers.
One method named offPlaceMatches that returns the number of ‘off place’ matches between two Strings that represent valid 4 digit
numbers.
One method named generateRandomValidNumber that returns a String that represents a random valid 4 digit number.
Hint: Generate a random 4 digit number by generating a random single
digit 4 times and concatenating them. Then using your isValidNumber
method, check if this String you created is valid. If it is not,
repeat the first part and pick 4 new random digits.
This is my code:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//print welcome, what 4 digit number do you guess...
System.out.println("Welcome to Mastermind.");
System.out.println("I have a 4 digit number in mind. Can you guess it?");
System.out.println("");
System.out.println("What is your guess?");
//string guess is number that is scanned
String guess = input.nextLine();
String validNumber = generateValidNumber();
System.out.print("Perfect matches: " + perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
while(!(perfectMatches(guess, validNumber) == 4)) {
System.out.println("");
System.out.println("What is your guess?");
guess = input.nextLine();
validNumber = generateValidNumber();
System.out.print("Perfect matches: " + perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
}
System.out.println("Yes! You guessed my number correctly. Well done.");
}
static boolean isValidNumber(String number) {
if(number.length() != 4) {
return false; }
char[] numberArray = new char[4];
for (int i = 0; i < 4; i++) {
numberArray[i] = number.charAt(i);
if(!((number.charAt(i) <= '9') && (number.charAt(i) >= '0'))) {
return false;
}
}
for (int i = 0; i < 4; i++) {
char c = numberArray[i];
int count = 0;
for(int j = 0; j < 4; j++)
if(numberArray[j] == c)
count++;
if(count > 1) {
return false;
}
}
return true;
}
static int perfectMatches(String one, String two) {
int counter = 0;
for(int i = 0; i < one.length(); i++) {
if(one.charAt(i) == two.charAt(i)) {
counter++;
}
}
return counter;
}
static int offPlaceMatches(String one, String two) {
int counter = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(i == 0)
continue;
if(one.charAt(j) == two.charAt(i)) {
counter++;
}
if(j == i -1) {
i++;
}
}
}
return counter;
}
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = "";
while(!validNumber) {
for(int i = 0; i < 4; i++) {
char c = (char) (int) (Math.random() * (9));
newNumber = newNumber + c;
}
if(isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
}
There's a problem in the generateValidNumber method.
You are not re-initializing newNumber when you try to find a new random number.
Changing it to the following function should result in the successful execution of the program. Also, multiply the random number with 10 to get an number in the range [0.0, 10.0) (0 included and 10 excluded)
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = null;
while(!validNumber) {
// add this line
newNumber = "";
for(int i = 0; i < 4; i++) {
char c = (char) ('0' + (Math.random() * 10));
newNumber = newNumber + c;
}
if(isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
But there are a few logical errors in the code. For e.g., you are generating a new number everytime a user guesses an invalid number.
Update:
I made a few changes to your code. This should help you get going.
import java.util.Scanner;
public class MastremindString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// print welcome, what 4 digit number do you guess...
System.out.println("Welcome to Mastermind.");
System.out
.println("I have a 4 digit number in mind. Can you guess it?");
System.out.println("");
System.out.println("What is your guess?");
// string guess is number that is scanned
String guess = input.nextLine();
String validNumber = generateValidNumber();
System.out.print("Perfect matches: "
+ perfectMatches(guess, validNumber));
System.out.println("off place: " + offPlaceMatches(guess, validNumber));
while (!(perfectMatches(guess, validNumber) == 4)) {
System.out.println("");
System.out.println("What is your guess?");
guess = input.nextLine();
System.out.print("Perfect matches: "
+ perfectMatches(guess, validNumber));
System.out.println("off place: "
+ offPlaceMatches(guess, validNumber));
}
System.out.println("Yes! You guessed my number correctly. Well done.");
}
static boolean isValidNumber(String number) {
if (number.length() != 4) {
return false;
}
char[] numberArray = new char[4];
for (int i = 0; i < 4; i++) {
numberArray[i] = number.charAt(i);
if (!((number.charAt(i) <= '9') && (number.charAt(i) >= '0'))) {
return false;
}
}
for (int i = 0; i < 4; i++) {
char c = numberArray[i];
int count = 0;
for (int j = 0; j < 4; j++)
if (numberArray[j] == c)
count++;
if (count > 1) {
return false;
}
}
return true;
}
static int perfectMatches(String one, String two) {
int counter = 0;
for (int i = 0; i < one.length(); i++) {
if (one.charAt(i) == two.charAt(i)) {
counter++;
}
}
return counter;
}
static int offPlaceMatches(String one, String two) {
int counter = 0;
for (int i = 0; i < one.length(); i++) {
for (int j = 0; j < two.length(); j++) {
if (one.charAt(j) == two.charAt(i) && i != j) {
counter++;
}
}
}
return counter;
}
static String generateValidNumber() {
boolean validNumber = false;
String newNumber = "";
while (!validNumber) {
newNumber = "";
for (int i = 0; i < 4; i++) {
char c = (char) ('0' + (Math.random() * 10));
newNumber = newNumber + c;
}
if (isValidNumber(newNumber))
validNumber = true;
}
return newNumber;
}
}
It appears that you are generating a new number on every cycle. The best way to fix this is to not assign to the validNumber variable within main(...) on every loop.
Since you get to the point of "What is your guess?" and you enter a number, but then nothing happens (which presumably means you do not get past the two lines following the first guess=input.nextLine(); call), the function to check first is the generateValidNumber(); function. Second, check your perfectMatches(...); function. You can add System.out.println("blah"); calls to see how far your code gets (as a very crude debugging tool).
I'm assuming you're using Eclipse and in an introductory programming course. An important subject often overlooked in programming courses is how to use a debugger to help you troubleshoot problems. If any of your classmates, lab assistants, or fellow students further along in your major can take 15-30 minutes to sit down and show you how to use the debugger, it will help you through the rest of your programming career.
If not, there are a lot of tutorials you can follow to get familiar with Eclipse's debugger.
To start off, double-click along the left of your code, usually just left of the line numbers. This will add a break point, which will pause your program when it reaches. Add a break point at each of your methods besides main and make sure that all the methods you think should be called are actually called.
When your program is at a break point, you can also take a look at the value of variables in the "Variables" view. If one of them has an unexpected value, you may have found your culprit.
There is a resume button you'll have to hit to resume program execution when you're done at a given break point. It should be next to the Pause and Stop buttons in the top bar by default, and is easy to confuse with the Run button.
First: You never call isValidNumber to check if the user's input is valid. You should call this method and if the number is invalid, the program should terminate or prompt the user for a new number
I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.
public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("enter integers between 1 and 100: ");
int[] num = new int[100];
int data = input.nextInt();
while ((data = input.nextInt()) != 0) {
num[data]++;
}
for (int i = 1; i < 100; ++i) {
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
}
You need two separate loops: the first to gather the information, and the second to print the results:
int data = 0;
while ((data = input.nextInt()) != 0)
{
num[data]++;
}
for (int i = 0; i < 100; ++i)
{
if (num[i] != 0) { /* print num[i] */ }
}
Just loop over the num array after your while loop to print the counts.
for (int index = 0; index < num.length; index++) {
if (num[index] != 0)
System.out.println(data + " occurs " + num[data] + " time(s).");
}
You are printing an output every time an integer is read. Your program is behaving as expected.
To get what you want, you need to scan all the input before you produce any output.
Try this instead:
while (data != 0){
data = input.nextInt();
num[data]++;
}
for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.
while (input.hasNextInt()){
num[input.nextInt()]++;
}
it's so simple
int data = 0;
int[] num = new int[100];
int i = 0;
while (i < num.length) {
if ((data = input.nextInt()) == 0)
break;
num[i] = data;
i++;
}
for (i = 0; i < 100; ++i) {
int times = 0;
if (num[i] != 0) {
for (int j = 0; j < 100; j++) {
if (num[j] == 0) {
break;
} else if (num[i] == num[j]) {
times++;
}
}
System.out.println(num[i] + " occurs " + times + " times ");
} else {
break;
}
}